Просмотр исходного кода

Run ES modules, fetch and Web Storage in the browser

Gets the Cloudron dashboard (a Vite/Vue 3 app) through its OIDC login:

- <script type="module"> runs through QuickJS's module loader; imports
  load synchronously via the helpers, modulepreload chunks are fetched in
  parallel first, and unhandled promise rejections are reported.
- js_prelude.js adds fetch/XHR, URL/URLSearchParams, TextEncoder, btoa,
  Web Storage (persisted per origin in /share), crypto.subtle SHA-256,
  observers, DOM classes and common Element methods.
- The curl helpers share one cookie jar (/share/bcookies) and accept any
  method/content type; empty-body form POSTs stay POSTs.
- uhttp percent-encodes unsafe path bytes; URL normalization no longer
  collapses "//" inside query strings (broke redirect_uri).
- location.replace/assign/reload navigate; the script budget excludes
  network waits; data-block <script> text is kept for textContent.
- Script-built inputs get their type/placeholder, flex-item controls are
  drawn, fields stretch in flex columns and clip/scroll their text, and
  clicks reach plain elements with listeners.
Johannes Zellner 1 неделя назад
Родитель
Сommit
8513cec844
15 измененных файлов с 2342 добавлено и 77 удалено
  1. 53 6
      AGENTS.md
  2. 4 1
      Makefile
  3. 510 37
      browser.c
  4. 68 7
      browser_html.c
  5. 1 0
      browser_html.h
  6. 2 2
      docs/network.html
  7. 0 0
      docs/userland.html
  8. 248 10
      js_browser.c
  9. 25 0
      js_browser.h
  10. 155 0
      js_mu.c
  11. 12 0
      js_mu.h
  12. 8 0
      js_prelude.S
  13. 1132 0
      js_prelude.js
  14. 76 7
      ucmd_curl.c
  15. 48 7
      uhttp.c

+ 53 - 6
AGENTS.md

@@ -1155,7 +1155,9 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   copy, then `BROWSER` on `root.img`/IDE/SATA fat mounts.  The launcher
   forwards its argument and cwd.
   `uhttp.c/h` is the shared ring-3 HTTP client extracted from curl: URL
-  parsing/resolution, redirects, chunked decoding, timeouts and TLS; curl,
+  parsing/resolution (unsafe path bytes are percent-encoded; path
+  normalization stops at `?`/`#`), redirects, chunked decoding, timeouts
+  and TLS; curl,
   the browser and chat use it.  `browser_html.c/h` is a tolerant HTML tree + the
   CSS subset: external `<link rel=stylesheet>` sheets (in document order,
   inline `<style>` last), one selector engine shared by the cascade,
@@ -1281,7 +1283,7 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   arena, so a large image no longer reserves a fixed 24 MB.  `<script>`
   blocks are collected by `browser_html.c`; inline bodies run directly and
   `<script src>` bodies are fetched through the same local/network path as
-  pages and CSS (512 KB cap), in document order, through the vendored QuickJS
+  pages and CSS (2 MB cap), in document order, through the vendored QuickJS
   engine (`third_party/quickjs/`, 2026-06-04, ES2025: classes, arrow
   functions, `let`/`const`, template literals, destructuring, spread,
   async/await, Promise, Map/Set, BigInt, optional chaining; linked only
@@ -1329,7 +1331,41 @@ it to `0x7E00`.  The kernel region itself only has one wall (`_end` below
   libc math/time layers.  The parsed page is painted before scripts are
   fetched and run, and remote `<script src>` bodies are cached under
   `/share/bjs-*` for the current boot.  Classic scripts run sloppy by
-  default (`"use strict"` and private class fields work).  `cloneNode`
+  default (`"use strict"` and private class fields work).
+  `<script type="module">` runs as an ES module (`js_browser_run_module`,
+  `js_ploadmodule`): QuickJS's module loader resolves each specifier to an
+  absolute URL (module name = URL, so every module is evaluated once) and
+  loads it synchronously through `host.load_script` (the boot script cache,
+  else one blocking helper fetch with input pumping off, since the loader
+  runs inside JavaScript); `import()` and `import.meta.url` work, `nomodule`
+  scripts are skipped, and the page's `<link rel="modulepreload">` targets
+  are downloaded on all helpers in parallel into the script cache before any
+  script runs.  The 20 s budget restarts after every blocking fetch, so it
+  measures script time, not the network.  Unhandled promise rejections are
+  reported (`JS_SetHostPromiseRejectionTracker`), as Vite apps boot from an
+  async IIFE.  `js_prelude.js` (embedded by `js_prelude.S`, run once per
+  state before the page's scripts) implements the Web APIs in JavaScript on
+  three C primitives (`__nb_http`, `__nb_storage`, `__nb_resolve`):
+  `fetch`/`Request`/`Response`/`Headers`, `XMLHttpRequest`, `URL`/
+  `URLSearchParams`, `TextEncoder`/`TextDecoder`, `btoa`/`atob`, `Blob`/
+  `File`/`FormData` (urlencoded only), `AbortController`,
+  `localStorage`/`sessionStorage` (a Proxy, so `localStorage.token = x`
+  works), `crypto.getRandomValues`/`randomUUID`/`subtle.digest("SHA-256")`
+  (PKCE), inert `MutationObserver`/`ResizeObserver`/`IntersectionObserver`,
+  `instanceof`-able DOM classes (`HTMLElement`, `Node`, ...), and Element
+  methods (`closest`, `append`/`prepend`/`before`/`after`, `replaceWith`,
+  `insertAdjacentHTML`, `toggleAttribute`, `*AttributeNS`) on the node
+  wrappers' own prototype.  fetch()/XHR are synchronous inside a Promise:
+  `js_host_http` submits `X <method> <len> <ctype> <url>` to a helper and
+  returns the status and body whatever the HTTP status (2 MB response, 16 KB
+  request body).  Web Storage is stored in `/share/bls<origin-hash>`
+  (local, per boot) and `/share/bss<pid>-<origin-hash>` (session, per
+  window), outside the page heap that navigation resets.  `console.*` print
+  Error stacks.  `location.assign`/`replace`/`reload` navigate.  The
+  Cloudron dashboard (`my.<domain>`: a Vite/Vue 3 app, 12 modules / 3.5 MB)
+  boots, builds its PKCE request, and its OIDC login form renders, submits
+  through `fetch()` with the interaction cookie and shows the server's
+  verdict; the `authcallback.html` code exchange runs the same way.  `cloneNode`
   copies attributes to the clone (it used to stamp them onto the previous
   node, which broke every `ng-repeat`).
   `addEventListener`/`removeEventListener`/`dispatchEvent` dispatch real DOM
@@ -2082,9 +2118,20 @@ and the WM falls back to polling (`io_keyboard_irq_masked()`).
     `once`/`passive` options.  POST uses
     `application/x-www-form-urlencoded`; a redirected POST follows as GET,
     and `enctype=multipart/form-data` plus file inputs are unsupported.
-    Also missing: `type="module"`,
-    `defer`/`async`, `MutationObserver`/`IntersectionObserver`,
-    `XMLHttpRequest`/`fetch`, `DOMParser`, canvas/2D contexts, user-state
+    ES modules, `fetch`/`XMLHttpRequest` and Web Storage work (see the
+    browser bullet) with these limits: fetch()/XHR block the page while they
+    run (no streaming bodies, no upload progress), `FormData` is sent
+    urlencoded (no multipart/files), only `Content-Type` is forwarded from
+    request headers, response headers other than `Content-Type` are not
+    exposed, bodies are text (Latin-1/UTF-8, no binary `arrayBuffer`),
+    CORS is not enforced, and the observers never fire.  Module loading is
+    sequential apart from the modulepreload pass.  `crypto` entropy is the
+    weak Math.random/clock mix (fine for PKCE nonces, like the TLS DRBG).
+    On QEMU's NE2000 the four parallel module downloads can overrun its
+    small RX ring and stall TLS handshakes into a 10 s timeout; use e1000.
+    Also missing: `defer`/`async` ordering, `DOMParser`/
+    `document.implementation.createDocument` (DOMPurify throws, so the
+    Cloudron login footer is not rendered), canvas/2D contexts, user-state
     pseudo-classes (`:hover`, `:focus`, ...), `:nth-child(... of S)` and
     pseudo-elements other than `::before`/`::after`; generated content is
     text only (no box, background, counters or `url()` images, and

+ 4 - 1
Makefile

@@ -865,7 +865,10 @@ js_browser.o: js_browser.c js_browser.h js_mu.h browser_html.h ucmd_lib.h \
 browser.o: browser.c ucmd_lib.h syscall.h wm_abi.h ngui.h browser_html.h svg_raster.h js_browser.h uhttp.h img.h inflate.h $(LIBC_HEADERS)
 	$(CC) $(CFLAGS) -Os $(SECTION_CFLAGS) -Ilibc/include -o $@ $<
 
-browser.elf: browser.o browser_html.o svg_raster.o js_browser.o uhttp.o uhttp_cookie.o ngui.o font_8x16.o $(UFONT_OBJS) $(IMGLIB_OBJS) inflate.o $(TLSLIB_OBJS) js_mu.o $(QJS_OBJS) ucmd.ld libc.a
+js_prelude.o: js_prelude.S js_prelude.js
+	$(AS) $(ASFLAGS) -o $@ $<
+
+browser.elf: browser.o browser_html.o svg_raster.o js_browser.o js_prelude.o uhttp.o uhttp_cookie.o ngui.o font_8x16.o $(UFONT_OBJS) $(IMGLIB_OBJS) inflate.o $(TLSLIB_OBJS) js_mu.o $(QJS_OBJS) ucmd.ld libc.a
 	$(LD) -T ucmd.ld -z max-page-size=0x100 --gc-sections -nostdlib -m elf_i386 -o $@ $(filter-out ucmd.ld,$^)
 	$(OBJCOPY) --strip-all $@ $@
 

+ 510 - 37
browser.c

@@ -51,14 +51,16 @@ static unsigned int decode_arena_size;
 #define BR_IMG_JOB_TIMEOUT_MS 30000u
 #define BR_CSS_MAX      (832u * 1024u)
 #define BR_CSS_COMP_MAX (192u * 1024u)
-#define BR_SCRIPT_MAX   (512u * 1024u)
+/* Scripts and ES modules: Vite bundles reach ~1.7 MB (the Cloudron
+ * dashboard's main chunk); the helper's FETCH_MAX is the same 2 MB. */
+#define BR_SCRIPT_MAX   (2u * 1024u * 1024u)
 #define FETCH_ABORT     (-2)
 /* Session cache for remote stylesheets (per launch; cleared at startup). */
 #define CSS_CACHE_MAX      16
 #define CSS_CACHE_FILE_MAX (256u * 1024u)
 #define CSS_CACHE_PREFIX   "bcss-"
-#define SCRIPT_CACHE_MAX      16
-#define SCRIPT_CACHE_FILE_MAX (512u * 1024u)
+#define SCRIPT_CACHE_MAX      24
+#define SCRIPT_CACHE_FILE_MAX BR_SCRIPT_MAX
 #define SCRIPT_CACHE_PREFIX   "bjs-"
 #define BR_MAX_SHEETS   6
 #define BR_HISTORY      16
@@ -164,6 +166,9 @@ static char pending_url[BR_URL_MAX];
 #define BR_POST_MAX 4096
 static char pending_post[BR_POST_MAX];
 static unsigned int pending_post_len;
+/* The pending navigation is a POST even when its body is empty (a form
+ * without fields, e.g. the OIDC consent auto-submit). */
+static int pending_post_is;
 static unsigned int pending_action;
 static int cancel_fetch;
 static int quit;
@@ -1163,9 +1168,25 @@ static int fetch_worker_read_body(struct fetch_worker *w,
 				  int *truncated, char *err,
 				  unsigned int errcap);
 static void fetch_workers_stop_all(void);
+static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
+				   unsigned int cap, const char *method,
+				   const char *ctype, const char *post,
+				   unsigned int post_len, unsigned int node,
+				   int bg, char *err, unsigned int errcap);
 static int script_cache_has(const char *url);
 static void script_cache_put(const char *url, const unsigned char *data,
 			     unsigned int len);
+static unsigned int script_cache_hash(const char *s);
+static int fetch_worker_poll(struct fetch_worker *w, char *err,
+			     unsigned int errcap);
+static void fetch_workers_cancel_busy(void);
+static void worker_wait_ui(void);
+static int fetch_worker_status(const struct fetch_worker *w);
+
+/* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
+ * module load: the wait must not pump input, or a click would dispatch DOM
+ * events into the middle of the running script. */
+static int fetch_wait_passive;
 
 static void script_error(const char *what, const char *url, const char *why)
 {
@@ -1184,6 +1205,206 @@ static void script_error(const char *what, const char *url, const char *why)
 	js_host_report(msg);
 }
 
+/* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
+
+/* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
+ * body (FETCH_POST_MAX in ucmd_curl.c). */
+#define JS_HTTP_MAX      (2u * 1024u * 1024u)
+#define JS_HTTP_POST_MAX (16u * 1024u)
+
+/* struct fetch_meta / fetch_worker internals come later in the file. */
+static int js_worker_http(const char *method, const char *url,
+			  const char *ctype, const char *body,
+			  unsigned int body_len, struct js_http_resp *r,
+			  char *err, int errcap);
+
+static int js_host_http(const char *method, const char *url,
+			const char *ctype, const char *body,
+			unsigned int body_len, struct js_http_resp *r,
+			char *err, int errcap)
+{
+	if (pending_action) {
+		s_copy(err, "page is navigating", (unsigned int)errcap);
+		return -1;
+	}
+	if (url[0] == '/') {
+		/* Local file: GET only. */
+		unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
+		int rv;
+
+		if (!buf) {
+			s_copy(err, "out of memory", (unsigned int)errcap);
+			return -1;
+		}
+		rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
+				(int)JS_HTTP_MAX);
+		r->status = rv < 0 ? 404 : 200;
+		r->len = rv < 0 ? 0 : (unsigned int)rv;
+		buf[r->len] = '\0';
+		r->body = (char *)buf;
+		s_copy(r->url, url, sizeof(r->url));
+		if (contains_ci(url, ".json"))
+			s_copy(r->ctype, "application/json", sizeof(r->ctype));
+		return 0;
+	}
+	if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
+		s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
+		return -1;
+	}
+	if (body_len > JS_HTTP_POST_MAX) {
+		s_copy(err, "request body too large", (unsigned int)errcap);
+		return -1;
+	}
+	return js_worker_http(method, url, ctype, body, body_len, r, err,
+			      errcap);
+}
+
+/* Module source for the engine's loader: the boot script cache first, then
+ * one blocking fetch with input pumping disabled (the loader runs inside
+ * JavaScript). */
+static char *js_host_load_script(const char *url, unsigned int *len)
+{
+	unsigned char *data = 0;
+	char err[64];
+	int rv;
+
+	fetch_wait_passive++;
+	set_status("Loading module...", 0, 0);
+	rv = fetch_script_text(url, &data, len, err, sizeof(err));
+	fetch_wait_passive--;
+	if (rv != 0) {
+		script_error("Cannot load module", url,
+			     rv == FETCH_ABORT ? "navigation" : err);
+		return 0;
+	}
+	return (char *)data;
+}
+
+/* Web Storage lives in /share, outside the page heap that every navigation
+ * resets: localStorage per origin for the boot, sessionStorage per origin
+ * and browser window. */
+static void js_storage_path(int kind, char *out, unsigned int cap)
+{
+	char origin[160];
+	unsigned int n = 0, i = 0, slashes = 0;
+
+	while (page_url[i] && i + 1 < sizeof(origin)) {
+		if (page_url[i] == '/' && ++slashes == 3)
+			break;
+		origin[i] = page_url[i];
+		i++;
+	}
+	origin[i] = '\0';
+	s_append(out, &n, kind ? "/share/bss" : "/share/bls", cap);
+	if (kind) {
+		s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
+		s_append(out, &n, "-", cap);
+	}
+	s_append_dec(out, &n, script_cache_hash(origin), cap);
+}
+
+static int js_host_storage(int kind, const char *set, char *out, int cap)
+{
+	char path[48];
+	int rv;
+
+	js_storage_path(kind, path, sizeof(path));
+	if (set) {
+		if (!set[0] || !strcmp(set, "{}")) {
+			u_syscall1(SYS_UNLINK, (int)path);
+			return 0;
+		}
+		return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
+				  (int)strlen(set)) < 0 ? -1 : 0;
+	}
+	rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
+	if (rv < 0)
+		return -1;
+	out[rv] = '\0';
+	return rv;
+}
+
+/* <link rel="modulepreload">: download the page's module graph on all
+ * helpers at once into the boot script cache, before any script runs.  The
+ * engine's module loader is sequential (one blocking fetch per import), so
+ * without this a Vite app with a dozen chunks pays every round trip in a
+ * row.  Failures are ignored; the loader fetches what is missing. */
+#define MODULE_PRELOAD_MAX 24
+
+static void prefetch_module_preloads(void)
+{
+	static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
+	struct fetch_worker *slot[MODULE_PRELOAD_MAX];
+	unsigned int count = 0, next = 0, done = 0, i;
+	char err[64];
+
+	for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
+		struct br_node *nd = &doc.nodes[i];
+		const char *rel, *href;
+
+		if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
+			continue;
+		rel = br_rel(&doc, i);
+		href = br_href(&doc, i);
+		if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
+			continue;
+		if (resolve_link(page_url, href, urls[count],
+				 sizeof(urls[count])) != 0 ||
+		    urls[count][0] == '/' || script_cache_has(urls[count]))
+			continue;
+		slot[count++] = 0;
+	}
+	if (!count)
+		return;
+	set_status("Loading modules...", 0, 0);
+	while (done < count) {
+		struct fetch_worker *w;
+
+		while (next < count && (w = fetch_worker_alloc()) != 0) {
+			if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
+						0, 0, 0, err,
+						sizeof(err)) != 0) {
+				fetch_worker_release(w);
+				done++;
+			} else {
+				slot[next] = w;
+			}
+			next++;
+		}
+		worker_wait_ui();
+		if (cancel_fetch || pending_action) {
+			fetch_workers_cancel_busy();
+			return;
+		}
+		for (i = 0; i < next; i++) {
+			unsigned char *body;
+			int rv, tr = 0;
+
+			if (!slot[i])
+				continue;
+			rv = fetch_worker_poll(slot[i], err, sizeof(err));
+			if (rv == 0)
+				continue;
+			body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
+			       (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
+			if (body) {
+				rv = fetch_worker_read_body(slot[i], body,
+					BR_SCRIPT_MAX, image_io_buf,
+					BR_PAGE_COMP_MAX, &tr, err,
+					sizeof(err));
+				if (rv > 0 && !tr)
+					script_cache_put(urls[i], body,
+							 (unsigned int)rv);
+				free(body);
+			}
+			fetch_worker_release(slot[i]);
+			slot[i] = 0;
+			done++;
+		}
+		u_sleep_ms(10);
+	}
+}
+
 /* Script prefetch state: one entry per <script> block.  Remote bodies are
  * submitted to helper workers ahead of time, but scripts still execute in
  * document order. */
@@ -1248,6 +1469,9 @@ static void run_page_scripts(void)
 	host.form_reset = js_host_form_reset;
 	host.click = js_host_click;
 	host.computed = js_host_computed;
+	host.http = js_host_http;
+	host.load_script = js_host_load_script;
+	host.storage = js_host_storage;
 	host.page_url = page_url;
 	host.width = ui.w;
 	host.height = ui.h;
@@ -1255,6 +1479,7 @@ static void run_page_scripts(void)
 		js_host_status("JavaScript: out of memory", 1);
 		return;
 	}
+	prefetch_module_preloads();
 
 	for (i = 0; i < doc.nscripts; i++) {
 		struct br_script *script = &doc.scripts[i];
@@ -1297,7 +1522,21 @@ static void run_page_scripts(void)
 			for (k = 0; k < len; k++)
 				src[k] = doc.script_src[off + k];
 			src[len] = '\0';
-			js_browser_run(src, page_url);
+			if (script->module) {
+				/* A distinct module name per inline module
+				 * (QuickJS registers modules by name); the
+				 * fragment keeps relative imports resolving
+				 * against the page. */
+				char mname[BR_URL_MAX + 16];
+				unsigned int mn = 0;
+
+				s_append(mname, &mn, page_url, sizeof(mname));
+				s_append(mname, &mn, "#module", sizeof(mname));
+				s_append_dec(mname, &mn, i, sizeof(mname));
+				js_browser_run_module(src, mname);
+			} else {
+				js_browser_run(src, page_url);
+			}
 			free(src);
 		} else if (script->src_off) {
 			const char *src_attr = doc.attrs + script->src_off;
@@ -1324,11 +1563,17 @@ static void run_page_scripts(void)
 						     script_urls[i], err);
 					continue;
 				}
-				js_browser_run((const char *)data,
-					       script_urls[i]);
+				if (script->module)
+					js_browser_run_module(
+						(const char *)data,
+						script_urls[i]);
+				else
+					js_browser_run((const char *)data,
+						       script_urls[i]);
 				free(data);
 			} else {
 				struct fetch_worker *w = script_slot[i];
+				unsigned char *body = 0;
 				int tr = 0, rv;
 
 				if (!w) {
@@ -1356,14 +1601,22 @@ static void run_page_scripts(void)
 					fetch_workers_stop_all();
 					break;
 				}
-				if (rv == 0)
-					rv = fetch_worker_read_body(w,
-						image_io_buf, BR_SCRIPT_MAX,
-						image_io_buf + BR_SCRIPT_MAX,
-						BR_IMG_FILE_MAX, &tr, err,
+				/* The body gets its own buffer (scripts are up
+				 * to 2 MB); image_io_buf takes the gzip
+				 * stream. */
+				body = rv == 0 ? (unsigned char *)malloc(
+					BR_SCRIPT_MAX + 1) : 0;
+				if (body)
+					rv = fetch_worker_read_body(w, body,
+						BR_SCRIPT_MAX, image_io_buf,
+						BR_PAGE_COMP_MAX, &tr, err,
 						sizeof(err));
-				else
+				else {
+					if (rv == 0)
+						s_copy(err, "out of memory",
+						       sizeof(err));
 					rv = -1;
+				}
 				fetch_worker_release(w);
 				script_slot[i] = 0;
 				script_submit_window(&next, ferr, sizeof(ferr));
@@ -1376,14 +1629,19 @@ static void run_page_scripts(void)
 						     script_urls[i],
 						     "script is too large");
 				else {
-					image_io_buf[rv] = '\0';
-					script_cache_put(script_urls[i],
-							 image_io_buf,
+					body[rv] = '\0';
+					script_cache_put(script_urls[i], body,
 							 (unsigned int)rv);
-					js_browser_run(
-						(const char *)image_io_buf,
-						script_urls[i]);
+					if (script->module)
+						js_browser_run_module(
+							(const char *)body,
+							script_urls[i]);
+					else
+						js_browser_run(
+							(const char *)body,
+							script_urls[i]);
 				}
+				free(body);
 			}
 		}
 		if (pending_action)
@@ -2308,12 +2566,36 @@ static struct fetch_worker *fetch_worker_alloc(void)
 	return 0;
 }
 
+static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
+				   unsigned int cap, const char *method,
+				   const char *ctype, const char *post,
+				   unsigned int post_len, unsigned int node,
+				   int bg, char *err, unsigned int errcap);
+
 static int fetch_worker_submit(struct fetch_worker *w, const char *url,
 			       unsigned int cap, const char *post,
 			       unsigned int post_len, unsigned int node,
 			       int bg, char *err, unsigned int errcap)
 {
-	static char req[768];
+	/* A body pointer with no bytes is still a POST: the classic request
+	 * line would turn it into a GET. */
+	if (post && !post_len)
+		return fetch_worker_submit_req(w, url, cap, "POST",
+			"application/x-www-form-urlencoded", post, 0, node,
+			bg, err, errcap);
+	return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
+				       node, bg, err, errcap);
+}
+
+/* `method` NULL keeps the classic GET / form-POST request line; otherwise
+ * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
+static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
+				   unsigned int cap, const char *method,
+				   const char *ctype, const char *post,
+				   unsigned int post_len, unsigned int node,
+				   int bg, char *err, unsigned int errcap)
+{
+	static char req[1024];
 	unsigned int n = 0;
 
 	fetch_seq++;
@@ -2332,7 +2614,24 @@ static int fetch_worker_submit(struct fetch_worker *w, const char *url,
 	s_append(req, &n, " ", sizeof(req));
 	s_append_dec(req, &n, cap, sizeof(req));
 	s_append(req, &n, " ", sizeof(req));
-	if (post_len) {
+	if (method) {
+		unsigned int k;
+
+		s_append(req, &n, "X ", sizeof(req));
+		s_append(req, &n, method, sizeof(req));
+		s_append(req, &n, " ", sizeof(req));
+		s_append_dec(req, &n, post_len, sizeof(req));
+		s_append(req, &n, " ", sizeof(req));
+		if (!ctype || !ctype[0])
+			s_append(req, &n, "-", sizeof(req));
+		/* One token on the request line: drop the spaces
+		 * ("application/json; charset=utf-8" stays valid). */
+		for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
+			if (ctype[k] != ' ')
+				req[n++] = ctype[k];
+		req[n] = '\0';
+		s_append(req, &n, " ", sizeof(req));
+	} else if (post_len) {
 		s_append(req, &n, "POST ", sizeof(req));
 		s_append_dec(req, &n, post_len, sizeof(req));
 		s_append(req, &n, " ", sizeof(req));
@@ -2509,6 +2808,7 @@ static void fetch_worker_release(struct fetch_worker *w)
 	w->image_job = 0;
 }
 
+
 /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
 static int fetch_worker_wait(struct fetch_worker *w, char *err,
 			     unsigned int errcap)
@@ -2516,7 +2816,8 @@ static int fetch_worker_wait(struct fetch_worker *w, char *err,
 	for (;;) {
 		int rv;
 
-		worker_wait_ui();
+		if (!fetch_wait_passive)
+			worker_wait_ui();
 		if (cancel_fetch || pending_action) {
 			fetch_workers_cancel_busy();
 			return FETCH_ABORT;
@@ -2567,6 +2868,68 @@ static int fetch_remote(const char *url, unsigned int cap,
 	return rv;
 }
 
+static int fetch_worker_status(const struct fetch_worker *w)
+{
+	return w->m.status;
+}
+
+/* fetch()/XHR through a helper: one request, the status and body come back
+ * whatever the HTTP status (a 401 is an answer, not a network error). */
+static int js_worker_http(const char *method, const char *url,
+			  const char *ctype, const char *body,
+			  unsigned int body_len, struct js_http_resp *r,
+			  char *err, int errcap)
+{
+	struct fetch_worker *w = fetch_worker_alloc();
+	unsigned char *plain;
+	int rv, tr = 0;
+
+	if (!w) {
+		s_copy(err, "network busy", (unsigned int)errcap);
+		return -1;
+	}
+	if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
+				    body_len, 0, 0, err,
+				    (unsigned int)errcap) != 0) {
+		fetch_worker_release(w);
+		return -1;
+	}
+	fetch_wait_passive++;
+	rv = fetch_worker_wait(w, err, (unsigned int)errcap);
+	fetch_wait_passive--;
+	if (rv != 0) {
+		if (rv == FETCH_ABORT)
+			s_copy(err, "page is navigating", (unsigned int)errcap);
+		fetch_worker_release(w);
+		return -1;
+	}
+	r->status = w->m.status;
+	s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
+	s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
+	plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
+	if (!plain) {
+		fetch_worker_release(w);
+		s_copy(err, "out of memory", (unsigned int)errcap);
+		return -1;
+	}
+	if (w->m.len == 0) {
+		rv = 0;     /* 204, an empty 200: no body file */
+	} else {
+		rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
+					    image_io_buf, BR_PAGE_COMP_MAX,
+					    &tr, err, (unsigned int)errcap);
+	}
+	fetch_worker_release(w);
+	if (rv < 0) {
+		free(plain);
+		return -1;
+	}
+	plain[rv] = '\0';
+	r->body = (char *)plain;
+	r->len = (unsigned int)rv;
+	return 0;
+}
+
 /* ---- HTTP / file fetch ---- */
 
 static int read_url(const char *url, unsigned int cap, unsigned char **out,
@@ -3647,7 +4010,7 @@ static void load_page(const char *url, int local, int push)
 	char final[BR_URL_MAX];
 	char err[80];
 	const char *detail = 0;
-	const char *post = pending_post_len ? pending_post : 0;
+	const char *post = pending_post_is ? pending_post : 0;
 	unsigned int post_len = pending_post_len;
 	unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
 	/* Phase timings for the status line: where a slow load spends it. */
@@ -3660,6 +4023,7 @@ static void load_page(const char *url, int local, int push)
 	nav_https_upgraded = 0;
 	final[0] = '\0';
 	pending_post_len = 0;
+	pending_post_is = 0;
 	cancel_fetch = 0;
 	preload_active = 0;
 	preload_pending = 0;
@@ -3877,6 +4241,7 @@ static void load_page(const char *url, int local, int push)
 static void load_home(int push)
 {
 	pending_post_len = 0;
+	pending_post_is = 0;
 	cancel_fetch = 0;
 	preload_active = 0;
 	preload_pending = 0;
@@ -4754,34 +5119,77 @@ static void flush_line(struct lay *l)
 								l->ui->theme.accent);
 					}
 				} else {
+					int editable =
+						r->form_kind == FORM_TEXT ||
+						r->form_kind == FORM_PASSWORD ||
+						r->form_kind == FORM_TEXTAREA;
+					int scroll = 0;
+					/* Editable fields draw the live value
+					 * (r->lit is a short copy). */
+					static char shown[FORM_VALUE_MAX + 1];
+					const char *txt = r->lit;
+					unsigned int tl = s_len(r->lit);
+
+					if (editable && fs && fs->len) {
+						unsigned int k;
+
+						if (r->form_kind == FORM_PASSWORD) {
+							for (k = 0; k < fs->len; k++)
+								shown[k] = '*';
+							shown[k] = '\0';
+							txt = shown;
+						} else {
+							txt = fs->value;
+						}
+						tl = fs->len;
+					}
+					/* The box is drawn in theme colours, so
+					 * the text is too: the page's CSS colour
+					 * (dark on a light page) would vanish on
+					 * the dark field. */
+					if (!disabled)
+						fg = editable && fs && !fs->len ?
+						     l->ui->theme.text_dim :
+						     l->ui->theme.text;
 					ngui_fill_rect(l->ui, box, bg);
 					ngui_frame(l->ui, box,
 						   focused ? l->ui->theme.accent :
 						   l->ui->theme.border);
+					/* A value wider than the field shows its
+					 * tail (where typing happens). */
+					if (editable && w > 12) {
+						int tw = (int)run_text_width(l->ui,
+							r, txt, tl);
+
+						if (tw > w - 12)
+							scroll = tw - (w - 12);
+					}
+					ngui_push_clip(l->ui, (struct ngui_rect){
+						x + 1, ry + 1,
+						w > 2 ? w - 2 : 1,
+						hh > 2 ? hh - 2 : 1 });
 					ngui_text_px_face(l->ui, run_face(r),
-							  x + 6, ry + 2,
-							  r->lit, s_len(r->lit),
-							  fg, r->font_px, r->bold,
-							  r->italic, r->mono);
-					if (focused && fs &&
-					    (r->form_kind == FORM_TEXT ||
-					     r->form_kind == FORM_PASSWORD ||
-					     r->form_kind == FORM_TEXTAREA)) {
+							  x + 6 - scroll,
+							  ry + (hh - r->font_px) / 2 - 1,
+							  txt, tl, fg, r->font_px,
+							  r->bold, r->italic, r->mono);
+					if (focused && fs && editable) {
 						int cw = 0;
 
 						if (fs->len && fs->caret)
 							cw = (int)run_text_width(
-								l->ui, r, r->lit,
+								l->ui, r, txt,
 								fs->caret < fs->len ?
 								fs->caret : fs->len);
 						ngui_fill_rect(l->ui,
 							(struct ngui_rect){
-								x + 6 + cw,
+								x + 6 + cw - scroll,
 								ry + 4, 1,
 								hh > 8 ? hh - 8 : 1
 							},
 							l->ui->theme.accent);
 					}
+					ngui_pop_clip(l->ui);
 					if (r->form_kind == FORM_SELECT) {
 						ngui_text_px(l->ui, x + w - 12,
 							     ry + 2, "v", 1, fg,
@@ -5382,6 +5790,11 @@ static void list_marker_text(char *m, unsigned int cap, int style, int idx)
 	m[n] = '\0';
 }
 
+/* Set by the layout when the control is stretched to its line: a flex item
+ * (its box width was assigned by the flex row) or a child of a flex column,
+ * whose default align-items: stretch makes inputs full width. */
+static int form_fill_line;
+
 static void add_form_run(struct lay *l, unsigned int node,
 			 const struct br_style *st, unsigned short href)
 {
@@ -5436,7 +5849,20 @@ static void add_form_run(struct lay *l, unsigned int node,
 			w = 64;
 		h = 22;
 	} else if (kind == FORM_TEXT || kind == FORM_PASSWORD) {
-		w = st->width_kind == 1 ? st->width : 120;
+		int line_w = l->line_right - l->line_left;
+
+		if (st->width_kind == 1)
+			w = st->width;
+		else if (st->width_kind == 2)
+			w = css_size(st->width_kind, st->width, line_w);
+		else if (form_fill_line || st->display == BR_DISPLAY_BLOCK)
+			w = line_w - (l->line_x - l->line_left);
+		else
+			w = 120;
+		/* Taller fields for large text (min-height/padding on login
+		 * pages): keep the box around the glyphs. */
+		if (st->font_px + 8 > h)
+			h = st->font_px + 8;
 	} else if (kind == FORM_SELECT) {
 		w = st->width_kind == 1 ? st->width : 120;
 	}
@@ -6448,9 +6874,14 @@ static void layout_block(struct lay *l, unsigned int node,
 		if (doc.nodes[node].tag == BR_TAG_INPUT &&
 		    s_eq(br_type(&doc, node), "hidden"))
 			return;
+		/* Reached as a block-level box (a flex item): the control
+		 * fills the box the caller assigned, and its line is flushed
+		 * here; flex layout resets the run list for the next item, so
+		 * a queued run would never be drawn. */
+		form_fill_line = 1;
 		add_form_run(l, node, st, link);
-		l->y += doc.nodes[node].tag == BR_TAG_TEXTAREA ? 40 :
-		       doc.nodes[node].tag == BR_TAG_BUTTON ? 22 : 20;
+		form_fill_line = 0;
+		flush_line(l);
 		return;
 	}
 	flush_line(l);
@@ -8581,8 +9012,13 @@ static void layout_children(struct lay *l, unsigned int parent,
 		if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
 		    nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) {
 			if (!(nd->tag == BR_TAG_INPUT &&
-			      s_eq(br_type(&doc, n), "hidden")))
+			      s_eq(br_type(&doc, n), "hidden"))) {
+				form_fill_line = pst->display ==
+						 BR_DISPLAY_FLEX &&
+						 pst->flex_col;
 				add_form_run(l, n, &cs, lk);
+				form_fill_line = 0;
+			}
 			n = nd->next;
 			continue;
 		}
@@ -9274,8 +9710,10 @@ static int form_submit_form(unsigned int node, int fire_event)
 			memcpy(pending_post, query, qn);
 		pending_post[qn] = '\0';
 		pending_post_len = qn;
+		pending_post_is = 1;
 	} else {
 		pending_post_len = 0;
+		pending_post_is = 0;
 		if (qn) {
 			unsigned int an = s_len(action);
 
@@ -9530,6 +9968,31 @@ static void form_key(int k)
 	ngui_invalidate(&ui);
 }
 
+/* The innermost laid-out box under a screen point: the smallest valid box
+ * that contains it (the last one wins a tie, i.e. the later/deeper node).
+ * Used to deliver clicks to elements that are neither links nor controls
+ * (a Vue <div role="button">, a card with a click listener). */
+static unsigned int find_box_hit(int x, int y)
+{
+	unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
+
+	for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
+		const struct br_layout_box *b = &layout_boxes[i];
+		unsigned int area;
+
+		if (!b->valid || b->w <= 0 || b->h <= 0 ||
+		    x < b->x || y < b->y || x >= b->x + b->w ||
+		    y >= b->y + b->h)
+			continue;
+		area = (unsigned int)b->w * (unsigned int)b->h;
+		if (area <= best_area) {
+			best = i;
+			best_area = area;
+		}
+	}
+	return best;
+}
+
 static void handle_page_click(unsigned int *action)
 {
 	int node;
@@ -9543,8 +10006,18 @@ static void handle_page_click(unsigned int *action)
 	    ui.press_y >= page_rect.y + page_rect.h)
 		return;
 	node = find_hit(ui.press_x, ui.press_y);
-	if (!node)
+	if (!node) {
+		unsigned int box;
+
+		if (!js_browser_active())
+			return;
+		box = find_box_hit(ui.press_x, ui.press_y);
+		if (box) {
+			form_blur();
+			js_browser_event(box, "click", 1, 1);
+		}
 		return;
+	}
 	if (form_is_control((unsigned int)node)) {
 		form_click((unsigned int)node);
 		return;

+ 68 - 7
browser_html.c

@@ -937,6 +937,33 @@ static unsigned int append_text(struct br_doc *d, unsigned int parent,
 	return idx;
 }
 
+/* Raw text child (no entity decoding, whitespace kept): the body of a
+ * data-block <script> such as type="application/json", which scripts read
+ * through textContent.  Bodies longer than a text node holds are dropped. */
+static unsigned int append_raw_text(struct br_doc *d, unsigned int parent,
+				    const char *s, unsigned int len)
+{
+	unsigned int idx, i;
+
+	if (len == 0 || len > 0xFFFFu)
+		return 0;
+	if (d->text_used + len + 1 >= BR_TEXT_SIZE) {
+		d->truncated = 1;
+		return 0;
+	}
+	idx = node_append(d, parent, BR_NODE_TEXT, 0);
+	if (!idx)
+		return 0;
+	for (i = 0; i < len; i++)
+		d->text[d->text_used + i] = s[i];
+	d->text[d->text_used + len] = '\0';
+	d->nodes[idx].text_off = d->text_used;
+	d->nodes[idx].text_len = (unsigned short)len;
+	d->nodes[idx].flags = BR_NODE_PREFORMAT;
+	d->text_used += len + 1;
+	return idx;
+}
+
 /* ---- runtime DOM helpers (JavaScript bindings) ---- */
 
 static int same_string(const char *a, const char *b)
@@ -1522,6 +1549,25 @@ static void attr_note_known(struct br_doc *d, struct br_node *n,
 			    const char *name, const char *value,
 			    unsigned int len)
 {
+	int control = n->tag == BR_TAG_INPUT || n->tag == BR_TAG_BUTTON ||
+		      n->tag == BR_TAG_SELECT || n->tag == BR_TAG_TEXTAREA;
+
+	/* Form controls keep type/value/placeholder in the rel/src/alt slots,
+	 * exactly like parse_attrs(); script-built inputs (Vue sets
+	 * type="password" after createElement) must land there too. */
+	if (control && same_string(name, "type")) {
+		n->rel_off = len ? store_attr(d, value, len, 40) : 0;
+		return;
+	}
+	if (control && same_string(name, "value")) {
+		n->src_off = len ? store_attr(d, value, len, 220) : 0;
+		return;
+	}
+	if ((n->tag == BR_TAG_INPUT || n->tag == BR_TAG_TEXTAREA) &&
+	    same_string(name, "placeholder")) {
+		n->alt_off = len ? store_attr(d, value, len, 120) : 0;
+		return;
+	}
 	if (same_string(name, "id"))
 		n->id_off = len ? store_attr(d, value, len, 64) : 0;
 	else if (same_string(name, "class"))
@@ -8107,9 +8153,13 @@ static unsigned int script_src_attr(struct br_doc *d, const char *s,
 
 /* JavaScript only: skip structured-data/template script blocks (JSON-LD,
  * application/json, text/template, ...) and non-JS type values.  External
- * src scripts are allowed; the browser fetches them separately. */
+ * src scripts are allowed; the browser fetches them separately.  Returns 1
+ * for a classic script, 2 for type="module", 0 to skip (also for a
+ * `nomodule` fallback, since module scripts run). */
 static int script_is_javascript(const char *s, unsigned int len)
 {
+	int kind = 1;
+
 	unsigned int i = 0;
 
 	while (i < len) {
@@ -8149,22 +8199,28 @@ static int script_is_javascript(const char *s, unsigned int len)
 		} else if (i == ne) {
 			i++;
 		}
-		if (ne > ns && ci_eq_n(s + ns, "type", ne - ns)) {
+		if (ne - ns == 8 && ci_eq_n(s + ns, "nomodule", 8))
+			return 0;
+		if (ne - ns == 4 && ci_eq_n(s + ns, "type", 4)) {
 			unsigned int vn = has_val ? ve - vs : 0;
 
 			if (vn == 0)
-				return 1;
+				continue;
+			if (vn == 6 && ci_eq_n(s + vs, "module", 6)) {
+				kind = 2;
+				continue;
+			}
 			if ((vn == 15 && ci_eq_n(s + vs, "text/javascript", 15)) ||
 			    (vn == 22 &&
 			     ci_eq_n(s + vs, "application/javascript", 22)) ||
 			    (vn == 15 && ci_eq_n(s + vs, "text/ecmascript", 15)) ||
 			    (vn == 22 &&
 			     ci_eq_n(s + vs, "application/ecmascript", 22)))
-				return 1;
+				continue;
 			return 0;
 		}
 	}
-	return 1;
+	return kind;
 }
 
 int br_parse(struct br_doc *d, const char *html, unsigned int len)
@@ -8309,12 +8365,15 @@ int br_parse(struct br_doc *d, const char *html, unsigned int len)
 				unsigned int end = p >= 0 ? (unsigned int)p : len;
 				unsigned int idx;
 
-				if (script_is_javascript(html + attr_start,
-							 attr_end - attr_start)) {
+				int kind = script_is_javascript(html + attr_start,
+							attr_end - attr_start);
+
+				if (kind) {
 					if (d->nscripts < BR_MAX_SCRIPTS) {
 						struct br_script *script =
 							&d->scripts[d->nscripts++];
 
+						script->module = kind == 2;
 						script->off = i;
 						script->len = end > i ? end - i : 0;
 						script->src_off = script_src_attr(
@@ -8334,6 +8393,8 @@ int br_parse(struct br_doc *d, const char *html, unsigned int len)
 					parse_attrs(d, &d->nodes[idx],
 						    html + attr_start,
 						    attr_end - attr_start);
+				if (idx && !kind && end > i)
+					append_raw_text(d, idx, html + i, end - i);
 				i = p >= 0 ? (unsigned int)p + 8 : len;
 				while (i < len && html[i] != '>')
 					i++;

+ 1 - 0
browser_html.h

@@ -266,6 +266,7 @@ struct br_script {
 	unsigned int off;       /* inline body, or empty for src scripts */
 	unsigned int len;
 	unsigned int src_off;   /* src attribute in the attr arena, 0 if inline */
+	unsigned int module;    /* type="module": run as an ES module */
 };
 
 struct br_doc {

+ 2 - 2
docs/network.html

@@ -408,9 +408,9 @@
 		<h2>HTTP clients</h2>
 		<ul>
 			<li><strong>curl</strong> — <code>http://</code> or <code>https://</code> GET with DNS, ARP, redirects (up to five hops), chunked decoding, status/headers/body dump and a TLS warning.</li>
-			<li><strong>uhttp</strong> — shared ring-3 HTTP/1.1 client used by curl, the browser and chat: URL parsing, redirects (up to eight hops; 1 KB paths and 1.5 KB header lines, enough for OIDC URLs), chunked decoding, timeouts and TLS.  Requests and bodies of any size are split into pieces the transport accepts (1024-byte TLS records, one peer MSS for plain TCP).  Optional per-request fields set the <code>Accept</code> header, extra header lines and a cookie jar; 1xx/204/304 responses are treated as bodyless so keep-alive does not wait for an idle timeout.</li>
+			<li><strong>uhttp</strong> — shared ring-3 HTTP/1.1 client used by curl, the browser and chat: URL parsing (spaces, controls, quotes and non-ASCII bytes in the path are percent-encoded, and <code>//</code>/<code>.</code>/<code>..</code> normalization stops at the query, which may carry a URL such as <code>redirect_uri=https://…</code>), redirects (up to eight hops; 1 KB paths and 1.5 KB header lines, enough for OIDC URLs), chunked decoding, timeouts and TLS.  Requests and bodies of any size are split into pieces the transport accepts (1024-byte TLS records, one peer MSS for plain TCP).  Optional per-request fields set the <code>Accept</code> header, extra header lines and a cookie jar; 1xx/204/304 responses are treated as bodyless so keep-alive does not wait for an idle timeout.</li>
 			<li><strong>uhttp_cookie</strong> — the cookie jar (<span class="file">uhttp_cookie.c</span>, 24 cookies of up to 768 bytes).  Every <code>Set-Cookie</code>, including those on redirect responses, is stored; matching cookies are sent on every request and redirect hop.  Cookies are host-only (<code>Domain</code> is ignored), <code>Path</code> is a prefix match, <code>Secure</code> cookies only go over https, and <code>Max-Age&lt;=0</code> or a 1970 <code>Expires</code> deletes a cookie.  The jar outlives the connection, so a cross-origin redirect that reconnects keeps the session.</li>
-			<li><strong>browser</strong> — runs network fetches in up to four headless <code>curl __serve</code> workers, each with its own request/body/meta files under <code>/share/bf&lt;session&gt;_&lt;slot&gt;*</code>.  The session id comes from the browser pid, so multiple browser windows do not share queue files.  Stylesheet and external-script bodies are downloaded in parallel but parsed/executed in document order; one image starts before the script phase, and the remaining images are prefetched in parallel and decoded as jobs complete, so the UI keeps drawing and scrolling.  Each worker keeps its own TCP/TLS connection; idle helpers stay warm across navigations (a cross-origin job just drops the old connection, and only busy helpers are killed), and helpers also exit after ten idle seconds or when the window loses focus.  A DNS failure is retried once after tearing the helpers down.  The helpers' DNS/TLS log lines go to a private tty that the browser drains and discards from every poll loop; a full tty ring blocks its writers, so an undrained one used to hang every helper after about sixteen TLS connections.  The status bar reports the page's total, header and first-byte times.</li>
+			<li><strong>browser</strong> — runs network fetches in up to four headless <code>curl __serve</code> workers, each with its own request/body/meta files under <code>/share/bf&lt;session&gt;_&lt;slot&gt;*</code>.  A request line is <code>&lt;seq&gt; &lt;cap&gt; [POST &lt;len&gt;] &lt;url&gt;</code> for page/form loads or <code>&lt;seq&gt; &lt;cap&gt; X &lt;method&gt; &lt;len&gt; &lt;content-type|-&gt; &lt;url&gt;</code> for script <code>fetch()</code>/XHR and empty-body form POSTs.  All helpers share one cookie jar in <code>/share/bcookies</code> (read before and written after every request that changed it), so a login session survives helper restarts and the parallel workers; it is RAM only and cleared at reboot.  The session id comes from the browser pid, so multiple browser windows do not share queue files.  Stylesheet and external-script bodies are downloaded in parallel but parsed/executed in document order; one image starts before the script phase, and the remaining images are prefetched in parallel and decoded as jobs complete, so the UI keeps drawing and scrolling.  Each worker keeps its own TCP/TLS connection; idle helpers stay warm across navigations (a cross-origin job just drops the old connection, and only busy helpers are killed), and helpers also exit after ten idle seconds or when the window loses focus.  A DNS failure is retried once after tearing the helpers down.  The helpers' DNS/TLS log lines go to a private tty that the browser drains and discards from every poll loop; a full tty ring blocks its writers, so an undrained one used to hang every helper after about sixteen TLS connections.  The status bar reports the page's total, header and first-byte times.</li>
 			<li><strong>websrv</strong> — the server side, speaking HTTP/1.1 + WebDAV over the TCP listener; see <a href="filesystems.html#webdav">Filesystems → WebDAV</a>.</li>
 		</ul>
 		<p>

Разница между файлами не показана из-за своего большого размера
+ 0 - 0
docs/userland.html


+ 248 - 10
js_browser.c

@@ -20,7 +20,7 @@
  * bootstrap (AngularJS rendering ~300 cards) needs several seconds on a
  * slow CPU, so the budget is generous. */
 #define JS_RUN_LIMIT 20000
-#define JS_TIMERS 16
+#define JS_TIMERS 64
 
 struct js_timer {
 	int used;
@@ -71,6 +71,7 @@ static int node_put(js_State *state, void *p, const char *name);
 static int node_delete(js_State *state, void *p, const char *name);
 static void push_element_url(js_State *state, unsigned int node,
 			     const char *name);
+static void rellist_supports(js_State *state);
 
 /* One wrapper per DOM node: the same element must have the same object
  * identity on every access, or library caches (jQuery expando data, Sizzle)
@@ -91,7 +92,7 @@ static void push_node(js_State *state, unsigned int handle)
 	/* js_newuserdatax() pops a prototype from the top.  Wrappers inherit
 	 * from Object.prototype like real DOM nodes (toString/hasOwnProperty;
 	 * Angular calls node.toString() to sniff SVG). */
-	js_getregistry(state, "wrapproto");
+	js_getregistry(state, "nodeproto");
 	js_newuserdatax(state, "node", (void *)(uintptr_t)handle,
 			node_has, node_put, node_delete, 0);
 	js_copy(state, -1);
@@ -190,7 +191,7 @@ static unsigned int node_name(unsigned int node, char *buf, unsigned int cap)
  * per dispatch in a small event-state table and mirrored onto the event
  * object, so a submit handler can cancel the browser's default action. */
 
-#define JS_LISTENERS        64
+#define JS_LISTENERS       256
 #define JS_EVENT_SLOTS       8
 #define JS_EVENT_TEMPLATES  16
 
@@ -1993,6 +1994,51 @@ static int node_has(js_State *state, void *p, const char *name)
 		js_getglobal(state, "document");
 		return 1;
 	}
+	if (!strcmp(name, "localName")) {
+		unsigned int i;
+
+		if (n->type != BR_NODE_ELEM) {
+			js_pushnull(state);
+			return 1;
+		}
+		node_name(node, buf, sizeof(buf));
+		for (i = 0; buf[i]; i++)
+			if (buf[i] >= 'A' && buf[i] <= 'Z')
+				buf[i] = (char)(buf[i] - 'A' + 'a');
+		js_pushstring(state, buf);
+		return 1;
+	}
+	if (!strcmp(name, "namespaceURI")) {
+		unsigned int a;
+
+		if (n->type != BR_NODE_ELEM) {
+			js_pushnull(state);
+			return 1;
+		}
+		for (a = node; a && a < D->nnode; a = D->nodes[a].parent)
+			if (D->nodes[a].type == BR_NODE_ELEM &&
+			    D->nodes[a].tag == BR_TAG_SVG)
+				break;
+		js_pushstring(state, a && a < D->nnode ?
+			      "http://www.w3.org/2000/svg" :
+			      "http://www.w3.org/1999/xhtml");
+		return 1;
+	}
+	if (!strcmp(name, "isConnected")) {
+		unsigned int a = node;
+
+		while (a && a < D->nnode && D->nodes[a].parent)
+			a = D->nodes[a].parent;
+		js_pushboolean(state, a == 0 || a == D->root);
+		return 1;
+	}
+	if (!strcmp(name, "relList")) {
+		/* Only supports(): Vite's modulepreload polyfill asks it and
+		 * otherwise refetches every preloaded module through fetch(). */
+		js_newobject(state);
+		def_func(state, "supports", rellist_supports, 1);
+		return 1;
+	}
 	if (!strcmp(name, "getAttribute"))
 		{ push_func_data(state, "getAttribute", node_getattr, 1, node + 1); return 1; }
 	if (!strcmp(name, "setAttribute"))
@@ -2331,6 +2377,26 @@ static void location_set(js_State *state)
 		host.navigate(url);
 }
 
+/* assign()/replace(): navigate (the history entry is not replaced yet). */
+static void location_assign(js_State *state)
+{
+	if (host.navigate)
+		host.navigate(js_tostring(state, 1));
+	js_pushundefined(state);
+}
+
+static void location_reload(js_State *state)
+{
+	if (host.navigate && current_url)
+		host.navigate(current_url);
+	js_pushundefined(state);
+}
+
+static void location_tostring(js_State *state)
+{
+	js_pushstring(state, current_url ? current_url : "");
+}
+
 static void win_noop(js_State *state);
 
 struct loc_parts {
@@ -2431,13 +2497,13 @@ static void push_location(js_State *state)
 	LOC_FIELD(origin);
 #undef LOC_FIELD
 
-	js_newcfunction(state, win_noop, "reload", 0);
+	js_newcfunction(state, location_reload, "reload", 0);
 	js_setproperty(state, -2, "reload");
-	js_newcfunction(state, win_noop, "assign", 1);
+	js_newcfunction(state, location_assign, "assign", 1);
 	js_setproperty(state, -2, "assign");
-	js_newcfunction(state, win_noop, "replace", 1);
+	js_newcfunction(state, location_assign, "replace", 1);
 	js_setproperty(state, -2, "replace");
-	js_newcfunction(state, win_noop, "toString", 0);
+	js_newcfunction(state, location_tostring, "toString", 0);
 	js_setproperty(state, -2, "toString");
 }
 
@@ -2476,7 +2542,7 @@ static void url_put(char *out, unsigned int cap, unsigned int *n,
 /* Collapse //, /./ and /../ inside the path part of an absolute URL. */
 static void url_normalize(char *url)
 {
-	char tmp[512];
+	char tmp[1024];
 	char *path;
 	unsigned int n = 0, i = 0;
 
@@ -2490,13 +2556,15 @@ static void url_normalize(char *url)
 	}
 	if (path[0] != '/')
 		return;
-	while (path[i]) {
+	/* The path only: ?query and #fragment are copied verbatim below. */
+	while (path[i] && path[i] != '?' && path[i] != '#') {
 		unsigned int start;
 
 		while (path[i] == '/')
 			i++;
 		start = i;
-		while (path[i] && path[i] != '/')
+		while (path[i] && path[i] != '/' && path[i] != '?' &&
+		       path[i] != '#')
 			i++;
 		if (i == start)
 			continue;
@@ -2517,6 +2585,10 @@ static void url_normalize(char *url)
 	}
 	if (n == 0)
 		tmp[n++] = '/';
+	else if (i > 0 && path[i - 1] == '/' && n + 1 < sizeof(tmp))
+		tmp[n++] = '/';     /* keep "dir/" a directory */
+	while (path[i] && n + 1 < sizeof(tmp))
+		tmp[n++] = path[i++];
 	tmp[n] = '\0';
 	memcpy(path, tmp, n + 1);
 }
@@ -2777,6 +2849,113 @@ static void win_matchmedia(js_State *state)
 	def_func(state, "removeEventListener", win_noop, 2);
 }
 
+static void rellist_supports(js_State *state)
+{
+	const char *t = js_tostring(state, 1);
+
+	js_pushboolean(state, !strcmp(t, "modulepreload") ||
+		       !strcmp(t, "preload") || !strcmp(t, "stylesheet"));
+}
+
+/* ---- primitives for js_prelude.js ---- */
+
+/* __nb_http(method, url, contentType, body) -> [status, ctype, url, text].
+ * Synchronous: the host fetches through its helpers while the script
+ * waits.  A network failure throws (fetch() turns it into a TypeError). */
+static void nb_http(js_State *state)
+{
+	struct js_http_resp r;
+	const char *method = js_tostring(state, 1);
+	const char *url = js_tostring(state, 2);
+	const char *ctype = js_tostring(state, 3);
+	const char *body = js_tostring(state, 4);
+	char err[96];
+	int rv;
+
+	memset(&r, 0, sizeof(r));
+	err[0] = '\0';
+	rv = host.http ? host.http(method, url, ctype, body,
+				   (unsigned int)strlen(body), &r, err,
+				   (int)sizeof(err)) : -1;
+	/* The budget covers running JavaScript, not the network wait. */
+	js_setlimit(state, JS_RUN_LIMIT, 0);
+	if (rv != 0) {
+		free(r.body);
+		js_typeerror(state, "network error: %s",
+			     err[0] ? err : "fetch failed");
+	}
+	js_newarray(state);
+	js_pushnumber(state, r.status);
+	js_setindex(state, -2, 0);
+	js_pushstring(state, r.ctype);
+	js_setindex(state, -2, 1);
+	js_pushstring(state, r.url);
+	js_setindex(state, -2, 2);
+	js_pushlstring(state, r.body ? r.body : "", (int)r.len);
+	js_setindex(state, -2, 3);
+	free(r.body);
+}
+
+#define JS_STORAGE_MAX (32u * 1024u)
+
+/* __nb_storage(kind) -> text, __nb_storage(kind, text) stores it. */
+static void nb_storage(js_State *state)
+{
+	int kind = js_tointeger(state, 1);
+	char *buf;
+	int n;
+
+	if (js_isstring(state, 2)) {
+		if (host.storage)
+			host.storage(kind, js_tostring(state, 2), 0, 0);
+		js_pushundefined(state);
+		return;
+	}
+	buf = (char *)malloc(JS_STORAGE_MAX);
+	n = buf && host.storage ?
+	    host.storage(kind, 0, buf, (int)JS_STORAGE_MAX) : -1;
+	if (n > 0)
+		js_pushlstring(state, buf, n);
+	else
+		js_pushstring(state, "");
+	free(buf);
+}
+
+static void url_resolve(const char *base, const char *rel,
+			char *out, unsigned int cap);
+
+static void nb_resolve(js_State *state)
+{
+	char out[512];
+
+	url_resolve(js_tostring(state, 1), js_tostring(state, 2), out,
+		    sizeof(out));
+	js_pushstring(state, out);
+}
+
+extern const char js_prelude_source[];
+
+static void install_prelude(js_State *state)
+{
+	js_newcfunction(state, nb_http, "__nb_http", 4);
+	js_defglobal(state, "__nb_http", 0);
+	js_newcfunction(state, nb_storage, "__nb_storage", 2);
+	js_defglobal(state, "__nb_storage", 0);
+	js_newcfunction(state, nb_resolve, "__nb_resolve", 2);
+	js_defglobal(state, "__nb_resolve", 0);
+	js_getregistry(state, "nodeproto");
+	js_defglobal(state, "__nb_nodeproto", 0);
+	if (js_ploadstring(state, "[prelude]", js_prelude_source)) {
+		report_top(state);
+		return;
+	}
+	js_pushundefined(state);
+	if (js_pcall(state, 0))
+		report_top(state);
+	else
+		js_pop(state, 1);
+}
+
 static void install_globals(js_State *state)
 {
 	unsigned int h;
@@ -2784,6 +2963,10 @@ static void install_globals(js_State *state)
 	/* Shared prototype of the node/style/dataset wrappers. */
 	js_newobject(state);
 	js_setregistry(state, "wrapproto");
+	/* DOM node wrappers: their own prototype, so the prelude can add the
+	 * Element methods there without touching style/dataset objects. */
+	js_newobject(state);
+	js_setregistry(state, "nodeproto");
 	js_newobject(state);
 	def_func(state, "getElementById", doc_getelementbyid, 1);
 	def_func(state, "createElement", doc_create_element, 1);
@@ -2914,6 +3097,32 @@ static void install_globals(js_State *state)
 	js_pop(state, 1);
 }
 
+static int module_resolve(const char *base, const char *name, char *out,
+			  unsigned int cap)
+{
+	url_resolve(base && base[0] ? base :
+		    (current_url ? current_url : ""), name, out, cap);
+	return 0;
+}
+
+static char *module_load(const char *url, unsigned int *len)
+{
+	char *src;
+
+	if (!host.load_script)
+		return 0;
+	src = host.load_script(url, len);
+	if (J)
+		js_setlimit(J, JS_RUN_LIMIT, 0);
+	if (!src && host.report) {
+		char msg[600];
+
+		snprintf(msg, sizeof(msg), "Cannot load module %s", url);
+		host.report(msg);
+	}
+	return src;
+}
+
 int js_browser_start(struct br_doc *doc, const struct js_browser_host *h)
 {
 	if (!doc || !h)
@@ -2934,7 +3143,10 @@ int js_browser_start(struct br_doc *doc, const struct js_browser_host *h)
 		return -1;
 	js_setreport(J, report_cb);
 	js_atpanic(J, panic_cb);
+	js_setmodulehost(J, module_resolve, module_load);
 	install_globals(J);
+	js_setlimit(J, JS_RUN_LIMIT, 0);
+	install_prelude(J);
 	return 0;
 }
 
@@ -3061,3 +3273,29 @@ int js_browser_run(const char *source, const char *url)
 	panic_armed = 0;
 	return 0;
 }
+
+/* Run a <script type="module">: imports are resolved against `url` and
+ * loaded through host.load_script. */
+int js_browser_run_module(const char *source, const char *url)
+{
+	if (!J || !D)
+		return -1;
+	js_setlimit(J, JS_RUN_LIMIT, 0);
+	panic_armed = 1;
+	if (setjmp(panic_env)) {
+		panic_armed = 0;
+		if (host.report)
+			host.report("uncaught JavaScript exception");
+		J = 0;
+		D = 0;
+		return -1;
+	}
+	if (js_ploadmodule(J, url ? url : "[module]", source)) {
+		report_top(J);
+		panic_armed = 0;
+		return -1;
+	}
+	js_pop(J, 1);
+	panic_armed = 0;
+	return 0;
+}

+ 25 - 0
js_browser.h

@@ -9,6 +9,16 @@
 
 struct br_doc;
 
+/* One synchronous HTTP exchange for fetch()/XMLHttpRequest.  `body` is a
+ * malloc()ed buffer owned by the caller after the call (may be NULL). */
+struct js_http_resp {
+	int status;
+	char ctype[64];
+	char url[512];          /* final URL after redirects */
+	char *body;
+	unsigned int len;
+};
+
 struct js_browser_host {
 	void (*status)(const char *msg, int error);
 	void (*report)(const char *msg);
@@ -32,6 +42,17 @@ struct js_browser_host {
 	/* Computed style for getComputedStyle(); return 1 when known. */
 	int (*computed)(unsigned int node, const char *property, char *buf,
 			int cap);
+	/* fetch()/XHR: returns 0 and fills `r`, or -1 with `err` set. */
+	int (*http)(const char *method, const char *url, const char *ctype,
+		    const char *body, unsigned int body_len,
+		    struct js_http_resp *r, char *err, int errcap);
+	/* Module source for an absolute URL, malloc()ed and NUL-terminated
+	 * (the caller frees it); NULL when it cannot be loaded. */
+	char *(*load_script)(const char *url, unsigned int *len);
+	/* Web Storage for this page's origin; kind 0 = local, 1 = session.
+	 * With `set` the text is stored (returns 0); otherwise it is read into
+	 * out (returns its length, or -1). */
+	int (*storage)(int kind, const char *set, char *out, int cap);
 	const char *page_url;   /* location.href for every script on the page */
 	unsigned int width;     /* viewport size for window.inner* */
 	unsigned int height;
@@ -44,6 +65,10 @@ void js_browser_stop(void);
 /* Run one script.  `url` is used in error messages and by location.href. */
 int js_browser_run(const char *source, const char *url);
 
+/* Run one <script type="module">; its imports load through
+ * host.load_script. */
+int js_browser_run_module(const char *source, const char *url);
+
 /* Run due setTimeout/setInterval callbacks; call once per UI loop. */
 void js_browser_tick(void);
 

+ 155 - 0
js_mu.c

@@ -85,6 +85,8 @@ struct js_State {
 	int limited;
 	int depth;              /* nested entries from C into JavaScript */
 	void *jsstack;          /* private engine stack (MU_OWN_STACK) */
+	js_ModuleResolve mod_resolve;
+	js_ModuleLoad mod_load;
 };
 
 struct mu_ud {
@@ -622,6 +624,40 @@ static int mu_interrupt(JSRuntime *rt, void *opaque)
 	return J->limited && (int)(u_ticks_ms() - J->deadline) >= 0;
 }
 
+/* An async function or a promise chain that fails with nobody listening
+ * (Vite apps bootstrap from an async IIFE) would otherwise vanish without a
+ * trace.  The error goes to the report hook, like an uncaught exception.
+ * A handler attached later in the same job cannot be detected here, so a
+ * rejection that is handled late is still reported once. */
+static void mu_rejection(JSContext *ctx, JSValueConst promise,
+			 JSValueConst reason, int is_handled, void *opaque)
+{
+	js_State *J = (js_State *)opaque;
+	const char *msg, *stack = 0;
+	JSValue st = JS_UNDEFINED;
+	char buf[768];
+
+	(void)promise;
+	if (is_handled || !J->report)
+		return;
+	msg = JS_ToCString(ctx, reason);
+	if (JS_IsObject(reason)) {
+		st = JS_GetPropertyStr(ctx, reason, "stack");
+		if (JS_IsString(st))
+			stack = JS_ToCString(ctx, st);
+	}
+	snprintf(buf, sizeof(buf), "Uncaught (in promise) %s%s%s",
+		 msg ? msg : "error", stack ? "\n" : "", stack ? stack : "");
+	J->report(J, buf);
+	if (stack)
+		JS_FreeCString(ctx, stack);
+	JS_FreeValue(ctx, st);
+	if (msg)
+		JS_FreeCString(ctx, msg);
+	else
+		JS_FreeValue(ctx, JS_GetException(ctx));
+}
+
 js_State *js_newstate(js_Alloc alloc, void *actx, int flags)
 {
 	js_State *J;
@@ -656,6 +692,7 @@ js_State *js_newstate(js_Alloc alloc, void *actx, int flags)
 	}
 	JS_SetContextOpaque(J->ctx, J);
 	JS_SetInterruptHandler(J->rt, mu_interrupt, J);
+	JS_SetHostPromiseRejectionTracker(J->rt, mu_rejection, J);
 	J->registry = JS_NewObject(J->ctx);
 	return J;
 }
@@ -804,6 +841,124 @@ static JSValue mu_compile(js_State *J, const char *filename,
 	return e.result;
 }
 
+/* ---- ES modules ----
+ *
+ * Module specifiers are resolved to absolute URLs by the host, and QuickJS
+ * caches modules by that name, so every URL is fetched and evaluated once
+ * per state, as in a browser.  The loader runs synchronously inside the
+ * engine: the host fetches the source while the script waits. */
+
+static void mu_set_import_meta(JSContext *ctx, JSModuleDef *m,
+			       const char *url)
+{
+	JSValue meta = JS_GetImportMeta(ctx, m);
+
+	if (JS_IsException(meta))
+		return;
+	JS_DefinePropertyValueStr(ctx, meta, "url", JS_NewString(ctx, url),
+				  JS_PROP_C_W_E);
+	JS_FreeValue(ctx, meta);
+}
+
+static char *mu_module_normalize(JSContext *ctx, const char *base,
+				 const char *name, void *opaque)
+{
+	js_State *J = (js_State *)opaque;
+	char buf[1024];
+	size_t n;
+	char *out;
+
+	if (!J->mod_resolve || J->mod_resolve(base, name, buf, sizeof(buf)))
+		snprintf(buf, sizeof(buf), "%s", name);
+	n = strlen(buf);
+	out = (char *)js_malloc(ctx, n + 1);
+	if (out)
+		memcpy(out, buf, n + 1);
+	return out;
+}
+
+static JSModuleDef *mu_module_loader(JSContext *ctx, const char *name,
+				     void *opaque)
+{
+	js_State *J = (js_State *)opaque;
+	unsigned int len = 0;
+	char *src;
+	JSValue f;
+	JSModuleDef *m;
+
+	src = J->mod_load ? J->mod_load(name, &len) : 0;
+	if (!src) {
+		JS_ThrowReferenceError(ctx, "could not load module '%s'", name);
+		return 0;
+	}
+	f = JS_Eval(ctx, src, len, name,
+		    JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
+	free(src);
+	if (JS_IsException(f))
+		return 0;
+	m = (JSModuleDef *)JS_VALUE_GET_PTR(f);
+	mu_set_import_meta(ctx, m, name);
+	JS_FreeValue(ctx, f);
+	return m;
+}
+
+void js_setmodulehost(js_State *J, js_ModuleResolve resolve,
+		      js_ModuleLoad load)
+{
+	J->mod_resolve = resolve;
+	J->mod_load = load;
+	JS_SetModuleLoaderFunc(J->rt, mu_module_normalize, mu_module_loader, J);
+}
+
+static void mu_do_module(struct mu_entry *e)
+{
+	JSContext *ctx = e->J->ctx;
+	JSValue f;
+
+	f = JS_Eval(ctx, e->source, strlen(e->source),
+		    e->filename ? e->filename : "[module]",
+		    JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
+	if (JS_IsException(f)) {
+		e->result = f;
+		return;
+	}
+	mu_set_import_meta(ctx, (JSModuleDef *)JS_VALUE_GET_PTR(f),
+			   e->filename ? e->filename : "");
+	/* Links the import graph (the loader fetches dependencies), then runs
+	 * it; the result is the evaluation promise. */
+	e->result = JS_EvalFunction(ctx, f);
+}
+
+int js_ploadmodule(js_State *J, const char *filename, const char *source)
+{
+	struct mu_entry e;
+	JSValue p;
+	int st;
+
+	memset(&e, 0, sizeof(e));
+	e.fn = mu_do_module;
+	e.filename = filename;
+	e.source = source;
+	mu_enter(J, &e);
+	p = e.result;
+	if (JS_IsException(p)) {
+		mu_push(J, JS_GetException(J->ctx));
+		return 1;
+	}
+	js_runjobs(J);
+	st = JS_PromiseState(J->ctx, p);
+	if (st == JS_PROMISE_REJECTED) {
+		JSValue r = JS_PromiseResult(J->ctx, p);
+
+		JS_FreeValue(J->ctx, p);
+		mu_push(J, r);
+		return 1;
+	}
+	JS_FreeValue(J->ctx, p);
+	mu_push(J, JS_UNDEFINED);
+	return 0;
+}
+
 int js_ploadstring(js_State *J, const char *filename, const char *source)
 {
 	JSValue f = mu_compile(J, filename, source);

+ 12 - 0
js_mu.h

@@ -44,6 +44,18 @@ void js_setlimit(js_State *J, int limit_ms, int memlimit);
 /* Run queued Promise jobs (then/await continuations). */
 void js_runjobs(js_State *J);
 
+/* ES modules.  resolve() turns a specifier into an absolute URL relative to
+ * the importing module (return 0 on success); load() returns the module
+ * source as a malloc()ed NUL-terminated string (NULL on failure). */
+typedef int (*js_ModuleResolve)(const char *base, const char *name,
+				char *out, unsigned int cap);
+typedef char *(*js_ModuleLoad)(const char *url, unsigned int *len);
+void js_setmodulehost(js_State *J, js_ModuleResolve resolve,
+		      js_ModuleLoad load);
+/* Compile, link and evaluate a module and run the resulting jobs.  Returns
+ * 0 (undefined pushed) or 1 with the error value pushed. */
+int js_ploadmodule(js_State *J, const char *filename, const char *source);
+
 int js_ploadstring(js_State *J, const char *filename, const char *source);
 void js_loadstring(js_State *J, const char *filename, const char *source);
 int js_pcall(js_State *J, int n);

+ 8 - 0
js_prelude.S

@@ -0,0 +1,8 @@
+/* Embeds js_prelude.js (the browser's Web API layer) as a NUL-terminated
+ * string for js_browser.c. */
+	.section .rodata
+	.globl js_prelude_source
+js_prelude_source:
+	.incbin "js_prelude.js"
+	.byte 0
+	.section .note.GNU-stack,"",@progbits

+ 1132 - 0
js_prelude.js

@@ -0,0 +1,1132 @@
+/* Web platform APIs for the NebOS browser, written in JavaScript on top of a
+ * few C primitives (js_browser.c):
+ *   __nb_http(method, url, contentType, body) -> [status, ctype, finalUrl, text]
+ *   __nb_storage(kind[, text])  kind 0 = localStorage, 1 = sessionStorage
+ *   __nb_resolve(base, relative) -> absolute URL
+ *   __nb_nodeproto              prototype shared by every DOM node wrapper
+ * It runs once per page state, before the page's scripts; the primitives are
+ * removed from the global object afterwards.  Embedded by js_prelude.S. */
+(function (g) {
+"use strict";
+var http = g.__nb_http, storage = g.__nb_storage, resolve = g.__nb_resolve;
+var nodeproto = g.__nb_nodeproto;
+delete g.__nb_http; delete g.__nb_storage; delete g.__nb_resolve;
+delete g.__nb_nodeproto;
+var hasOwn = Object.prototype.hasOwnProperty;
+
+function def(name, value) {
+	Object.defineProperty(g, name, { value: value, writable: true,
+		configurable: true, enumerable: false });
+}
+
+/* ---- console, timers, misc globals ---- */
+var con = g.console, rawlog = con.log;
+/* Errors print with their stack (Vue reports caught errors this way). */
+function fmt(a) {
+	if (a instanceof Error)
+		return a.name + ": " + a.message + (a.stack ? "\n" + a.stack : "");
+	if (a !== null && typeof a === "object" && !(typeof a.nodeType === "number")) {
+		try { return JSON.stringify(a); } catch (e) { return String(a); }
+	}
+	return a;
+}
+function logger(prefix) {
+	return function () {
+		var args = Array.prototype.map.call(arguments, fmt);
+		if (prefix) args.unshift(prefix);
+		rawlog.apply(con, args);
+	};
+}
+con.log = logger("");
+con.info = logger("");
+con.debug = logger("");
+con.dir = logger("");
+con.warn = logger("[warn]");
+con.error = logger("[error]");
+con.trace = logger("[trace]");
+["group", "groupCollapsed", "groupEnd", "time", "timeEnd", "timeLog",
+ "table", "count", "countReset", "clear"].forEach(function (k) {
+	if (!con[k]) con[k] = function () {};
+});
+con.assert = function (c) {
+	if (!c) con.log.apply(con, ["Assertion failed:"].concat(
+		Array.prototype.slice.call(arguments, 1)));
+};
+def("self", g); def("top", g); def("parent", g); def("frames", g);
+def("isSecureContext", true);
+def("origin", g.location.origin);
+def("queueMicrotask", function (f) { Promise.resolve().then(f); });
+def("requestIdleCallback", function (f) {
+	return setTimeout(function () {
+		f({ didTimeout: false, timeRemaining: function () { return 10; } });
+	}, 1);
+});
+def("cancelIdleCallback", function (id) { clearTimeout(id); });
+def("structuredClone", function (v) {
+	return v === undefined ? v : JSON.parse(JSON.stringify(v));
+});
+
+class DOMException extends Error {
+	constructor(message, name) {
+		super(message === undefined ? "" : message);
+		this.name = name === undefined ? "Error" : name;
+	}
+}
+def("DOMException", DOMException);
+
+/* ---- base64 ---- */
+var B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+def("btoa", function (s) {
+	s = String(s);
+	var out = "", i;
+	for (i = 0; i < s.length; i += 3) {
+		var a = s.charCodeAt(i), b = s.charCodeAt(i + 1),
+		    c = s.charCodeAt(i + 2);
+		if (a > 255 || b > 255 || c > 255)
+			throw new DOMException("Invalid character",
+					       "InvalidCharacterError");
+		var n = (a << 16) | ((b || 0) << 8) | (c || 0);
+		out += B64[n >> 18 & 63] + B64[n >> 12 & 63] +
+			(i + 1 < s.length ? B64[n >> 6 & 63] : "=") +
+			(i + 2 < s.length ? B64[n & 63] : "=");
+	}
+	return out;
+});
+def("atob", function (s) {
+	s = String(s).replace(/[\s=]/g, "");
+	var out = "", bits = 0, acc = 0, i;
+	for (i = 0; i < s.length; i++) {
+		var v = B64.indexOf(s[i]);
+		if (v < 0)
+			throw new DOMException("Invalid character",
+					       "InvalidCharacterError");
+		acc = (acc << 6) | v;
+		bits += 6;
+		if (bits >= 8) {
+			bits -= 8;
+			out += String.fromCharCode((acc >> bits) & 255);
+		}
+	}
+	return out;
+});
+
+/* ---- text encoding ---- */
+function utf8(s) {
+	var out = [], i;
+	s = String(s);
+	for (i = 0; i < s.length; i++) {
+		var c = s.charCodeAt(i);
+		if (c >= 0xd800 && c < 0xdc00 && i + 1 < s.length) {
+			var d = s.charCodeAt(i + 1);
+			if (d >= 0xdc00 && d < 0xe000) {
+				c = 0x10000 + ((c - 0xd800) << 10) + (d - 0xdc00);
+				i++;
+			}
+		}
+		if (c < 0x80) out.push(c);
+		else if (c < 0x800) out.push(0xc0 | c >> 6, 0x80 | c & 63);
+		else if (c < 0x10000)
+			out.push(0xe0 | c >> 12, 0x80 | c >> 6 & 63, 0x80 | c & 63);
+		else
+			out.push(0xf0 | c >> 18, 0x80 | c >> 12 & 63,
+				 0x80 | c >> 6 & 63, 0x80 | c & 63);
+	}
+	return new Uint8Array(out);
+}
+function bytesOf(b) {
+	if (b instanceof ArrayBuffer) return new Uint8Array(b);
+	if (ArrayBuffer.isView(b))
+		return new Uint8Array(b.buffer, b.byteOffset, b.byteLength);
+	return utf8(b);
+}
+function unutf8(u) {
+	var s = "", i = 0;
+	while (i < u.length) {
+		var c = u[i++];
+		if (c >= 0xf0 && i + 2 < u.length + 0) {
+			c = ((c & 7) << 18) | ((u[i++] & 63) << 12) |
+			    ((u[i++] & 63) << 6) | (u[i++] & 63);
+		} else if (c >= 0xe0) {
+			c = ((c & 15) << 12) | ((u[i++] & 63) << 6) | (u[i++] & 63);
+		} else if (c >= 0xc0) {
+			c = ((c & 31) << 6) | (u[i++] & 63);
+		}
+		s += String.fromCodePoint(c);
+	}
+	return s;
+}
+class TextEncoder {
+	get encoding() { return "utf-8"; }
+	encode(s) { return utf8(s === undefined ? "" : s); }
+}
+class TextDecoder {
+	constructor(label) { this.encoding = "utf-8"; }
+	decode(b) { return b ? unutf8(bytesOf(b)) : ""; }
+}
+def("TextEncoder", TextEncoder);
+def("TextDecoder", TextDecoder);
+
+/* ---- URLSearchParams / URL ---- */
+function qenc(s) {
+	return encodeURIComponent(s).replace(/%20/g, "+").replace(/[!'()~]/g,
+		function (c) {
+			return "%" + c.charCodeAt(0).toString(16).toUpperCase();
+		});
+}
+function qdec(s) {
+	s = s.replace(/\+/g, " ");
+	try { return decodeURIComponent(s); } catch (e) { return s; }
+}
+class URLSearchParams {
+	constructor(init) {
+		this._l = [];
+		this._url = null;
+		if (init == null) return;
+		if (init instanceof URLSearchParams) {
+			this._l = init._l.map(function (p) { return [p[0], p[1]]; });
+			return;
+		}
+		if (typeof init === "object" || typeof init === "function") {
+			if (typeof init[Symbol.iterator] === "function") {
+				for (var p of init)
+					this._l.push([String(p[0]), String(p[1])]);
+			} else {
+				for (var k of Object.keys(init))
+					this._l.push([k, String(init[k])]);
+			}
+			return;
+		}
+		this._parse(String(init));
+	}
+	_parse(s) {
+		this._l = [];
+		if (s[0] === "?") s = s.slice(1);
+		for (var part of s.split("&")) {
+			if (!part) continue;
+			var i = part.indexOf("=");
+			this._l.push(i < 0 ? [qdec(part), ""] :
+				[qdec(part.slice(0, i)), qdec(part.slice(i + 1))]);
+		}
+	}
+	_upd() {
+		if (this._url) {
+			var s = this.toString();
+			this._url._search = s ? "?" + s : "";
+		}
+	}
+	append(k, v) { this._l.push([String(k), String(v)]); this._upd(); }
+	delete(k) {
+		k = String(k);
+		this._l = this._l.filter(function (p) { return p[0] !== k; });
+		this._upd();
+	}
+	get(k) {
+		k = String(k);
+		for (var p of this._l) if (p[0] === k) return p[1];
+		return null;
+	}
+	getAll(k) {
+		k = String(k);
+		return this._l.filter(function (p) { return p[0] === k; })
+			.map(function (p) { return p[1]; });
+	}
+	has(k) { return this.get(k) !== null; }
+	set(k, v) {
+		k = String(k); v = String(v);
+		var found = false;
+		this._l = this._l.filter(function (p) {
+			if (p[0] !== k) return true;
+			if (found) return false;
+			found = true;
+			p[1] = v;
+			return true;
+		});
+		if (!found) this._l.push([k, v]);
+		this._upd();
+	}
+	sort() {
+		this._l.sort(function (a, b) {
+			return a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0;
+		});
+		this._upd();
+	}
+	forEach(f, t) { for (var p of this._l.slice()) f.call(t, p[1], p[0], this); }
+	keys() { return this._l.map(function (p) { return p[0]; })[Symbol.iterator](); }
+	values() { return this._l.map(function (p) { return p[1]; })[Symbol.iterator](); }
+	entries() { return this._l.map(function (p) { return [p[0], p[1]]; })[Symbol.iterator](); }
+	[Symbol.iterator]() { return this.entries(); }
+	get size() { return this._l.length; }
+	toString() {
+		return this._l.map(function (p) {
+			return qenc(p[0]) + "=" + qenc(p[1]);
+		}).join("&");
+	}
+}
+def("URLSearchParams", URLSearchParams);
+
+var URL_RE = /^([a-zA-Z][a-zA-Z0-9+.\-]*:)(\/\/([^\/?#]*))?([^?#]*)(\?[^#]*)?(#.*)?$/;
+class URL {
+	constructor(url, base) {
+		url = String(url).trim();
+		if (!/^[a-zA-Z][a-zA-Z0-9+.\-]*:/.test(url)) {
+			if (base === undefined)
+				throw new TypeError("Invalid URL: " + url);
+			base = new URL(String(base)).href;
+			url = resolve(base, url);
+		}
+		this._parse(url);
+	}
+	_parse(u) {
+		var m = URL_RE.exec(u);
+		if (!m) throw new TypeError("Invalid URL: " + u);
+		this._protocol = m[1].toLowerCase();
+		var auth = m[3] || "", at = auth.lastIndexOf("@");
+		this._user = "";
+		this._pass = "";
+		if (at >= 0) {
+			var ui = auth.slice(0, at), c = ui.indexOf(":");
+			auth = auth.slice(at + 1);
+			this._user = c < 0 ? ui : ui.slice(0, c);
+			this._pass = c < 0 ? "" : ui.slice(c + 1);
+		}
+		var pm = /^(\[[^\]]*\]|[^:]*)(?::(\d*))?$/.exec(auth);
+		this._hostname = (pm ? pm[1] : auth).toLowerCase();
+		this._port = (pm && pm[2]) || "";
+		if ((this._protocol === "https:" && this._port === "443") ||
+		    (this._protocol === "http:" && this._port === "80"))
+			this._port = "";
+		this._special = m[2] !== undefined;
+		this._pathname = m[4] || (this._special ? "/" : "");
+		this._search = m[5] && m[5].length > 1 ? m[5] : "";
+		this._hash = m[6] && m[6].length > 1 ? m[6] : "";
+		if (this._sp) this._sp._parse(this._search);
+	}
+	get protocol() { return this._protocol; }
+	set protocol(v) {
+		v = String(v);
+		this._protocol = (v.endsWith(":") ? v : v + ":").toLowerCase();
+	}
+	get username() { return this._user; }
+	set username(v) { this._user = String(v); }
+	get password() { return this._pass; }
+	set password(v) { this._pass = String(v); }
+	get hostname() { return this._hostname; }
+	set hostname(v) { this._hostname = String(v).toLowerCase(); }
+	get port() { return this._port; }
+	set port(v) { this._port = String(v); }
+	get host() { return this._hostname + (this._port ? ":" + this._port : ""); }
+	set host(v) {
+		var m = /^(\[[^\]]*\]|[^:]*)(?::(\d*))?$/.exec(String(v));
+		if (m) { this._hostname = m[1].toLowerCase(); this._port = m[2] || ""; }
+	}
+	get pathname() { return this._pathname; }
+	set pathname(v) {
+		v = String(v);
+		this._pathname = this._special && v[0] !== "/" ? "/" + v : v;
+	}
+	get search() { return this._search; }
+	set search(v) {
+		v = String(v);
+		if (v && v[0] !== "?") v = "?" + v;
+		this._search = v === "?" ? "" : v;
+		if (this._sp) this._sp._parse(this._search);
+	}
+	get hash() { return this._hash; }
+	set hash(v) {
+		v = String(v);
+		if (v && v[0] !== "#") v = "#" + v;
+		this._hash = v === "#" ? "" : v;
+	}
+	get origin() {
+		return this._special && this._protocol !== "file:" ?
+			this._protocol + "//" + this.host : "null";
+	}
+	get href() {
+		var a = this._user ? this._user +
+			(this._pass ? ":" + this._pass : "") + "@" : "";
+		return this._protocol + (this._special ? "//" + a + this.host : "") +
+			this._pathname + this._search + this._hash;
+	}
+	set href(v) { this._parse(String(v)); }
+	get searchParams() {
+		if (!this._sp) {
+			this._sp = new URLSearchParams(this._search);
+			this._sp._url = this;
+		}
+		return this._sp;
+	}
+	toString() { return this.href; }
+	toJSON() { return this.href; }
+	static canParse(u, b) {
+		try { new URL(u, b); return true; } catch (e) { return false; }
+	}
+	static parse(u, b) {
+		try { return new URL(u, b); } catch (e) { return null; }
+	}
+	static createObjectURL() { return "blob:nebos/" + Date.now(); }
+	static revokeObjectURL() {}
+}
+def("URL", URL);
+def("webkitURL", URL);
+
+/* ---- Headers / Blob / FormData / Request / Response ---- */
+class Headers {
+	constructor(init) {
+		this._m = new Map();
+		if (!init) return;
+		if (init instanceof Headers)
+			init.forEach((v, k) => this.append(k, v));
+		else if (typeof init[Symbol.iterator] === "function")
+			for (var p of init) this.append(p[0], p[1]);
+		else
+			for (var k of Object.keys(init)) this.append(k, init[k]);
+	}
+	append(k, v) {
+		k = String(k).toLowerCase();
+		var o = this._m.get(k);
+		this._m.set(k, o !== undefined ? o + ", " + v : String(v));
+	}
+	set(k, v) { this._m.set(String(k).toLowerCase(), String(v)); }
+	get(k) {
+		var v = this._m.get(String(k).toLowerCase());
+		return v === undefined ? null : v;
+	}
+	has(k) { return this._m.has(String(k).toLowerCase()); }
+	delete(k) { this._m.delete(String(k).toLowerCase()); }
+	forEach(f, t) { for (var [k, v] of this._m) f.call(t, v, k, this); }
+	keys() { return this._m.keys(); }
+	values() { return this._m.values(); }
+	entries() { return this._m.entries(); }
+	[Symbol.iterator]() { return this._m.entries(); }
+}
+def("Headers", Headers);
+
+function partText(p) {
+	if (typeof p === "string") return p;
+	if (p instanceof Blob) return p._s;
+	if (p instanceof ArrayBuffer || ArrayBuffer.isView(p))
+		return unutf8(bytesOf(p));
+	return String(p);
+}
+class Blob {
+	constructor(parts, opts) {
+		this._s = (parts || []).map(partText).join("");
+		this.type = (opts && opts.type) || "";
+	}
+	get size() { return utf8(this._s).length; }
+	text() { return Promise.resolve(this._s); }
+	arrayBuffer() { return Promise.resolve(utf8(this._s).buffer); }
+	slice(a, b, t) { return new Blob([this._s.slice(a, b)], { type: t }); }
+}
+class File extends Blob {
+	constructor(parts, name, opts) {
+		super(parts, opts);
+		this.name = String(name);
+		this.lastModified = (opts && opts.lastModified) || Date.now();
+	}
+}
+def("Blob", Blob);
+def("File", File);
+
+class FormData {
+	constructor() { this._l = []; }
+	append(k, v) { this._l.push([String(k), v]); }
+	set(k, v) { this.delete(k); this.append(k, v); }
+	get(k) {
+		for (var p of this._l) if (p[0] === k) return p[1];
+		return null;
+	}
+	getAll(k) {
+		return this._l.filter(function (p) { return p[0] === k; })
+			.map(function (p) { return p[1]; });
+	}
+	has(k) { return this.get(k) !== null; }
+	delete(k) { this._l = this._l.filter(function (p) { return p[0] !== k; }); }
+	forEach(f, t) { for (var p of this._l) f.call(t, p[1], p[0], this); }
+	entries() { return this._l.map(function (p) { return [p[0], p[1]]; })[Symbol.iterator](); }
+	keys() { return this._l.map(function (p) { return p[0]; })[Symbol.iterator](); }
+	values() { return this._l.map(function (p) { return p[1]; })[Symbol.iterator](); }
+	[Symbol.iterator]() { return this.entries(); }
+}
+def("FormData", FormData);
+
+class AbortSignal {
+	constructor() {
+		this.aborted = false;
+		this.reason = undefined;
+		this.onabort = null;
+		this._l = [];
+	}
+	addEventListener(t, f) { if (t === "abort") this._l.push(f); }
+	removeEventListener(t, f) { this._l = this._l.filter(function (x) { return x !== f; }); }
+	throwIfAborted() { if (this.aborted) throw this.reason; }
+	static abort(r) { var c = new AbortController(); c.abort(r); return c.signal; }
+	static timeout(ms) {
+		var c = new AbortController();
+		setTimeout(function () {
+			c.abort(new DOMException("signal timed out", "TimeoutError"));
+		}, ms);
+		return c.signal;
+	}
+}
+class AbortController {
+	constructor() { this.signal = new AbortSignal(); }
+	abort(r) {
+		var s = this.signal, ev;
+		if (s.aborted) return;
+		s.aborted = true;
+		s.reason = r === undefined ?
+			new DOMException("signal is aborted without reason",
+					 "AbortError") : r;
+		ev = { type: "abort", target: s };
+		if (typeof s.onabort === "function") s.onabort(ev);
+		s._l.forEach(function (f) { f(ev); });
+	}
+}
+def("AbortSignal", AbortSignal);
+def("AbortController", AbortController);
+
+class Request {
+	constructor(input, init) {
+		init = init || {};
+		if (input instanceof Request) {
+			this.url = input.url;
+			this.method = input.method;
+			this.headers = new Headers(input.headers);
+			this.body = input.body;
+			this.signal = input.signal;
+		} else {
+			this.url = new URL(String(input), g.location.href).href;
+			this.method = "GET";
+			this.headers = new Headers();
+			this.body = null;
+			this.signal = null;
+		}
+		if (init.method) this.method = String(init.method).toUpperCase();
+		if (init.headers) this.headers = new Headers(init.headers);
+		if (init.body !== undefined) this.body = init.body;
+		if (init.signal) this.signal = init.signal;
+		this.credentials = init.credentials || "same-origin";
+		this.mode = init.mode || "cors";
+	}
+	clone() { return new Request(this); }
+}
+def("Request", Request);
+
+class Response {
+	constructor(body, init) {
+		init = init || {};
+		this._b = body == null ? "" : partText(body);
+		this.status = init.status === undefined ? 200 : init.status;
+		this.statusText = init.statusText || "";
+		this.headers = init.headers instanceof Headers ? init.headers :
+			new Headers(init.headers);
+		this.ok = this.status >= 200 && this.status < 300;
+		this.url = init.url || "";
+		this.redirected = !!init.redirected;
+		this.type = "basic";
+		this.bodyUsed = false;
+		this.body = null;
+	}
+	text() { this.bodyUsed = true; return Promise.resolve(this._b); }
+	json() {
+		this.bodyUsed = true;
+		try { return Promise.resolve(JSON.parse(this._b)); }
+		catch (e) { return Promise.reject(e); }
+	}
+	blob() {
+		this.bodyUsed = true;
+		return Promise.resolve(new Blob([this._b],
+			{ type: this.headers.get("content-type") || "" }));
+	}
+	arrayBuffer() { this.bodyUsed = true; return Promise.resolve(utf8(this._b).buffer); }
+	formData() { return Promise.reject(new TypeError("formData() is not supported")); }
+	clone() {
+		return new Response(this._b, { status: this.status,
+			statusText: this.statusText, url: this.url,
+			headers: new Headers(this.headers) });
+	}
+	static json(data, init) {
+		var h = new Headers(init && init.headers);
+		h.set("content-type", "application/json");
+		return new Response(JSON.stringify(data),
+			Object.assign({}, init, { headers: h }));
+	}
+	static error() { return new Response(null, { status: 0 }); }
+	static redirect(url, status) {
+		return new Response(null, { status: status || 302,
+			headers: { location: String(url) } });
+	}
+}
+def("Response", Response);
+
+var STATUS_TEXT = { 200: "OK", 201: "Created", 204: "No Content",
+	301: "Moved Permanently", 302: "Found", 303: "See Other",
+	304: "Not Modified", 400: "Bad Request", 401: "Unauthorized",
+	403: "Forbidden", 404: "Not Found", 409: "Conflict", 410: "Gone",
+	500: "Internal Server Error", 502: "Bad Gateway",
+	503: "Service Unavailable" };
+
+/* One synchronous request through the browser's fetch helpers. */
+function send(method, url, headers, body) {
+	var ct = headers.get("content-type");
+	if (body instanceof URLSearchParams) {
+		if (!ct) ct = "application/x-www-form-urlencoded;charset=UTF-8";
+		body = body.toString();
+	} else if (body instanceof FormData) {
+		var sp = new URLSearchParams();
+		body.forEach(function (v, k) {
+			sp.append(k, typeof v === "string" ? v : "");
+		});
+		body = sp.toString();
+		ct = "application/x-www-form-urlencoded;charset=UTF-8";
+	} else if (body instanceof Blob) {
+		if (!ct) ct = body.type;
+		body = body._s;
+	} else if (body != null && typeof body !== "string") {
+		body = partText(body);
+	} else if (typeof body === "string" && !ct) {
+		ct = "text/plain;charset=UTF-8";
+	}
+	if (method === "GET" || method === "HEAD") body = null;
+	var r = http(method, url, ct || "", body == null ? "" : body);
+	var h = new Headers();
+	if (r[1]) h.set("content-type", r[1]);
+	return { status: r[0], headers: h, url: r[2] || url, text: r[3] };
+}
+
+def("fetch", function (input, init) {
+	return new Promise(function (res, rej) {
+		var req, out;
+		try {
+			req = new Request(input, init);
+		} catch (e) {
+			rej(e);
+			return;
+		}
+		if (req.signal && req.signal.aborted) {
+			rej(req.signal.reason);
+			return;
+		}
+		try {
+			out = send(req.method, req.url, req.headers, req.body);
+		} catch (e) {
+			rej(new TypeError("Failed to fetch"));
+			return;
+		}
+		res(new Response(out.text, { status: out.status,
+			statusText: STATUS_TEXT[out.status] || "",
+			headers: out.headers, url: out.url,
+			redirected: out.url !== req.url }));
+	});
+});
+
+/* XMLHttpRequest on the same synchronous path; events fire asynchronously
+ * (from a timer) so the caller can finish wiring its handlers. */
+class XMLHttpRequest {
+	constructor() {
+		this.readyState = 0;
+		this.status = 0;
+		this.statusText = "";
+		this.responseText = "";
+		this.response = "";
+		this.responseType = "";
+		this.responseURL = "";
+		this.timeout = 0;
+		this.withCredentials = false;
+		this._h = new Headers();
+		this._rh = new Headers();
+		this._l = {};
+		this.upload = { addEventListener: function () {} };
+	}
+	open(method, url) {
+		this._m = String(method).toUpperCase();
+		this._u = new URL(String(url), g.location.href).href;
+		this.readyState = 1;
+	}
+	setRequestHeader(k, v) { this._h.append(k, v); }
+	getResponseHeader(k) { return this._rh.get(k); }
+	getAllResponseHeaders() {
+		var s = "";
+		this._rh.forEach(function (v, k) { s += k + ": " + v + "\r\n"; });
+		return s;
+	}
+	overrideMimeType() {}
+	addEventListener(t, f) { (this._l[t] = this._l[t] || []).push(f); }
+	removeEventListener(t, f) {
+		if (this._l[t]) this._l[t] = this._l[t].filter(function (x) { return x !== f; });
+	}
+	_fire(t) {
+		var ev = { type: t, target: this, currentTarget: this,
+			   lengthComputable: false, loaded: 0, total: 0 };
+		if (typeof this["on" + t] === "function") this["on" + t](ev);
+		(this._l[t] || []).slice().forEach((f) => f.call(this, ev));
+	}
+	abort() { this._aborted = true; }
+	send(body) {
+		var self = this, out, err = false;
+		try {
+			out = send(this._m, this._u, this._h, body);
+		} catch (e) {
+			err = true;
+		}
+		setTimeout(function () {
+			if (self._aborted) return;
+			if (err) {
+				self.readyState = 4;
+				self._fire("readystatechange");
+				self._fire("error");
+				self._fire("loadend");
+				return;
+			}
+			self.status = out.status;
+			self.statusText = STATUS_TEXT[out.status] || "";
+			self._rh = out.headers;
+			self.responseURL = out.url;
+			self.responseText = out.text;
+			if (self.responseType === "json") {
+				try { self.response = JSON.parse(out.text); }
+				catch (e) { self.response = null; }
+			} else {
+				self.response = out.text;
+			}
+			self.readyState = 4;
+			self._fire("readystatechange");
+			self._fire("load");
+			self._fire("loadend");
+		}, 0);
+	}
+}
+XMLHttpRequest.UNSENT = 0;
+XMLHttpRequest.OPENED = 1;
+XMLHttpRequest.HEADERS_RECEIVED = 2;
+XMLHttpRequest.LOADING = 3;
+XMLHttpRequest.DONE = 4;
+def("XMLHttpRequest", XMLHttpRequest);
+
+/* ---- Web Storage, persisted by the host per origin ---- */
+function makeStorage(kind) {
+	var data = {};
+	try {
+		var t = storage(kind);
+		if (t) data = JSON.parse(t) || {};
+	} catch (e) {
+		data = {};
+	}
+	function save() { storage(kind, JSON.stringify(data)); }
+	var api = {
+		getItem: function (k) {
+			k = String(k);
+			return hasOwn.call(data, k) ? data[k] : null;
+		},
+		setItem: function (k, v) { data[String(k)] = String(v); save(); },
+		removeItem: function (k) { delete data[String(k)]; save(); },
+		clear: function () { data = {}; save(); },
+		key: function (i) {
+			var k = Object.keys(data);
+			return i < k.length ? k[i] : null;
+		}
+	};
+	return new Proxy({}, {
+		get: function (t, k) {
+			if (typeof k === "symbol") return undefined;
+			if (k === "length") return Object.keys(data).length;
+			if (hasOwn.call(api, k)) return api[k];
+			return hasOwn.call(data, k) ? data[k] : undefined;
+		},
+		set: function (t, k, v) {
+			if (typeof k === "symbol") return true;
+			data[k] = String(v);
+			save();
+			return true;
+		},
+		has: function (t, k) {
+			return typeof k === "string" &&
+				(k === "length" || hasOwn.call(api, k) || hasOwn.call(data, k));
+		},
+		deleteProperty: function (t, k) {
+			if (typeof k === "string" && hasOwn.call(data, k)) {
+				delete data[k];
+				save();
+			}
+			return true;
+		},
+		ownKeys: function () { return Object.keys(data); },
+		getOwnPropertyDescriptor: function (t, k) {
+			if (typeof k === "string" && hasOwn.call(data, k))
+				return { value: data[k], writable: true,
+					 enumerable: true, configurable: true };
+			return undefined;
+		}
+	});
+}
+def("localStorage", makeStorage(0));
+def("sessionStorage", makeStorage(1));
+
+/* ---- crypto ---- */
+var K256 = [
+	0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
+	0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
+	0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
+	0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
+	0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
+	0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
+	0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
+	0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
+	0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
+	0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
+	0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2];
+function sha256(msg) {
+	var h = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
+		 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
+	var len = msg.length, n = ((len + 9 + 63) >> 6) << 6;
+	var b = new Uint8Array(n), w = new Array(64), i, j;
+	b.set(msg);
+	b[len] = 0x80;
+	b[n - 4] = (len * 8) >>> 24;
+	b[n - 3] = (len * 8) >>> 16 & 255;
+	b[n - 2] = (len * 8) >>> 8 & 255;
+	b[n - 1] = (len * 8) & 255;
+	b[n - 5] = Math.floor(len / 0x20000000) & 255;
+	function rotr(x, r) { return (x >>> r) | (x << (32 - r)); }
+	for (i = 0; i < n; i += 64) {
+		for (j = 0; j < 16; j++)
+			w[j] = (b[i + 4 * j] << 24) | (b[i + 4 * j + 1] << 16) |
+			       (b[i + 4 * j + 2] << 8) | b[i + 4 * j + 3];
+		for (j = 16; j < 64; j++) {
+			var s0 = rotr(w[j - 15], 7) ^ rotr(w[j - 15], 18) ^ (w[j - 15] >>> 3);
+			var s1 = rotr(w[j - 2], 17) ^ rotr(w[j - 2], 19) ^ (w[j - 2] >>> 10);
+			w[j] = (w[j - 16] + s0 + w[j - 7] + s1) | 0;
+		}
+		var a = h[0], bb = h[1], c = h[2], d = h[3], e = h[4], f = h[5],
+		    gg = h[6], hh = h[7];
+		for (j = 0; j < 64; j++) {
+			var S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
+			var ch = (e & f) ^ (~e & gg);
+			var t1 = (hh + S1 + ch + K256[j] + w[j]) | 0;
+			var S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
+			var mj = (a & bb) ^ (a & c) ^ (bb & c);
+			var t2 = (S0 + mj) | 0;
+			hh = gg; gg = f; f = e; e = (d + t1) | 0;
+			d = c; c = bb; bb = a; a = (t1 + t2) | 0;
+		}
+		h[0] = (h[0] + a) | 0; h[1] = (h[1] + bb) | 0;
+		h[2] = (h[2] + c) | 0; h[3] = (h[3] + d) | 0;
+		h[4] = (h[4] + e) | 0; h[5] = (h[5] + f) | 0;
+		h[6] = (h[6] + gg) | 0; h[7] = (h[7] + hh) | 0;
+	}
+	var out = new Uint8Array(32);
+	for (i = 0; i < 8; i++) {
+		out[4 * i] = h[i] >>> 24;
+		out[4 * i + 1] = h[i] >>> 16 & 255;
+		out[4 * i + 2] = h[i] >>> 8 & 255;
+		out[4 * i + 3] = h[i] & 255;
+	}
+	return out;
+}
+/* The entropy is weak (Math.random seeded from the clock, stirred with the
+ * millisecond timer), like the TLS DRBG; fine for PKCE nonces on a hobby
+ * OS, not for long-term keys. */
+var rngState = sha256(utf8(String(Date.now()) + ":" + Math.random() + ":" +
+			   g.performance.now()));
+var rngPos = 0;
+function randomByte() {
+	if (rngPos >= 32) {
+		var seed = new Uint8Array(40);
+		seed.set(rngState);
+		var t = g.performance.now() * 1000 + Math.random() * 4294967296;
+		for (var i = 0; i < 8; i++)
+			seed[32 + i] = Math.floor(t / Math.pow(256, i)) & 255;
+		rngState = sha256(seed);
+		rngPos = 0;
+	}
+	return rngState[rngPos++];
+}
+var subtle = {
+	digest: function (alg, data) {
+		var name = typeof alg === "string" ? alg : alg && alg.name;
+		if (String(name).toUpperCase().replace("-", "") !== "SHA256")
+			return Promise.reject(new DOMException(
+				"Unsupported algorithm " + name, "NotSupportedError"));
+		return Promise.resolve(sha256(bytesOf(data)).buffer);
+	}
+};
+def("crypto", {
+	subtle: subtle,
+	getRandomValues: function (a) {
+		var u = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
+		for (var i = 0; i < u.length; i++) u[i] = randomByte();
+		return a;
+	},
+	randomUUID: function () {
+		var b = new Uint8Array(16), i, s = "";
+		this.getRandomValues(b);
+		b[6] = (b[6] & 0x0f) | 0x40;
+		b[8] = (b[8] & 0x3f) | 0x80;
+		for (i = 0; i < 16; i++) {
+			s += (b[i] + 0x100).toString(16).slice(1);
+			if (i === 3 || i === 5 || i === 7 || i === 9) s += "-";
+		}
+		return s;
+	}
+});
+
+/* ---- observers (no layout notifications yet: inert) ---- */
+class MutationObserver {
+	constructor(cb) { this._cb = cb; }
+	observe() {}
+	disconnect() {}
+	takeRecords() { return []; }
+}
+class ResizeObserver {
+	constructor(cb) { this._cb = cb; }
+	observe() {}
+	unobserve() {}
+	disconnect() {}
+}
+class IntersectionObserver {
+	constructor(cb, opts) { this._cb = cb; this.root = null; this.thresholds = [0]; }
+	observe() {}
+	unobserve() {}
+	disconnect() {}
+	takeRecords() { return []; }
+}
+def("MutationObserver", MutationObserver);
+def("ResizeObserver", ResizeObserver);
+def("IntersectionObserver", IntersectionObserver);
+
+/* ---- DOM classes: instanceof works on the node wrappers ---- */
+function domClass(name, test) {
+	var C = function () { throw new TypeError("Illegal constructor"); };
+	Object.defineProperty(C, "name", { value: name });
+	Object.defineProperty(C, Symbol.hasInstance, {
+		value: function (o) {
+			return o != null && typeof o === "object" &&
+				typeof o.nodeType === "number" && test(o);
+		}
+	});
+	C.prototype = nodeproto;
+	def(name, C);
+	return C;
+}
+function tag(t) { return function (o) { return o.nodeType === 1 && o.tagName === t; }; }
+domClass("EventTarget", function (o) { return true; });
+domClass("Node", function (o) { return true; });
+domClass("Element", function (o) { return o.nodeType === 1; });
+domClass("HTMLElement", function (o) { return o.nodeType === 1; });
+domClass("SVGElement", function (o) { return o.nodeType === 1 && o.namespaceURI === "http://www.w3.org/2000/svg"; });
+domClass("CharacterData", function (o) { return o.nodeType === 3 || o.nodeType === 8; });
+domClass("Text", function (o) { return o.nodeType === 3; });
+domClass("Comment", function (o) { return o.nodeType === 8; });
+domClass("DocumentFragment", function (o) { return o.nodeType === 11; });
+domClass("Document", function (o) { return o.nodeType === 9; });
+domClass("HTMLDocument", function (o) { return o.nodeType === 9; });
+domClass("HTMLInputElement", tag("INPUT"));
+domClass("HTMLTextAreaElement", tag("TEXTAREA"));
+domClass("HTMLSelectElement", tag("SELECT"));
+domClass("HTMLOptionElement", tag("OPTION"));
+domClass("HTMLButtonElement", tag("BUTTON"));
+domClass("HTMLFormElement", tag("FORM"));
+domClass("HTMLAnchorElement", tag("A"));
+domClass("HTMLImageElement", tag("IMG"));
+domClass("HTMLTemplateElement", tag("TEMPLATE"));
+domClass("HTMLIFrameElement", tag("IFRAME"));
+domClass("HTMLLinkElement", tag("LINK"));
+domClass("HTMLScriptElement", tag("SCRIPT"));
+domClass("HTMLStyleElement", tag("STYLE"));
+domClass("HTMLCanvasElement", tag("CANVAS"));
+def("Window", function Window() {});
+def("ShadowRoot", function ShadowRoot() {});
+
+var NodeConst = g.Node;
+[["ELEMENT_NODE", 1], ["ATTRIBUTE_NODE", 2], ["TEXT_NODE", 3],
+ ["CDATA_SECTION_NODE", 4], ["COMMENT_NODE", 8], ["DOCUMENT_NODE", 9],
+ ["DOCUMENT_TYPE_NODE", 10], ["DOCUMENT_FRAGMENT_NODE", 11]]
+	.forEach(function (p) { NodeConst[p[0]] = p[1]; });
+
+/* Methods every node wrapper inherits (the C has-hook answers the rest). */
+var doc = g.document;
+function toNode(n) {
+	return typeof n === "object" && n !== null ? n : doc.createTextNode(String(n));
+}
+Object.assign(nodeproto, {
+	setAttributeNS: function (ns, n, v) {
+		this.setAttribute(String(n).replace(/^[^:]*:/, ""), v);
+	},
+	getAttributeNS: function (ns, n) { return this.getAttribute(n); },
+	removeAttributeNS: function (ns, n) { this.removeAttribute(n); },
+	hasAttributeNS: function (ns, n) { return this.hasAttribute(n); },
+	toggleAttribute: function (n, force) {
+		var on = force === undefined ? !this.hasAttribute(n) : !!force;
+		if (on) this.setAttribute(n, "");
+		else this.removeAttribute(n);
+		return on;
+	},
+	getAttributeNames: function () {
+		var a = this.attributes, out = [], i;
+		for (i = 0; a && i < a.length; i++) out.push(a[i].name);
+		return out;
+	},
+	closest: function (sel) {
+		var e = this;
+		while (e && e.nodeType === 1) {
+			if (e.matches(sel)) return e;
+			e = e.parentNode;
+		}
+		return null;
+	},
+	append: function () {
+		for (var i = 0; i < arguments.length; i++)
+			this.appendChild(toNode(arguments[i]));
+	},
+	prepend: function () {
+		var first = this.firstChild;
+		for (var i = 0; i < arguments.length; i++)
+			this.insertBefore(toNode(arguments[i]), first);
+	},
+	before: function () {
+		var p = this.parentNode;
+		if (!p) return;
+		for (var i = 0; i < arguments.length; i++)
+			p.insertBefore(toNode(arguments[i]), this);
+	},
+	after: function () {
+		var p = this.parentNode, next = this.nextSibling;
+		if (!p) return;
+		for (var i = 0; i < arguments.length; i++)
+			p.insertBefore(toNode(arguments[i]), next);
+	},
+	replaceWith: function () {
+		var p = this.parentNode;
+		if (!p) return;
+		this.before.apply(this, arguments);
+		p.removeChild(this);
+	},
+	replaceChildren: function () {
+		while (this.firstChild) this.removeChild(this.firstChild);
+		this.append.apply(this, arguments);
+	},
+	insertAdjacentElement: function (pos, el) {
+		pos = String(pos).toLowerCase();
+		if (pos === "beforebegin") this.before(el);
+		else if (pos === "afterbegin") this.prepend(el);
+		else if (pos === "beforeend") this.appendChild(el);
+		else if (pos === "afterend") this.after(el);
+		return el;
+	},
+	insertAdjacentText: function (pos, text) {
+		this.insertAdjacentElement(pos, doc.createTextNode(String(text)));
+	},
+	insertAdjacentHTML: function (pos, html) {
+		var tmp = doc.createElement("div"), nodes = [], c;
+		tmp.innerHTML = html;
+		for (c = tmp.firstChild; c; c = c.nextSibling) nodes.push(c);
+		pos = String(pos).toLowerCase();
+		if (pos === "afterbegin") nodes.reverse();
+		for (c of nodes) {
+			tmp.removeChild(c);
+			this.insertAdjacentElement(pos, c);
+		}
+	},
+	getRootNode: function () { return doc; },
+	scrollIntoView: function () {},
+	scrollTo: function () {},
+	scrollBy: function () {},
+	animate: function () {
+		return { finished: Promise.resolve(), cancel: function () {},
+			 play: function () {}, pause: function () {},
+			 onfinish: null };
+	},
+	attachShadow: function () { return this; },
+	compareDocumentPosition: function (other) {
+		if (this === other) return 0;
+		if (this.contains(other)) return 20;
+		if (other.contains && other.contains(this)) return 10;
+		return 4;
+	},
+	isSameNode: function (o) { return this === o; },
+	normalize: function () {}
+});
+
+/* ---- document extras ---- */
+doc.createElementNS = function (ns, name) {
+	var el = doc.createElement(String(name).replace(/^[^:]*:/, ""));
+	if (ns === "http://www.w3.org/2000/svg")
+		el.setAttribute("xmlns", ns);
+	return el;
+};
+doc.createRange = function () {
+	return {
+		createContextualFragment: function (html) {
+			var tmp = doc.createElement("div"),
+			    frag = doc.createDocumentFragment();
+			tmp.innerHTML = html;
+			while (tmp.firstChild) frag.appendChild(tmp.firstChild);
+			return frag;
+		},
+		selectNodeContents: function () {},
+		setStart: function () {}, setEnd: function () {},
+		getBoundingClientRect: function () {
+			return { x: 0, y: 0, top: 0, left: 0, right: 0, bottom: 0,
+				 width: 0, height: 0 };
+		}
+	};
+};
+doc.createTreeWalker = undefined;
+doc.hasFocus = function () { return true; };
+doc.getElementsByName = function (n) {
+	return doc.querySelectorAll("[name=\"" + String(n).replace(/"/g, "\\\"") + "\"]");
+};
+doc.hidden = false;
+doc.visibilityState = "visible";
+doc.characterSet = "UTF-8";
+doc.charset = "UTF-8";
+doc.contentType = "text/html";
+doc.referrer = "";
+doc.dir = "";
+doc.fonts = { ready: Promise.resolve(), add: function () {},
+	      load: function () { return Promise.resolve([]); },
+	      check: function () { return true; },
+	      addEventListener: function () {} };
+doc.implementation = {
+	hasFeature: function () { return true; },
+	createHTMLDocument: function () { return doc; }
+};
+Object.defineProperty(doc, "activeElement", {
+	get: function () { return doc.body; }, configurable: true });
+Object.defineProperty(doc, "currentScript", {
+	get: function () { return null; }, configurable: true });
+Object.defineProperty(doc, "defaultView", {
+	get: function () { return g; }, configurable: true });
+
+var nav = g.navigator;
+nav.languages = [nav.language];
+nav.onLine = true;
+nav.cookieEnabled = true;
+nav.maxTouchPoints = 0;
+nav.hardwareConcurrency = 1;
+nav.vendor = "";
+nav.clipboard = {
+	writeText: function () { return Promise.resolve(); },
+	readText: function () { return Promise.resolve(""); }
+};
+nav.sendBeacon = function () { return true; };
+
+g.history.state = null;
+g.screen = { width: g.innerWidth, height: g.innerHeight,
+	     availWidth: g.innerWidth, availHeight: g.innerHeight,
+	     colorDepth: 16, pixelDepth: 16 };
+g.outerWidth = g.innerWidth;
+g.outerHeight = g.innerHeight;
+g.name = "";
+g.closed = false;
+g.open = function () { return null; };
+g.close = function () {};
+g.focus = function () {};
+g.blur = function () {};
+g.print = function () {};
+g.postMessage = function () {};
+g.confirm = function () { return true; };
+g.prompt = function () { return null; };
+g.dispatchEvent = g.dispatchEvent || function () { return true; };
+})(globalThis);

+ 76 - 7
ucmd_curl.c

@@ -13,6 +13,7 @@
 
 #include "ucmd_lib.h"
 #include "uhttp.h"
+#include "uhttp_cookie.h"
 
 #define LINE_MAX_C 320
 
@@ -61,7 +62,7 @@ static const struct uhttp_hooks hooks = {
 /* ---- headless fetch helper for the browser ---------------------------- */
 
 #define FETCH_PATH_MAX 32
-#define FETCH_POST_MAX 4096u
+#define FETCH_POST_MAX 16384u
 #define FETCH_MAX   (2u * 1024u * 1024u)
 
 /* Each browser worker gets its own set of /share files; slot -1 keeps the
@@ -140,6 +141,28 @@ static void fetch_fail(unsigned int status, int err, const char *ctype,
 	u_syscall3(SYS_WRITE_FILE, (int)fp.meta, (int)meta, (int)n);
 }
 
+/* One cookie jar for every helper of every browser window, kept in /share
+ * (RAM, cleared at reboot) so a login session survives helper restarts and
+ * the parallel workers.  Re-read before each request and written back when
+ * the response changed it; with several helpers the last writer wins. */
+#define FETCH_JAR_PATH "/share/bcookies"
+static struct uhttp_jar fetch_jar;
+
+static void jar_load(void)
+{
+	int n = u_syscall3(SYS_READ_FILE, (int)FETCH_JAR_PATH,
+			   (int)&fetch_jar, (int)sizeof(fetch_jar));
+
+	if (n != (int)sizeof(fetch_jar))
+		uhttp_jar_init(&fetch_jar);
+}
+
+static void jar_save(void)
+{
+	u_syscall3(SYS_WRITE_FILE, (int)FETCH_JAR_PATH, (int)&fetch_jar,
+		   (int)sizeof(fetch_jar));
+}
+
 struct fetch_times {
 	unsigned int open_ms;
 	unsigned int first_ms;
@@ -172,6 +195,7 @@ static void write_meta(unsigned int seq, int with_seq, struct uhttp *h,
 
 /* Fetch one URL through a possibly reused keep-alive connection. */
 static void helper_fetch(struct uhttp *h, const char *url, unsigned int cap,
+			 const char *method, const char *ctype,
 			 const char *post, unsigned int post_len,
 			 unsigned char *buf, unsigned int *outlen,
 			 unsigned int *outtrunc, int *outerr,
@@ -189,8 +213,11 @@ static void helper_fetch(struct uhttp *h, const char *url, unsigned int cap,
 		times->first_ms = 0;
 		times->total_ms = 0;
 	}
-	uhttp_set_method(h, post_len ? "POST" : 0, post, post_len,
-			 "application/x-www-form-urlencoded");
+	if (!method)
+		method = post_len ? "POST" : 0;
+	if (!ctype || !ctype[0])
+		ctype = "application/x-www-form-urlencoded";
+	uhttp_set_method(h, method, post, post_len, ctype);
 	rv = uhttp_open(h, url, UHTTP_GZIP, 0);
 	if (rv == UHTTP_ERR_BUSY) {
 		int tries;
@@ -279,7 +306,7 @@ static void fetch_once(void)
 
 	uhttp_init(&h);
 	h.user_agent = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36";
-	helper_fetch(&h, req + i, cap, 0, 0, buf, &body_len, &body_trunc, &err,
+	helper_fetch(&h, req + i, cap, 0, 0, 0, 0, buf, &body_len, &body_trunc, &err,
 		     &times);
 	if (body_len)
 		u_syscall3(SYS_WRITE_FILE, (int)fp.body, (int)buf,
@@ -330,10 +357,16 @@ static void fetch_serve(const char *arg)
 	h.user_agent = "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36";
 	h.keepalive = 1;
 
+	h.jar = &fetch_jar;
+
 	for (;;) {
 		unsigned int seq = 0, cap = 0, body_len = 0, body_trunc = 0;
-		unsigned int post_len = 0;
+		unsigned int post_len = 0, jar_changes;
 		int is_post = 0;
+		char method[12], ctype[96];
+
+		method[0] = '\0';
+		ctype[0] = '\0';
 		char done[16];
 		unsigned int dn = 0;
 		unsigned int i = 0;
@@ -358,7 +391,38 @@ static void fetch_serve(const char *arg)
 			}
 			while (req[i] == ' ')
 				i++;
-			if (!strncmp(req + i, "POST ", 5)) {
+			method[0] = '\0';
+			ctype[0] = '\0';
+			/* "X <method> <body length> <content type or -> <url>":
+			 * any method, for the browser's fetch()/XHR. */
+			if (!strncmp(req + i, "X ", 2)) {
+				unsigned int k = 0;
+
+				i += 2;
+				while (req[i] && req[i] != ' ' &&
+				       k + 1 < sizeof(method))
+					method[k++] = req[i++];
+				method[k] = '\0';
+				while (req[i] == ' ')
+					i++;
+				while (req[i] >= '0' && req[i] <= '9') {
+					post_len = post_len * 10 +
+						(unsigned int)(req[i] - '0');
+					i++;
+				}
+				while (req[i] == ' ')
+					i++;
+				k = 0;
+				while (req[i] && req[i] != ' ' &&
+				       k + 1 < sizeof(ctype))
+					ctype[k++] = req[i++];
+				ctype[k] = '\0';
+				if (!strcmp(ctype, "-"))
+					ctype[0] = '\0';
+				while (req[i] == ' ')
+					i++;
+				is_post = post_len > 0 || strcmp(method, "GET");
+			} else if (!strncmp(req + i, "POST ", 5)) {
 				is_post = 1;
 				i += 5;
 				while (req[i] >= '0' && req[i] <= '9') {
@@ -403,8 +467,13 @@ static void fetch_serve(const char *arg)
 			post_len = 0;
 		}
 
-		helper_fetch(&h, url, cap, is_post ? (char *)post : 0, post_len,
+		jar_load();
+		jar_changes = fetch_jar.changes;
+		helper_fetch(&h, url, cap, method[0] ? method : 0, ctype,
+			     post_len ? (char *)post : 0, post_len,
 			     buf, &body_len, &body_trunc, &err, &times);
+		if (fetch_jar.changes != jar_changes)
+			jar_save();
 		if (body_len)
 			u_syscall3(SYS_WRITE_FILE, (int)fp.body, (int)buf,
 				   (int)body_len);

+ 48 - 7
uhttp.c

@@ -113,13 +113,26 @@ int uhttp_parse_url(const char *s, struct uhttp_url *u)
 
 	i = 0;
 	if (*p == '/') {
-		while (p[i]) {
-			if (p[i] == '#')
-				break;
-			if (i + 1 >= UHTTP_PATH_MAX)
+		static const char hex[] = "0123456789ABCDEF";
+		unsigned int j = 0;
+
+		/* Percent-encode what cannot go on a request line (spaces,
+		 * controls, quotes, non-ASCII), like a browser does; scripts
+		 * build URLs such as "...&scope=openid email profile". */
+		while (p[j] && p[j] != '#') {
+			unsigned char c = (unsigned char)p[j++];
+			int esc = c <= ' ' || c >= 0x7F || c == '"' ||
+				  c == '<' || c == '>';
+
+			if (i + (esc ? 3u : 1u) >= UHTTP_PATH_MAX)
 				return UHTTP_ERR_URL;
-			u->path[i] = p[i];
-			i++;
+			if (esc) {
+				u->path[i++] = '%';
+				u->path[i++] = hex[c >> 4];
+				u->path[i++] = hex[c & 15];
+			} else {
+				u->path[i++] = (char)c;
+			}
 		}
 	}
 	u->path[i] = '\0';
@@ -160,9 +173,37 @@ static void url_build(const struct uhttp_url *u, char *out, unsigned int cap)
 	out[n] = '\0';
 }
 
+static int path_normalize_part(char *path);
+
 /* Normalize an absolute URL path in place: collapse "//", "." and "..".
- * 0 ok, -1 too long. */
+ * Only the path: a query or fragment is kept verbatim (it may carry a URL,
+ * e.g. ?redirect_uri=https://host/cb).  0 ok, -1 too long. */
 static int path_normalize(char *path)
+{
+	char rest[UHTTP_PATH_MAX];
+	unsigned int q = 0, i, n;
+	int rv;
+
+	while (path[q] && path[q] != '?' && path[q] != '#')
+		q++;
+	if (!path[q])
+		return path_normalize_part(path);
+	for (i = 0; path[q + i]; i++)
+		rest[i] = path[q + i];
+	rest[i] = '\0';
+	path[q] = '\0';
+	rv = path_normalize_part(path);
+	n = 0;
+	while (path[n])
+		n++;
+	if (rv != 0 || n + i + 1 > UHTTP_PATH_MAX)
+		return -1;
+	for (q = 0; q <= i; q++)
+		path[n + q] = rest[q];
+	return 0;
+}
+
+static int path_normalize_part(char *path)
 {
 	char tmp[UHTTP_PATH_MAX];
 	unsigned int i, o = 1, len = 0, start, seglen, j;

Некоторые файлы не были показаны из-за большого количества измененных файлов