brumate 0.0.1 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +43 -72
  2. package/dist/boot-DN1ZU8Hg.d.ts +37 -0
  3. package/dist/cli.js +2 -2
  4. package/dist/{client-DuDTDePF.d.ts → client-DwJInP_a.d.ts} +133 -44
  5. package/dist/client-routes-DakuM32C.js +94 -0
  6. package/dist/client-routes-DakuM32C.js.map +1 -0
  7. package/dist/{cookies-rgIAc8IE.js → cookies-Av5WFmcf.js} +18 -8
  8. package/dist/cookies-Av5WFmcf.js.map +1 -0
  9. package/dist/{devtools-Bm8cS7hX.js → devtools-BKjnHrnv.js} +10 -5
  10. package/dist/devtools-BKjnHrnv.js.map +1 -0
  11. package/dist/{devtools-panel-CTbDSBBA.js → devtools-panel-AWOn0VK2.js} +23 -26
  12. package/dist/devtools-panel-AWOn0VK2.js.map +1 -0
  13. package/dist/{files-D_JUcSU5.js → files-DdT84mPy.js} +22 -3
  14. package/dist/{files-D_JUcSU5.js.map → files-DdT84mPy.js.map} +1 -1
  15. package/dist/{html-CxWpXngy.js → html-DEeoepg3.js} +47 -10
  16. package/dist/html-DEeoepg3.js.map +1 -0
  17. package/dist/{html-DV-Tezgq.d.ts → html-Du8jY2Cc.d.ts} +14 -2
  18. package/dist/index.d.ts +65 -6
  19. package/dist/index.js +20 -4
  20. package/dist/index.js.map +1 -1
  21. package/dist/{inspect-CGCWfaEx.js → inspect-BPchdWbU.js} +887 -172
  22. package/dist/inspect-BPchdWbU.js.map +1 -0
  23. package/dist/loader-Dc9OwY5I.js +101 -0
  24. package/dist/loader-Dc9OwY5I.js.map +1 -0
  25. package/dist/{navigate-C5dP89YL.js → navigate-CzLjnoPH.js} +112 -59
  26. package/dist/navigate-CzLjnoPH.js.map +1 -0
  27. package/dist/{produce-BjQGMpqL.d.ts → produce-CtZ32UGG.d.ts} +13 -3
  28. package/dist/{rpc-B86KKjzx.js → rpc-9fSqL_YK.js} +57 -12
  29. package/dist/rpc-9fSqL_YK.js.map +1 -0
  30. package/dist/runtime/client.d.ts +4 -4
  31. package/dist/runtime/client.js +599 -306
  32. package/dist/runtime/client.js.map +1 -1
  33. package/dist/runtime/devtools.d.ts +3 -1
  34. package/dist/runtime/devtools.js +1 -1
  35. package/dist/runtime/hot.d.ts +1 -1
  36. package/dist/runtime/hot.js +9 -5
  37. package/dist/runtime/hot.js.map +1 -1
  38. package/dist/runtime/html.d.ts +2 -2
  39. package/dist/runtime/html.js +1 -1
  40. package/dist/runtime/loader.d.ts +12 -2
  41. package/dist/runtime/loader.js +3 -1
  42. package/dist/runtime/server.d.ts +4 -4
  43. package/dist/runtime/server.js +5 -5
  44. package/dist/runtime/signals.d.ts +2 -2
  45. package/dist/runtime/signals.js +5 -5
  46. package/dist/runtime/signals.js.map +1 -1
  47. package/dist/runtime/static-loader.d.ts +3 -0
  48. package/dist/runtime/static-loader.js +1 -0
  49. package/dist/runtime/testing.d.ts +21 -2
  50. package/dist/runtime/testing.js +83 -7
  51. package/dist/runtime/testing.js.map +1 -1
  52. package/dist/{server-sQCvduOz.d.ts → server-BxqjLUnV.d.ts} +211 -20
  53. package/dist/{server-CX3JnPCs.js → server-DZsgnPKS.js} +595 -185
  54. package/dist/server-DZsgnPKS.js.map +1 -0
  55. package/dist/shared-CWYOd0H3.js +40 -0
  56. package/dist/shared-CWYOd0H3.js.map +1 -0
  57. package/dist/static-loader-BcFh4ebX.d.ts +11 -0
  58. package/dist/static-loader-ClNkHZGn.js +185 -0
  59. package/dist/static-loader-ClNkHZGn.js.map +1 -0
  60. package/dist/stream-bgNCMcaA.js +280 -0
  61. package/dist/stream-bgNCMcaA.js.map +1 -0
  62. package/dist/vite.d.ts +30 -5
  63. package/dist/vite.js +501 -62
  64. package/dist/vite.js.map +1 -1
  65. package/package.json +7 -2
  66. package/types.d.ts +5 -0
  67. package/dist/cookies-rgIAc8IE.js.map +0 -1
  68. package/dist/devtools-Bm8cS7hX.js.map +0 -1
  69. package/dist/devtools-panel-CTbDSBBA.js.map +0 -1
  70. package/dist/html-CxWpXngy.js.map +0 -1
  71. package/dist/inspect-CGCWfaEx.js.map +0 -1
  72. package/dist/loader-BUhNqDHw.d.ts +0 -30
  73. package/dist/loader-py4qu6tQ.js +0 -215
  74. package/dist/loader-py4qu6tQ.js.map +0 -1
  75. package/dist/navigate-C5dP89YL.js.map +0 -1
  76. package/dist/rpc-B86KKjzx.js.map +0 -1
  77. package/dist/server-CX3JnPCs.js.map +0 -1
  78. package/dist/shared-BE_oBSDM.js +0 -176
  79. package/dist/shared-BE_oBSDM.js.map +0 -1
  80. package/dist/stream-cvhqOzfs.js +0 -145
  81. package/dist/stream-cvhqOzfs.js.map +0 -1
@@ -0,0 +1,101 @@
1
+ import { i as strategy, n as boot, r as importCore } from "./static-loader-ClNkHZGn.js";
2
+ //#region src/runtime/loader.ts
3
+ /**
4
+ * Starts resuming the page. Listens to the events in `b-on` attributes
5
+ * and loads `brumate/client` and the component's module on the first one.
6
+ * Returns a function that removes the listeners and stops the core.
7
+ */
8
+ function start(options) {
9
+ return boot(options, options.navigate === false ? void 0 : navigation);
10
+ }
11
+ /** Starts loading the page of a link, unless the link asks not to. */
12
+ function prefetch(link) {
13
+ if (link && strategy(link) !== "none") import("./navigate-CzLjnoPH.js").then((module) => module.prefetch(link.href));
14
+ }
15
+ /**
16
+ * Imports the code with which the core reads the pages that navigation adds.
17
+ * A core that runs loads it when the loader navigates. A core that starts
18
+ * later loads it with the core, when the page has records that navigation
19
+ * marked.
20
+ */
21
+ const routes = () => import("./client-routes-DakuM32C.js").then((module) => module.ready);
22
+ /**
23
+ * Loads pages without a full page load: links to the same origin, the back
24
+ * and forward buttons, forms that post to a server function, and redirects
25
+ * from server functions to the same origin. Returns how the loader imports
26
+ * the core.
27
+ */
28
+ function navigation({ options, listen, core, scan }) {
29
+ const rpc = `${options.rpc ?? "/_brumate"}/`;
30
+ let page = String(location.href).split("#")[0];
31
+ const go = (url, init, push = true, reload = false) => {
32
+ page = url.split("#")[0];
33
+ if (core()) routes();
34
+ import("./navigate-CzLjnoPH.js").then((module) => module.navigate({
35
+ url,
36
+ init,
37
+ push,
38
+ reload,
39
+ transition: typeof options.navigate === "object" && options.navigate.transition === true,
40
+ leave: async (partial) => {
41
+ if (core()) (await routes())(partial);
42
+ },
43
+ enter: () => {
44
+ core()?.then((client) => client.init({
45
+ ...options,
46
+ listen: scan
47
+ }));
48
+ page = location.href.split("#")[0];
49
+ }
50
+ }));
51
+ };
52
+ const pageLink = (target) => {
53
+ const link = target?.closest?.("a[href]");
54
+ return link && !link.target && !link.matches("[download],[data-reload]") && link.origin === location.origin && !(link.hash && link.href.split("#")[0] === page) ? link : void 0;
55
+ };
56
+ listen(document, "click", (event) => {
57
+ const mouse = event;
58
+ const link = pageLink(event.target);
59
+ if (!link || event.defaultPrevented || mouse.button || mouse.metaKey || mouse.ctrlKey || mouse.shiftKey || mouse.altKey) return;
60
+ event.preventDefault();
61
+ go(link.href);
62
+ });
63
+ let resting;
64
+ listen(document, "pointerover", (event) => {
65
+ const link = pageLink(event.target);
66
+ if (link) {
67
+ clearTimeout(resting);
68
+ resting = setTimeout(() => prefetch(link), 80);
69
+ }
70
+ }, { passive: true });
71
+ listen(document, "pointerout", () => clearTimeout(resting), { passive: true });
72
+ listen(document, "focusin", (event) => prefetch(pageLink(event.target)));
73
+ listen(document, "submit", (event) => {
74
+ const form = event.target;
75
+ const submitter = event.submitter;
76
+ const action = submitter?.getAttribute("formaction") ?? form.getAttribute("action") ?? "";
77
+ const method = submitter?.getAttribute("formmethod") ?? form.getAttribute("method");
78
+ if (event.defaultPrevented || method?.toLowerCase() !== "post" || !action.startsWith(rpc)) return;
79
+ event.preventDefault();
80
+ go(action, {
81
+ method: "POST",
82
+ body: new FormData(form, submitter)
83
+ });
84
+ });
85
+ listen(document, "brumate:redirect", (event) => {
86
+ const url = new URL(event.detail, location.href);
87
+ if (url.origin === location.origin) {
88
+ event.preventDefault();
89
+ go(url.href, void 0, true, true);
90
+ }
91
+ });
92
+ listen(document, "brumate:reload", () => go(location.href, { method: "GET" }, false));
93
+ listen(window, "popstate", () => {
94
+ if (location.href.split("#")[0] !== page) go(location.href, void 0, false);
95
+ });
96
+ return () => Promise.all([importCore(), document.querySelector("[b-offset],[b-roots]") && routes()]).then(([client]) => client);
97
+ }
98
+ //#endregion
99
+ export { start as t };
100
+
101
+ //# sourceMappingURL=loader-Dc9OwY5I.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loader-Dc9OwY5I.js","names":[],"sources":["../src/runtime/loader.ts"],"sourcesContent":["import type * as Routes from './client-routes.ts';\nimport { boot, importCore, strategy } from './boot.ts';\nimport type { Core, LoaderOptions, Navigation } from './boot.ts';\n\nexport type { LoaderOptions, NavigateOptions } from './boot.ts';\nexport { startWithoutNavigation } from './static-loader.ts';\n\n/**\n * Starts resuming the page. Listens to the events in `b-on` attributes\n * and loads `brumate/client` and the component's module on the first one.\n * Returns a function that removes the listeners and stops the core.\n */\nexport function start(options: LoaderOptions): () => void {\n return boot(options, options.navigate === false ? undefined : navigation);\n}\n\n/** Starts loading the page of a link, unless the link asks not to. */\nfunction prefetch(link: HTMLAnchorElement | undefined): void {\n if (link && strategy(link) !== 'none') {\n void import('./navigate.ts').then((module) => module.prefetch(link.href));\n }\n}\n\n/**\n * Imports the code with which the core reads the pages that navigation adds.\n * A core that runs loads it when the loader navigates. A core that starts\n * later loads it with the core, when the page has records that navigation\n * marked.\n */\nconst routes = (): (typeof Routes)['ready'] =>\n import('./client-routes.ts').then((module) => module.ready);\n\n/**\n * Loads pages without a full page load: links to the same origin, the back\n * and forward buttons, forms that post to a server function, and redirects\n * from server functions to the same origin. Returns how the loader imports\n * the core.\n */\nfunction navigation({ options, listen, core, scan }: Navigation): () => Promise<Core> {\n const rpc = `${options.rpc ?? '/_brumate'}/`;\n // The page without its hash, to tell a change of the hash from a change of the page.\n let page = String(location.href).split('#')[0];\n const go = (url: string, init?: RequestInit, push = true, reload = false): void => {\n page = url.split('#')[0]!;\n if (core()) {\n void routes();\n }\n void import('./navigate.ts').then((module) =>\n module.navigate({\n url,\n init,\n push,\n reload,\n transition: typeof options.navigate === 'object' && options.navigate.transition === true,\n // The core forgets the old page, or only stops reading, when layouts stay.\n leave: async (partial) => {\n if (core()) {\n (await routes())(partial);\n }\n },\n enter: () => {\n void core()?.then((client) => client.init({ ...options, listen: scan }));\n page = location.href.split('#')[0]!;\n },\n }),\n );\n };\n // A link to another page of this site, which the loader loads itself.\n const pageLink = (target: EventTarget | null): HTMLAnchorElement | undefined => {\n const link = (target as Element | null)?.closest?.('a[href]') as HTMLAnchorElement | null;\n return link &&\n !link.target &&\n !link.matches('[download],[data-reload]') &&\n link.origin === location.origin &&\n // A link to a place in the same page scrolls there.\n !(link.hash && link.href.split('#')[0] === page)\n ? link\n : undefined;\n };\n listen(document, 'click', (event) => {\n const mouse = event as MouseEvent;\n const link = pageLink(event.target);\n if (\n !link ||\n event.defaultPrevented ||\n mouse.button ||\n mouse.metaKey ||\n mouse.ctrlKey ||\n mouse.shiftKey ||\n mouse.altKey\n ) {\n return;\n }\n event.preventDefault();\n go(link.href);\n });\n // A page loads when the pointer rests on its link, or the link gets focus, so a click finds it loading.\n let resting: ReturnType<typeof setTimeout> | undefined;\n listen(\n document,\n 'pointerover',\n (event) => {\n const link = pageLink(event.target);\n if (link) {\n clearTimeout(resting);\n resting = setTimeout(() => prefetch(link), 80);\n }\n },\n { passive: true },\n );\n listen(document, 'pointerout', () => clearTimeout(resting), { passive: true });\n listen(document, 'focusin', (event) => prefetch(pageLink(event.target)));\n listen(document, 'submit', (event) => {\n const form = event.target as HTMLFormElement;\n const submitter = (event as SubmitEvent).submitter;\n const action = submitter?.getAttribute('formaction') ?? form.getAttribute('action') ?? '';\n const method = submitter?.getAttribute('formmethod') ?? form.getAttribute('method');\n if (event.defaultPrevented || method?.toLowerCase() !== 'post' || !action.startsWith(rpc)) {\n return;\n }\n event.preventDefault();\n go(action, { method: 'POST', body: new FormData(form, submitter) });\n });\n // A server function that redirects, from `rpc.ts`. Another site loads in full.\n listen(document, 'brumate:redirect', (event) => {\n const url = new URL((event as CustomEvent<string>).detail, location.href);\n if (url.origin === location.origin) {\n event.preventDefault();\n go(url.href, undefined, true, true);\n }\n });\n // A hot update whose markup changed loads the page again, in place. With `init`, the whole\n // page is replaced, as for a form, so layouts render again too, and it keeps the scroll.\n listen(document, 'brumate:reload', () => go(location.href, { method: 'GET' }, false));\n listen(window, 'popstate', () => {\n // A change of the hash only stays on the page.\n if (location.href.split('#')[0] !== page) {\n go(location.href, undefined, false);\n }\n });\n return () =>\n Promise.all([importCore(), document.querySelector('[b-offset],[b-roots]') && routes()]).then(\n ([client]) => client,\n );\n}\n"],"mappings":";;;;;;;AAYA,SAAgB,MAAM,SAAoC;CACxD,OAAO,KAAK,SAAS,QAAQ,aAAa,QAAQ,KAAA,IAAY,UAAU;AAC1E;;AAGA,SAAS,SAAS,MAA2C;CAC3D,IAAI,QAAQ,SAAS,IAAI,MAAM,QAC7B,OAAY,yBAAgB,CAAC,MAAM,WAAW,OAAO,SAAS,KAAK,IAAI,CAAC;AAE5E;;;;;;;AAQA,MAAM,eACJ,OAAO,8BAAqB,CAAC,MAAM,WAAW,OAAO,KAAK;;;;;;;AAQ5D,SAAS,WAAW,EAAE,SAAS,QAAQ,MAAM,QAAyC;CACpF,MAAM,MAAM,GAAG,QAAQ,OAAO,YAAY;CAE1C,IAAI,OAAO,OAAO,SAAS,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;CAC5C,MAAM,MAAM,KAAa,MAAoB,OAAO,MAAM,SAAS,UAAgB;EACjF,OAAO,IAAI,MAAM,GAAG,CAAC,CAAC;EACtB,IAAI,KAAK,GACP,OAAY;EAEd,OAAY,yBAAgB,CAAC,MAAM,WACjC,OAAO,SAAS;GACd;GACA;GACA;GACA;GACA,YAAY,OAAO,QAAQ,aAAa,YAAY,QAAQ,SAAS,eAAe;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,aAAa,YAAY,KAAK,KAAK,aAAa,QAAQ;EAClF,IAAI,MAAM,oBAAoB,QAAQ,YAAY,MAAM,UAAU,CAAC,OAAO,WAAW,GAAG,GACtF;EAEF,MAAM,eAAe;EACrB,GAAG,QAAQ;GAAE,QAAQ;GAAQ,MAAM,IAAI,SAAS,MAAM,SAAS;EAAE,CAAC;CACpE,CAAC;CAED,OAAO,UAAU,qBAAqB,UAAU;EAC9C,MAAM,MAAM,IAAI,IAAK,MAA8B,QAAQ,SAAS,IAAI;EACxE,IAAI,IAAI,WAAW,SAAS,QAAQ;GAClC,MAAM,eAAe;GACrB,GAAG,IAAI,MAAM,KAAA,GAAW,MAAM,IAAI;EACpC;CACF,CAAC;CAGD,OAAO,UAAU,wBAAwB,GAAG,SAAS,MAAM,EAAE,QAAQ,MAAM,GAAG,KAAK,CAAC;CACpF,OAAO,QAAQ,kBAAkB;EAE/B,IAAI,SAAS,KAAK,MAAM,GAAG,CAAC,CAAC,OAAO,MAClC,GAAG,SAAS,MAAM,KAAA,GAAW,KAAK;CAEtC,CAAC;CACD,aACE,QAAQ,IAAI,CAAC,WAAW,GAAG,SAAS,cAAc,sBAAsB,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,MACrF,CAAC,YAAY,MAChB;AACJ"}
@@ -9,21 +9,22 @@ async function transition(visit, update) {
9
9
  update();
10
10
  return;
11
11
  }
12
- const types = [visit.init ? "form" : visit.push ? "push" : "traverse"];
12
+ const types = [visit.init || visit.reload ? "form" : visit.push ? "push" : "traverse"];
13
13
  await (typeof ViewTransition !== "undefined" && "types" in ViewTransition.prototype ? document.startViewTransition({
14
14
  update,
15
15
  types
16
16
  }) : document.startViewTransition(update)).updateCallbackDone;
17
17
  }
18
18
  let controller;
19
- const STATE = "script[type=\"brumate/state\"]";
19
+ const STATE = "script[b-state]";
20
+ const REGION = /^R(-?\d+):([^:]+):(\d+):(.*)$/;
20
21
  /** Finds the route slots in a document, nested as the routes are. */
21
22
  function regions(root) {
22
23
  const top = [];
23
24
  const stack = [];
24
25
  const walker = (root.ownerDocument ?? root).createTreeWalker(root, 128);
25
26
  for (let node = walker.nextNode(); node; node = walker.nextNode()) {
26
- const match = /^R(-?\d+):([^:]+):(\d+):(.*)$/.exec(node.data);
27
+ const match = REGION.exec(node.data);
27
28
  if (match) {
28
29
  const region = {
29
30
  layout: Number(match[1]),
@@ -70,25 +71,27 @@ function between(start, end) {
70
71
  */
71
72
  function keepStyles(removed) {
72
73
  for (const style of removed) {
73
- const id = style.getAttribute("data-brm");
74
+ const id = style.getAttribute("b-style");
74
75
  const attribute = `s-${id.slice(id.lastIndexOf("_") + 1)}`;
75
- if (!document.querySelector(`style[data-brm="${CSS.escape(id)}"]`) && document.querySelector(`[${attribute}]`)) document.head.append(style);
76
+ if (!document.querySelector(`style[b-style="${CSS.escape(id)}"]`) && document.querySelector(`[${attribute}]`)) document.head.append(style);
76
77
  }
77
78
  }
78
- /** True when a slot's end comment is a sibling of its start comment. */
79
+ /**
80
+ * True when a slot's end comment is a sibling of its start comment. The end
81
+ * comes after the start in the document, so it then follows it.
82
+ */
79
83
  function complete(region) {
80
- return between(region.start, region.end).at(-1) === region.end;
84
+ return region.start.parentNode === region.end.parentNode;
81
85
  }
82
86
  /**
83
87
  * Plans to replace only the routes that change, when the new page has the
84
88
  * same root route as the current one. Returns undefined when it cannot.
85
89
  */
86
- function planRoutes(next, requested) {
87
- const scripts = document.querySelectorAll(`${STATE}[data-route]`);
88
- const route = scripts[scripts.length - 1]?.getAttribute("data-route");
89
- const state = next.body.querySelector(`${STATE}[data-route]`);
90
- if (!route || state?.getAttribute("data-route") !== route) return;
91
- if (state.getAttribute("data-root") !== String(requested)) return;
90
+ function planRoutes(next, state, requested) {
91
+ const scripts = document.querySelectorAll(`${STATE}[b-route]`);
92
+ const route = scripts[scripts.length - 1]?.getAttribute("b-route");
93
+ if (!route || state?.getAttribute("b-route") !== route) return;
94
+ if (state.getAttribute("b-root") !== String(requested)) return;
92
95
  const result = plan(regions(document.body), regions(next.body), {
93
96
  replace: [],
94
97
  alias: /* @__PURE__ */ new Map()
@@ -97,45 +100,52 @@ function planRoutes(next, requested) {
97
100
  return result;
98
101
  }
99
102
  /** Replaces the routes that change, and keeps the rest of the page. */
100
- function replaceRoutes(next, result) {
101
- const state = next.body.querySelector(`${STATE}[data-route]`);
103
+ function replaceRoutes(next, state, result) {
102
104
  const removed = [];
103
105
  for (const [before, region] of result.replace) {
104
106
  const nodes = between(before.start, before.end);
105
107
  for (const node of nodes) if (node.nodeType === 1) {
106
108
  const element = node;
107
- removed.push(...element.matches("style[data-brm]") ? [element] : [], ...element.querySelectorAll("style[data-brm]"));
109
+ if (element.matches("style[b-style]")) removed.push(element);
110
+ removed.push(...element.querySelectorAll("style[b-style]"));
108
111
  }
109
112
  const parent = before.start.parentNode;
110
113
  for (const node of between(region.start, region.end)) parent.insertBefore(document.adoptNode(node), before.start);
111
114
  for (const node of nodes) node.parentNode?.removeChild(node);
112
115
  }
113
116
  keepStyles(removed);
114
- state.setAttribute("data-drop", result.replace.map(([before]) => before.root).join(","));
115
- state.setAttribute("data-roots", result.replace.map(([, region]) => region.root).join(","));
116
- state.setAttribute("data-alias", [...result.alias].map(([from, to]) => `${from}:${to}`).join(","));
117
- for (const script of next.body.querySelectorAll(STATE)) document.body.append(document.adoptNode(script));
117
+ state.setAttribute("b-drop", result.replace.map(([before]) => before.root).join(","));
118
+ state.setAttribute("b-roots", result.replace.map(([, region]) => region.root).join(","));
119
+ state.setAttribute("b-alias", [...result.alias].map(([from, to]) => `${from}:${to}`).join(","));
120
+ for (const script of next.body.querySelectorAll(STATE)) document.body.append(runnable(script));
118
121
  }
119
122
  /**
120
123
  * A page whose IDs do not start where this page asked, such as a prerendered
121
124
  * file on a static host, has its IDs moved before it is read. Returns
122
125
  * undefined when the server started them there.
123
126
  */
124
- function shiftFor(next, requested) {
125
- const state = next.body.querySelector(`${STATE}[data-route]`);
127
+ function shiftFor(state, requested) {
126
128
  if (!state) return;
127
- const root = Number(state.getAttribute("data-root") ?? 0);
129
+ const root = Number(state.getAttribute("b-root") ?? 0);
128
130
  return root === requested ? void 0 : {
129
131
  by: requested - root,
130
132
  root: String(requested)
131
133
  };
132
134
  }
133
135
  const COMMENT_IDS = /^([tb])(\d+)(:.*)$|^([ilP])(\d+)$/;
134
- const REGION = /^R(-?\d+):([^:]+):(\d+):(.*)$/;
136
+ /** Attributes that hold a scope ID, then `:` and more. */
137
+ const SCOPED = ["b-b", "b-result"];
138
+ /** Attributes that hold only a scope or boundary ID. */
139
+ const IDS = [
140
+ "b-v",
141
+ "b-l",
142
+ "b-h",
143
+ "b-next"
144
+ ];
135
145
  /**
136
146
  * Adds a number to every scope and boundary ID in markup that the server
137
147
  * rendered: anchors, markers, swap scripts and state records. The core moves
138
- * the IDs inside a state record when it reads one with `data-offset`.
148
+ * the IDs inside a state record when it reads one with `b-offset`.
139
149
  */
140
150
  function shiftIds(root, shift) {
141
151
  const add = (value) => String(Number(value) + shift.by);
@@ -153,25 +163,20 @@ function shiftIds(root, shift) {
153
163
  }
154
164
  if (node.nodeType !== 1) return;
155
165
  const element = node;
156
- for (const name of ["data-b", "data-result"]) {
166
+ for (const name of SCOPED) {
157
167
  const value = element.getAttribute(name);
158
168
  if (value) {
159
169
  const [scope, rest] = value.split(":");
160
170
  element.setAttribute(name, `${add(scope)}:${rest}`);
161
171
  }
162
172
  }
163
- for (const name of [
164
- "data-v",
165
- "data-l",
166
- "data-h",
167
- "data-next"
168
- ]) {
173
+ for (const name of IDS) {
169
174
  const value = element.getAttribute(name);
170
175
  if (value) element.setAttribute(name, add(value));
171
176
  }
172
- if (element.matches(STATE)) {
173
- element.setAttribute("data-offset", String(shift.by));
174
- element.setAttribute("data-root", shift.root);
177
+ if (element.localName === "script" && element.matches(STATE)) {
178
+ element.setAttribute("b-offset", String(shift.by));
179
+ element.setAttribute("b-root", shift.root);
175
180
  } else if (element.tagName === "SCRIPT" && !element.hasAttribute("type")) element.textContent = element.textContent.replace(/\$b([SH])\((\d+)/g, (_, kind, id) => `$b${kind}(${add(id)}`);
176
181
  for (const child of element.tagName === "TEMPLATE" ? element.content.childNodes : element.childNodes) visit(child);
177
182
  };
@@ -180,7 +185,7 @@ function shiftIds(root, shift) {
180
185
  /** A number above every scope and boundary ID in the page, for the server to start the next page at. */
181
186
  function base() {
182
187
  let value = 0;
183
- for (const script of document.querySelectorAll(`${STATE}[data-next]`)) value = Math.max(value, Number(script.getAttribute("data-next")));
188
+ for (const script of document.querySelectorAll(`${STATE}[b-next]`)) value = Math.max(value, Number(script.getAttribute("b-next")));
184
189
  return value;
185
190
  }
186
191
  /**
@@ -217,7 +222,11 @@ function append(nodes, shift) {
217
222
  for (const node of nodes) {
218
223
  if (shift) shiftIds(node, shift);
219
224
  const adopted = document.adoptNode(node);
220
- const scripts = adopted.nodeType === 1 ? [...adopted.matches("script") ? [adopted] : [], ...adopted.querySelectorAll("script")] : [];
225
+ const scripts = [];
226
+ if (adopted.nodeType === 1) {
227
+ if (adopted.matches("script")) scripts.push(adopted);
228
+ scripts.push(...adopted.querySelectorAll("script"));
229
+ }
221
230
  document.body.append(adopted);
222
231
  for (const script of scripts) if (!script.src && (!script.type || script.type === "text/javascript" || script.type === "module")) script.replaceWith(runnable(script));
223
232
  }
@@ -258,22 +267,38 @@ function prefetch(url) {
258
267
  const key = url.split("#")[0];
259
268
  const entry = prefetched.get(key);
260
269
  if (entry && performance.now() - entry.at < FRESH) return;
270
+ entry?.controller.abort();
261
271
  const requested = base();
262
- const response = fetch(key, { headers: { "x-brumate-base": String(requested) } });
263
- response.catch(() => prefetched.delete(key));
264
- prefetched.set(key, {
272
+ const loading = new AbortController();
273
+ const response = fetch(key, {
274
+ headers: { "x-brumate-base": String(requested) },
275
+ signal: loading.signal
276
+ });
277
+ const next = {
265
278
  at: performance.now(),
266
279
  base: requested,
267
- response
280
+ response,
281
+ controller: loading
282
+ };
283
+ response.catch(() => {
284
+ if (prefetched.get(key) === next) prefetched.delete(key);
268
285
  });
286
+ prefetched.set(key, next);
287
+ }
288
+ /** Stops the pages that loaded early and were not used, so they free their connections. */
289
+ function clearPrefetched() {
290
+ for (const entry of prefetched.values()) entry.controller.abort();
291
+ prefetched.clear();
269
292
  }
270
293
  /** The response of a page that loaded early for these IDs, if it is still fresh. */
271
294
  function takePrefetched(url, requested) {
272
295
  const key = url.split("#")[0];
273
296
  const entry = prefetched.get(key);
274
297
  prefetched.delete(key);
275
- return entry && entry.base === requested && performance.now() - entry.at < FRESH ? entry.response : void 0;
298
+ if (entry && entry.base === requested && performance.now() - entry.at < FRESH) return entry.response;
299
+ entry?.controller.abort();
276
300
  }
301
+ const HTML_END = /<\/html\s*>/gi;
277
302
  async function navigate(visit) {
278
303
  pageNonce();
279
304
  controller?.abort();
@@ -286,7 +311,7 @@ async function navigate(visit) {
286
311
  }, "");
287
312
  let response;
288
313
  try {
289
- const early = visit.init ? void 0 : takePrefetched(visit.url, requested);
314
+ const early = visit.init || visit.reload ? void 0 : takePrefetched(visit.url, requested);
290
315
  const headers = new Headers(visit.init?.headers);
291
316
  headers.set("x-brumate-base", String(requested));
292
317
  response = await (early ?? fetch(visit.url, {
@@ -294,11 +319,16 @@ async function navigate(visit) {
294
319
  headers,
295
320
  signal: current.signal
296
321
  }));
297
- prefetched.clear();
322
+ clearPrefetched();
298
323
  } catch (error) {
299
- if (!current.signal.aborted) location.assign(visit.url);
324
+ if (current.signal.aborted) return;
325
+ location.assign(visit.url);
300
326
  throw error;
301
327
  }
328
+ if (current.signal.aborted) {
329
+ response.body?.cancel().catch(() => {});
330
+ return;
331
+ }
302
332
  if (!(response.headers.get("content-type") ?? "").includes("text/html") || !response.body) {
303
333
  if (!visit.init) {
304
334
  location.assign(visit.url);
@@ -310,25 +340,42 @@ async function navigate(visit) {
310
340
  const url = new URL(response.url || visit.url, location.href);
311
341
  url.hash = new URL(visit.url, location.href).hash;
312
342
  const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
343
+ const stop = () => {
344
+ reader.cancel().catch(() => {});
345
+ };
346
+ const read = async () => {
347
+ try {
348
+ const chunk = await reader.read();
349
+ if (!current.signal.aborted) return chunk;
350
+ } catch (error) {
351
+ if (!current.signal.aborted) throw error;
352
+ }
353
+ stop();
354
+ };
313
355
  let text = "";
314
356
  let end = -1;
315
357
  while (end === -1) {
316
- const chunk = await reader.read();
317
- if (current.signal.aborted) return;
358
+ const chunk = await read();
359
+ if (!chunk) return;
318
360
  if (chunk.done) {
319
361
  end = text.length;
320
362
  break;
321
363
  }
364
+ HTML_END.lastIndex = Math.max(0, text.lastIndexOf("<"));
322
365
  text += chunk.value;
323
- const index = text.search(/<\/html\s*>/i);
324
- if (index !== -1) end = index + text.slice(index).indexOf(">") + 1;
366
+ const match = HTML_END.exec(text);
367
+ if (match) end = match.index + match[0].length;
325
368
  }
326
369
  const next = new DOMParser().parseFromString(text.slice(0, end), "text/html");
327
- const shift = visit.init ? void 0 : shiftFor(next, requested);
370
+ const state = next.body.querySelector(`${STATE}[b-route]`);
371
+ const shift = visit.init ? void 0 : shiftFor(state, requested);
328
372
  if (shift) shiftIds(next.body, shift);
329
- const routes = visit.init ? void 0 : planRoutes(next, requested);
373
+ const routes = visit.init || visit.reload ? void 0 : planRoutes(next, state, requested);
330
374
  await visit.leave(routes !== void 0);
331
- if (current.signal.aborted) return;
375
+ if (current.signal.aborted) {
376
+ stop();
377
+ return;
378
+ }
332
379
  await transition(visit, () => {
333
380
  for (const attribute of [...document.documentElement.attributes]) document.documentElement.removeAttribute(attribute.name);
334
381
  for (const attribute of next.documentElement.attributes) document.documentElement.setAttribute(attribute.name, attribute.value);
@@ -337,15 +384,21 @@ async function navigate(visit) {
337
384
  document.title = title;
338
385
  const same = url.href === location.href;
339
386
  const top = window.scrollY;
340
- if (routes) replaceRoutes(next, routes);
341
- else document.body.replaceWith(document.adoptNode(next.body));
387
+ if (routes) replaceRoutes(next, state, routes);
388
+ else {
389
+ document.body.replaceWith(document.adoptNode(next.body));
390
+ for (const script of document.body.querySelectorAll(STATE)) script.replaceWith(runnable(script));
391
+ }
342
392
  if (visit.push && !same) history.pushState({}, "", url);
343
393
  else if (!same) history.replaceState(history.state, "", url);
344
394
  visit.enter();
345
- if (visit.init && same) window.scrollTo(0, top);
395
+ if ((visit.init || visit.reload) && same) window.scrollTo(0, top);
346
396
  else scroll(url, visit.push ? void 0 : history.state?.scroll);
347
397
  });
348
- if (current.signal.aborted) return;
398
+ if (current.signal.aborted) {
399
+ stop();
400
+ return;
401
+ }
349
402
  const sink = document.implementation.createHTMLDocument("");
350
403
  sink.open();
351
404
  sink.write("<!doctype html><body>");
@@ -355,8 +408,8 @@ async function navigate(visit) {
355
408
  sink.write(rest);
356
409
  append([...sink.body.childNodes].slice(0, -1), shift);
357
410
  }
358
- const chunk = await reader.read();
359
- if (current.signal.aborted) return;
411
+ const chunk = await read();
412
+ if (!chunk) return;
360
413
  if (chunk.done) break;
361
414
  rest = chunk.value;
362
415
  }
@@ -366,4 +419,4 @@ async function navigate(visit) {
366
419
  //#endregion
367
420
  export { navigate, prefetch };
368
421
 
369
- //# sourceMappingURL=navigate-C5dP89YL.js.map
422
+ //# sourceMappingURL=navigate-CzLjnoPH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"navigate-CzLjnoPH.js","names":[],"sources":["../src/runtime/navigate.ts"],"sourcesContent":["// Client navigation. The loader imports it on the first navigation, so pages\n// that never navigate do not load it.\n\nexport interface Visit {\n url: string;\n /** For a form that posts to a server function. */\n init?: RequestInit;\n /** False for the back and forward buttons, which already changed the history. */\n push: boolean;\n /**\n * Runs before the new page replaces the old one. `partial` is true when\n * the page keeps its layouts and replaces only some routes.\n */\n leave: (partial: boolean) => Promise<void>;\n /** Runs after the first render of the new page is in the document. */\n enter: () => void;\n /** Swaps the page inside a view transition, where the browser has them. */\n transition?: boolean;\n /**\n * Loads the page after a server function changed something, as for a\n * redirect from one. As a form does, it replaces the whole page, and does\n * not use a page that a link loaded early.\n */\n reload?: boolean;\n}\n\n/**\n * Runs `update` inside a view transition, with a type that tells how the page\n * was reached: `push` for a link, `traverse` for the back and forward\n * buttons, and `form` for a form. Without transitions, it runs `update`.\n */\nasync function transition(visit: Visit, update: () => void): Promise<void> {\n if (!visit.transition || typeof document.startViewTransition !== 'function') {\n update();\n return;\n }\n const types = [visit.init || visit.reload ? 'form' : visit.push ? 'push' : 'traverse'];\n // Browsers that have transitions without types take only a callback.\n const started =\n typeof ViewTransition !== 'undefined' && 'types' in ViewTransition.prototype\n ? document.startViewTransition({ update, types })\n : document.startViewTransition(update);\n await started.updateCallbackDone;\n}\n\nlet controller: AbortController | undefined;\n\nconst STATE = 'script[b-state]';\nconst REGION = /^R(-?\\d+):([^:]+):(\\d+):(.*)$/;\n\n/** A route slot in the page, between `<!--R…-->` and `<!--/R-->`. */\ninterface Region {\n /** The scope of the layout that renders the slot. */\n layout: number;\n name: string;\n /** The scope of the route in the slot. */\n root: number;\n key: string;\n start: Comment;\n end: Comment;\n children: Region[];\n}\n\n/** Finds the route slots in a document, nested as the routes are. */\nfunction regions(root: Node): Region[] {\n const top: Region[] = [];\n const stack: Region[] = [];\n const walker = (root.ownerDocument ?? (root as Document)).createTreeWalker(root, 128);\n for (\n let node = walker.nextNode() as Comment | null;\n node;\n node = walker.nextNode() as Comment | null\n ) {\n const match = REGION.exec(node.data);\n if (match) {\n const region: Region = {\n layout: Number(match[1]),\n name: match[2]!,\n root: Number(match[3]),\n key: decodeURIComponent(match[4]!),\n start: node,\n end: node,\n children: [],\n };\n (stack.at(-1)?.children ?? top).push(region);\n stack.push(region);\n } else if (node.data === '/R' && stack.length > 0) {\n stack.pop()!.end = node;\n }\n }\n return top;\n}\n\ninterface Plan {\n /** Old slots and the new slots that replace them. */\n replace: [Region, Region][];\n alias: Map<number, number>;\n}\n\n/**\n * Pairs the slots of the old and the new page by name. A layout with the\n * same key stays, and its slots are compared in turn. Any other route is\n * replaced. Returns undefined when the pages do not line up.\n */\nfunction plan(old: Region[], next: Region[], result: Plan): Plan | undefined {\n for (const region of next) {\n const before = old.find((item) => item.name === region.name);\n if (!before) {\n return undefined;\n }\n result.alias.set(region.layout, before.layout);\n if (before.key === region.key && region.children.length > 0) {\n // The layout stays, so its new scope stands for the old one.\n result.alias.set(region.root, before.root);\n if (!plan(before.children, region.children, result)) {\n return undefined;\n }\n } else {\n result.replace.push([before, region]);\n }\n }\n return result;\n}\n\nfunction between(start: Node, end: Node): Node[] {\n const nodes = [start];\n for (let node = start.nextSibling; node && nodes.at(-1) !== end; node = node.nextSibling) {\n nodes.push(node);\n }\n return nodes;\n}\n\n/**\n * The server writes a component's stylesheet before its first instance, so\n * an old route can hold the stylesheet of a component that a kept layout\n * still shows. Such a stylesheet moves to the head. The others go with the\n * route, so the page keeps only the CSS of the components that it shows.\n */\nfunction keepStyles(removed: HTMLStyleElement[]): void {\n for (const style of removed) {\n const id = style.getAttribute('b-style')!;\n // The component ID ends with the hash that scopes its elements, as `s-<hash>`.\n const attribute = `s-${id.slice(id.lastIndexOf('_') + 1)}`;\n const present = document.querySelector(`style[b-style=\"${CSS.escape(id)}\"]`);\n if (!present && document.querySelector(`[${attribute}]`)) {\n document.head.append(style);\n }\n }\n}\n\n/**\n * True when a slot's end comment is a sibling of its start comment. The end\n * comes after the start in the document, so it then follows it.\n */\nfunction complete(region: Region): boolean {\n return region.start.parentNode === region.end.parentNode;\n}\n\n/**\n * Plans to replace only the routes that change, when the new page has the\n * same root route as the current one. Returns undefined when it cannot.\n */\nfunction planRoutes(next: Document, state: Element | null, requested: number): Plan | undefined {\n const scripts = document.querySelectorAll(`${STATE}[b-route]`);\n const route = scripts[scripts.length - 1]?.getAttribute('b-route');\n if (!route || state?.getAttribute('b-route') !== route) {\n return undefined;\n }\n // A page that did not start its IDs above this one, such as a static file that\n // ignores the request header, would mix its IDs with the kept layouts.\n if (state.getAttribute('b-root') !== String(requested)) {\n return undefined;\n }\n const result = plan(regions(document.body), regions(next.body), {\n replace: [],\n alias: new Map(),\n });\n if (\n !result ||\n result.replace.length === 0 ||\n !result.replace.every(([before, region]) => complete(before) && complete(region))\n ) {\n return undefined;\n }\n return result;\n}\n\n/** Replaces the routes that change, and keeps the rest of the page. */\nfunction replaceRoutes(next: Document, state: Element, result: Plan): void {\n const removed: HTMLStyleElement[] = [];\n for (const [before, region] of result.replace) {\n const nodes = between(before.start, before.end);\n for (const node of nodes) {\n if (node.nodeType === 1) {\n const element = node as Element;\n if (element.matches('style[b-style]')) {\n removed.push(element as HTMLStyleElement);\n }\n removed.push(...element.querySelectorAll<HTMLStyleElement>('style[b-style]'));\n }\n }\n const parent = before.start.parentNode!;\n for (const node of between(region.start, region.end)) {\n parent.insertBefore(document.adoptNode(node), before.start);\n }\n for (const node of nodes) {\n node.parentNode?.removeChild(node);\n }\n }\n keepStyles(removed);\n // The core drops the scopes of the old routes, and adds only the scopes of the new ones.\n state.setAttribute('b-drop', result.replace.map(([before]) => before.root).join(','));\n state.setAttribute('b-roots', result.replace.map(([, region]) => region.root).join(','));\n state.setAttribute('b-alias', [...result.alias].map(([from, to]) => `${from}:${to}`).join(','));\n // The records run as they are added, after the IDs and these attributes are set.\n for (const script of next.body.querySelectorAll<HTMLScriptElement>(STATE)) {\n document.body.append(runnable(script));\n }\n}\n\n/** Moves the IDs of a page above the IDs of the page in the browser. */\ninterface Shift {\n /** The number to add to each scope and boundary ID. */\n by: number;\n /** The `b-root` of its state records, which keeps their references apart. */\n root: string;\n}\n\n/**\n * A page whose IDs do not start where this page asked, such as a prerendered\n * file on a static host, has its IDs moved before it is read. Returns\n * undefined when the server started them there.\n */\nfunction shiftFor(state: Element | null, requested: number): Shift | undefined {\n if (!state) {\n return undefined;\n }\n const root = Number(state.getAttribute('b-root') ?? 0);\n return root === requested ? undefined : { by: requested - root, root: String(requested) };\n}\n\nconst COMMENT_IDS = /^([tb])(\\d+)(:.*)$|^([ilP])(\\d+)$/;\n/** Attributes that hold a scope ID, then `:` and more. */\nconst SCOPED = ['b-b', 'b-result'];\n/** Attributes that hold only a scope or boundary ID. */\nconst IDS = ['b-v', 'b-l', 'b-h', 'b-next'];\n\n/**\n * Adds a number to every scope and boundary ID in markup that the server\n * rendered: anchors, markers, swap scripts and state records. The core moves\n * the IDs inside a state record when it reads one with `b-offset`.\n */\nfunction shiftIds(root: Node, shift: Shift): void {\n const add = (value: string): string => String(Number(value) + shift.by);\n const visit = (node: Node): void => {\n if (node.nodeType === 8) {\n const comment = node as Comment;\n const region = REGION.exec(comment.data);\n if (region) {\n const layout = Number(region[1]) < 0 ? region[1]! : add(region[1]!);\n comment.data = `R${layout}:${region[2]}:${add(region[3]!)}:${region[4]}`;\n return;\n }\n const match = COMMENT_IDS.exec(comment.data);\n if (match) {\n comment.data = match[1]\n ? `${match[1]}${add(match[2]!)}${match[3]}`\n : `${match[4]}${add(match[5]!)}`;\n }\n return;\n }\n if (node.nodeType !== 1) {\n return;\n }\n const element = node as Element;\n for (const name of SCOPED) {\n const value = element.getAttribute(name);\n if (value) {\n const [scope, rest] = value.split(':') as [string, string];\n element.setAttribute(name, `${add(scope)}:${rest}`);\n }\n }\n for (const name of IDS) {\n const value = element.getAttribute(name);\n if (value) {\n element.setAttribute(name, add(value));\n }\n }\n // Only a script can match the state selector, so other elements skip it. The text of a\n // record is not changed: the core moves the IDs in its value when it reads it.\n if (element.localName === 'script' && element.matches(STATE)) {\n element.setAttribute('b-offset', String(shift.by));\n element.setAttribute('b-root', shift.root);\n } else if (element.tagName === 'SCRIPT' && !element.hasAttribute('type')) {\n // The scripts that swap in `#loading` bodies and their head name the boundary.\n element.textContent = element.textContent!.replace(\n /\\$b([SH])\\((\\d+)/g,\n (_, kind: string, id: string) => `$b${kind}(${add(id)}`,\n );\n }\n for (const child of element.tagName === 'TEMPLATE'\n ? (element as HTMLTemplateElement).content.childNodes\n : element.childNodes) {\n visit(child);\n }\n };\n visit(root);\n}\n\n/** A number above every scope and boundary ID in the page, for the server to start the next page at. */\nfunction base(): number {\n let value = 0;\n for (const script of document.querySelectorAll(`${STATE}[b-next]`)) {\n value = Math.max(value, Number(script.getAttribute('b-next')));\n }\n return value;\n}\n\n/**\n * The Content Security Policy nonce of the page that the browser loaded.\n * Its policy stays for the whole visit, so scripts of later pages need it,\n * not the nonce of their own response. Read once, while a script holds it.\n */\nlet loadedNonce: string | undefined;\n\n/** The nonce of a script. Browsers hide the attribute once the page loads, and keep the property. */\nfunction nonceOf(script: HTMLScriptElement): string | null {\n return script.nonce || script.getAttribute('nonce');\n}\n\nfunction pageNonce(): string | undefined {\n for (const script of loadedNonce ? [] : document.querySelectorAll('script')) {\n loadedNonce = nonceOf(script) || undefined;\n if (loadedNonce) {\n break;\n }\n }\n return loadedNonce;\n}\n\n/** Copies a script, so the browser runs it. Scripts from a parser that has no window do not run. */\nfunction runnable(script: HTMLScriptElement): HTMLScriptElement {\n const copy = document.createElement('script');\n for (const attribute of script.attributes) {\n if (attribute.name !== 'nonce') {\n copy.setAttribute(attribute.name, attribute.value);\n }\n }\n // A script that its server gave a nonce runs under the policy of the loaded page.\n const nonce = nonceOf(script);\n if (nonce) {\n copy.nonce = pageNonce() ?? nonce;\n // A DOM without the property, such as in tests, reads the attribute.\n copy.setAttribute('nonce', copy.nonce);\n }\n copy.textContent = script.textContent;\n return copy;\n}\n\n/** Moves nodes into the body. Inline scripts, such as the ones that swap in `#loading` bodies, run. */\nfunction append(nodes: Node[], shift: Shift | undefined): void {\n for (const node of nodes) {\n if (shift) {\n shiftIds(node, shift);\n }\n const adopted = document.adoptNode(node);\n const scripts: HTMLScriptElement[] = [];\n if (adopted.nodeType === 1) {\n if ((adopted as Element).matches('script')) {\n scripts.push(adopted as HTMLScriptElement);\n }\n scripts.push(...(adopted as Element).querySelectorAll('script'));\n }\n document.body.append(adopted);\n for (const script of scripts) {\n if (\n !script.src &&\n (!script.type || script.type === 'text/javascript' || script.type === 'module')\n ) {\n script.replaceWith(runnable(script));\n }\n }\n }\n}\n\n/** Makes the head of the page match the new one, keeping elements that are in both. */\nfunction updateHead(next: Document): void {\n const keep = new Map<string, Element>();\n for (const element of document.head.children) {\n keep.set(element.outerHTML, element);\n }\n // A copy, because adopting an element removes it from the live list.\n // oxlint-disable-next-line unicorn/no-useless-spread\n for (const element of [...next.head.children]) {\n const html = element.outerHTML;\n if (keep.has(html)) {\n keep.delete(html);\n } else {\n document.head.append(document.adoptNode(element));\n }\n }\n for (const element of keep.values()) {\n // Module scripts stay, because removing them does not unload them.\n if (!(element.tagName === 'SCRIPT' && (element as HTMLScriptElement).src)) {\n element.remove();\n }\n }\n}\n\nfunction scroll(url: URL, saved: number | undefined): void {\n if (saved !== undefined) {\n window.scrollTo(0, saved);\n return;\n }\n const target = url.hash && document.getElementById(decodeURIComponent(url.hash.slice(1)));\n if (target) {\n target.scrollIntoView();\n } else {\n window.scrollTo(0, 0);\n }\n}\n\n/**\n * Loads a page and replaces the current one with it. The first render of the\n * page replaces the document as soon as it arrives. Markup that the server\n * streams after it, such as `#loading` bodies, follows as it arrives.\n */\n// Pages that a link started to load before its click, by URL without the hash.\nconst prefetched = new Map<\n string,\n { at: number; base: number; response: Promise<Response>; controller: AbortController }\n>();\n\n/** How long a page that loaded early is used, in milliseconds. */\nconst FRESH = 10_000;\n\n/**\n * Starts loading a page before its link is clicked. A click within a few\n * seconds uses the response, so the page arrives sooner.\n */\nexport function prefetch(url: string): void {\n const key = url.split('#')[0]!;\n const entry = prefetched.get(key);\n if (entry && performance.now() - entry.at < FRESH) {\n return;\n }\n entry?.controller.abort();\n const requested = base();\n const loading = new AbortController();\n const response = fetch(key, {\n headers: { 'x-brumate-base': String(requested) },\n signal: loading.signal,\n });\n const next = { at: performance.now(), base: requested, response, controller: loading };\n // A failed load is not used. The click loads the page again.\n response.catch(() => {\n if (prefetched.get(key) === next) {\n prefetched.delete(key);\n }\n });\n prefetched.set(key, next);\n}\n\n/** Stops the pages that loaded early and were not used, so they free their connections. */\nfunction clearPrefetched(): void {\n for (const entry of prefetched.values()) {\n entry.controller.abort();\n }\n prefetched.clear();\n}\n\n/** The response of a page that loaded early for these IDs, if it is still fresh. */\nfunction takePrefetched(url: string, requested: number): Promise<Response> | undefined {\n const key = url.split('#')[0]!;\n const entry = prefetched.get(key);\n prefetched.delete(key);\n if (entry && entry.base === requested && performance.now() - entry.at < FRESH) {\n return entry.response;\n }\n entry?.controller.abort();\n return undefined;\n}\n\n// The end of the first render, which can be split across chunks.\nconst HTML_END = /<\\/html\\s*>/gi;\n\nexport async function navigate(visit: Visit): Promise<void> {\n // Read before the page changes, while the scripts of the loaded page are in it.\n pageNonce();\n controller?.abort();\n const requested = base();\n const current = new AbortController();\n controller = current;\n // The scroll position of the page that is left, for the back button.\n history.replaceState({ ...history.state, scroll: window.scrollY }, '');\n let response: Response;\n try {\n const early = visit.init || visit.reload ? undefined : takePrefetched(visit.url, requested);\n const headers = new Headers(visit.init?.headers);\n headers.set('x-brumate-base', String(requested));\n response = await (early ??\n fetch(visit.url, { ...visit.init, headers, signal: current.signal }));\n // Other pages loaded for this page, whose IDs no longer fit the next one.\n clearPrefetched();\n } catch (error) {\n // A later navigation stopped this one.\n if (current.signal.aborted) {\n return;\n }\n location.assign(visit.url);\n throw error;\n }\n if (current.signal.aborted) {\n // A page that loaded early is not tied to the signal, so its body is cancelled here.\n response.body?.cancel().catch(() => {});\n return;\n }\n const type = response.headers.get('content-type') ?? '';\n if (!type.includes('text/html') || !response.body) {\n if (!visit.init) {\n // Not a page, such as a file. The browser opens it.\n location.assign(visit.url);\n return;\n }\n // The error of a form post, which a browser without scripts shows as text.\n const text = await response.text();\n response = new Response(\n `<!doctype html><pre>${text.replace(/[&<]/g, (char) => (char === '&' ? '&amp;' : '&lt;'))}</pre>`,\n );\n }\n const url = new URL(response.url || visit.url, location.href);\n url.hash = new URL(visit.url, location.href).hash;\n const reader = response.body!.pipeThrough(new TextDecoderStream()).getReader();\n // Frees the connection of a page that a later navigation replaced.\n const stop = (): void => {\n reader.cancel().catch(() => {});\n };\n // The next chunk, or nothing once a later navigation started.\n const read = async (): Promise<ReadableStreamReadResult<string> | undefined> => {\n try {\n const chunk = await reader.read();\n if (!current.signal.aborted) {\n return chunk;\n }\n } catch (error) {\n if (!current.signal.aborted) {\n throw error;\n }\n }\n stop();\n return undefined;\n };\n\n // The first render ends with </html>. What comes after it streams in later.\n let text = '';\n let end = -1;\n while (end === -1) {\n // oxlint-disable-next-line no-await-in-loop -- Chunks arrive in order.\n const chunk = await read();\n if (!chunk) {\n return;\n }\n if (chunk.done) {\n end = text.length;\n break;\n }\n // A tag split across chunks starts at the last `<` of the text so far.\n HTML_END.lastIndex = Math.max(0, text.lastIndexOf('<'));\n text += chunk.value;\n const match = HTML_END.exec(text);\n if (match) {\n end = match.index + match[0].length;\n }\n }\n const next = new DOMParser().parseFromString(text.slice(0, end), 'text/html');\n const state = next.body.querySelector(`${STATE}[b-route]`);\n const shift = visit.init ? undefined : shiftFor(state, requested);\n if (shift) {\n shiftIds(next.body, shift);\n }\n // A link keeps the layouts that stay the same. A form, or a redirect from a server\n // function, replaces the whole page, because what it changed can show anywhere on it.\n const routes = visit.init || visit.reload ? undefined : planRoutes(next, state, requested);\n await visit.leave(routes !== undefined);\n if (current.signal.aborted) {\n stop();\n return;\n }\n await transition(visit, () => {\n // A copy, because removing an attribute changes the live list.\n // oxlint-disable-next-line unicorn/no-useless-spread\n for (const attribute of [...document.documentElement.attributes]) {\n document.documentElement.removeAttribute(attribute.name);\n }\n for (const attribute of next.documentElement.attributes) {\n document.documentElement.setAttribute(attribute.name, attribute.value);\n }\n // Read before the head moves, because moving the <title> clears it in `next`.\n const title = next.title;\n updateHead(next);\n document.title = title;\n const same = url.href === location.href;\n const top = window.scrollY;\n if (routes) {\n replaceRoutes(next, state!, routes);\n } else {\n document.body.replaceWith(document.adoptNode(next.body));\n // The state records of the page run in order, so the core reads them when it starts again.\n for (const script of document.body.querySelectorAll<HTMLScriptElement>(STATE)) {\n script.replaceWith(runnable(script));\n }\n }\n // A link to the page itself, or a form that comes back to it, does not add to the history.\n if (visit.push && !same) {\n history.pushState({}, '', url);\n } else if (!same) {\n history.replaceState(history.state, '', url);\n }\n visit.enter();\n if ((visit.init || visit.reload) && same) {\n // A form that comes back to its page keeps the place on the page.\n window.scrollTo(0, top);\n } else {\n scroll(url, visit.push ? undefined : (history.state?.scroll as number | undefined));\n }\n });\n if (current.signal.aborted) {\n stop();\n return;\n }\n\n // Later markup is parsed in a document without a window, so it can arrive\n // in any pieces. A node is complete once the parser has moved past it.\n const sink = document.implementation.createHTMLDocument('');\n sink.open();\n sink.write('<!doctype html><body>');\n let rest = text.slice(end);\n for (;;) {\n if (rest) {\n sink.write(rest);\n append([...sink.body.childNodes].slice(0, -1), shift);\n }\n // oxlint-disable-next-line no-await-in-loop -- Chunks arrive in order.\n const chunk = await read();\n if (!chunk) {\n return;\n }\n if (chunk.done) {\n break;\n }\n rest = chunk.value;\n }\n sink.close();\n append([...sink.body.childNodes], shift);\n}\n"],"mappings":";;;;;;AA+BA,eAAe,WAAW,OAAc,QAAmC;CACzE,IAAI,CAAC,MAAM,cAAc,OAAO,SAAS,wBAAwB,YAAY;EAC3E,OAAO;EACP;CACF;CACA,MAAM,QAAQ,CAAC,MAAM,QAAQ,MAAM,SAAS,SAAS,MAAM,OAAO,SAAS,UAAU;CAMrF,OAHE,OAAO,mBAAmB,eAAe,WAAW,eAAe,YAC/D,SAAS,oBAAoB;EAAE;EAAQ;CAAM,CAAC,IAC9C,SAAS,oBAAoB,MAAM,EAAA,CAC3B;AAChB;AAEA,IAAI;AAEJ,MAAM,QAAQ;AACd,MAAM,SAAS;;AAgBf,SAAS,QAAQ,MAAsB;CACrC,MAAM,MAAgB,CAAC;CACvB,MAAM,QAAkB,CAAC;CACzB,MAAM,UAAU,KAAK,iBAAkB,KAAA,CAAmB,iBAAiB,MAAM,GAAG;CACpF,KACE,IAAI,OAAO,OAAO,SAAS,GAC3B,MACA,OAAO,OAAO,SAAS,GACvB;EACA,MAAM,QAAQ,OAAO,KAAK,KAAK,IAAI;EACnC,IAAI,OAAO;GACT,MAAM,SAAiB;IACrB,QAAQ,OAAO,MAA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QAAQ,MAAM,KAAK;EACzB,IAAI,CAAC,OACH;EAEF,IAAI,MAAM,MACR;EAEF,OAAO,MAAM;CACf;CACA,KAAK,MAAM;CACX,OAAO,CAAC,GAAG,KAAK,KAAK,UAAU,GAAG,KAAK;AACzC"}
@@ -1,4 +1,3 @@
1
- import "seroval";
2
1
  //#region src/runtime/shared.d.ts
3
2
  /** An element that the server rendered. The client finds it by its anchor. */
4
3
  declare class ElementReference {
@@ -36,6 +35,17 @@ interface ScopeState {
36
35
  }
37
36
  /** The state of a page, by scope ID. */
38
37
  type PageState = Record<number, ScopeState>;
38
+ /**
39
+ * The page state as the server writes it. Records of scopes that share their
40
+ * kind, their parent or owner, and their shape are in one group of `g`,
41
+ * such as the items of a list, instead of one object each. A group is a flat
42
+ * array: `[kind, base, flags, slotCount, module?, source?, sourceSlot?, ...scopes]`, and each scope
43
+ * is its ID as the gap from the one before it (the first from `base`), its
44
+ * slots, and then its item and its child components, as `flags` says.
45
+ */
46
+ type PackedState = PageState & {
47
+ g?: unknown[][];
48
+ };
39
49
  //#endregion
40
50
  //#region src/runtime/produce.d.ts
41
51
  /**
@@ -46,5 +56,5 @@ type PageState = Record<number, ScopeState>;
46
56
  */
47
57
  declare function produce<T>(base: T, recipe: (draft: T) => T | void): T;
48
58
  //#endregion
49
- export { ScopeState as a, PageState as i, ElementReference as n, FunctionReference as r, produce as t };
50
- //# sourceMappingURL=produce-BjQGMpqL.d.ts.map
59
+ export { PageState as a, PackedState as i, ElementReference as n, ScopeState as o, FunctionReference as r, produce as t };
60
+ //# sourceMappingURL=produce-CtZ32UGG.d.ts.map