brumate 0.1.1 → 0.2.0

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 (108) hide show
  1. package/dist/{boot-DN1ZU8Hg.d.ts → boot-D-IdPy7B.d.ts} +24 -2
  2. package/dist/cli.js +2 -2
  3. package/dist/client-C0UCNL3J.js +1643 -0
  4. package/dist/client-C0UCNL3J.js.map +1 -0
  5. package/dist/{client-DwJInP_a.d.ts → client-MD0ZmcFR.d.ts} +101 -26
  6. package/dist/{client-routes-DakuM32C.js → client-routes-JTbGtukf.js} +28 -15
  7. package/dist/client-routes-JTbGtukf.js.map +1 -0
  8. package/dist/context-CTiSzQRc.js +27 -0
  9. package/dist/context-CTiSzQRc.js.map +1 -0
  10. package/dist/context-btHuB01Z.d.ts +42 -0
  11. package/dist/defer-D0bo1Gqx.js +52 -0
  12. package/dist/defer-D0bo1Gqx.js.map +1 -0
  13. package/dist/{devtools-BKjnHrnv.js → devtools-C50VH8gZ.js} +2 -2
  14. package/dist/devtools-C50VH8gZ.js.map +1 -0
  15. package/dist/{devtools-panel-AWOn0VK2.js → devtools-panel-AYjfwPhj.js} +4 -3
  16. package/dist/devtools-panel-AYjfwPhj.js.map +1 -0
  17. package/dist/events-BKWRqtMg.js +52 -0
  18. package/dist/events-BKWRqtMg.js.map +1 -0
  19. package/dist/{files-DdT84mPy.js → files-Bnn1JqHx.js} +18 -3
  20. package/dist/files-Bnn1JqHx.js.map +1 -0
  21. package/dist/{html-DEeoepg3.js → html-bHZbkK-h.js} +26 -8
  22. package/dist/html-bHZbkK-h.js.map +1 -0
  23. package/dist/{html-Du8jY2Cc.d.ts → html-y1q7-t7D.d.ts} +12 -5
  24. package/dist/index.d.ts +77 -29
  25. package/dist/index.js +12 -4
  26. package/dist/index.js.map +1 -1
  27. package/dist/{inspect-BPchdWbU.js → inspect-BJtACnQp.js} +784 -82
  28. package/dist/inspect-BJtACnQp.js.map +1 -0
  29. package/dist/{loader-Dc9OwY5I.js → loader-B18i3_-T.js} +46 -11
  30. package/dist/loader-B18i3_-T.js.map +1 -0
  31. package/dist/{navigate-CzLjnoPH.js → navigate-BwuZveDF.js} +71 -12
  32. package/dist/navigate-BwuZveDF.js.map +1 -0
  33. package/dist/{produce-BRGHP7e0.js → produce-CWfJ4byV.js} +43 -2
  34. package/dist/produce-CWfJ4byV.js.map +1 -0
  35. package/dist/{produce-CtZ32UGG.d.ts → produce-D4K7qpaL.d.ts} +23 -11
  36. package/dist/routes-BZNt7DSZ.d.ts +38 -0
  37. package/dist/{rpc-9fSqL_YK.js → rpc-B-Zkn6Ch.js} +24 -18
  38. package/dist/rpc-B-Zkn6Ch.js.map +1 -0
  39. package/dist/runtime/batch.d.ts +23 -0
  40. package/dist/runtime/batch.js +69 -0
  41. package/dist/runtime/batch.js.map +1 -0
  42. package/dist/runtime/client.d.ts +5 -5
  43. package/dist/runtime/client.js +5 -1345
  44. package/dist/runtime/context.d.ts +2 -2
  45. package/dist/runtime/context.js +1 -1
  46. package/dist/runtime/devtools.d.ts +5 -4
  47. package/dist/runtime/devtools.js +1 -1
  48. package/dist/runtime/env.d.ts +44 -0
  49. package/dist/runtime/env.js +61 -0
  50. package/dist/runtime/env.js.map +1 -0
  51. package/dist/runtime/events.d.ts +27 -0
  52. package/dist/runtime/events.js +1 -0
  53. package/dist/runtime/hot.d.ts +1 -1
  54. package/dist/runtime/html.d.ts +2 -2
  55. package/dist/runtime/html.js +1 -1
  56. package/dist/runtime/loader.d.ts +2 -2
  57. package/dist/runtime/loader.js +2 -2
  58. package/dist/runtime/routes.d.ts +2 -21
  59. package/dist/runtime/routes.js +31 -1
  60. package/dist/runtime/routes.js.map +1 -1
  61. package/dist/runtime/server.d.ts +6 -5
  62. package/dist/runtime/server.js +5 -6
  63. package/dist/runtime/signals.d.ts +22 -1
  64. package/dist/runtime/signals.js +29 -1
  65. package/dist/runtime/signals.js.map +1 -1
  66. package/dist/runtime/static-loader.d.ts +2 -2
  67. package/dist/runtime/static-loader.js +1 -1
  68. package/dist/runtime/testing.d.ts +46 -5
  69. package/dist/runtime/testing.js +240 -33
  70. package/dist/runtime/testing.js.map +1 -1
  71. package/dist/secrets-BxagsJxJ.js +23 -0
  72. package/dist/secrets-BxagsJxJ.js.map +1 -0
  73. package/dist/{server-BxqjLUnV.d.ts → server-BA9SJ2Vm.d.ts} +544 -106
  74. package/dist/server-BqfM95r1.js +2762 -0
  75. package/dist/server-BqfM95r1.js.map +1 -0
  76. package/dist/skew-FRmAy9iy.js +49 -0
  77. package/dist/skew-FRmAy9iy.js.map +1 -0
  78. package/dist/standard-schema-BNY82yX3.d.ts +63 -0
  79. package/dist/{static-loader-BcFh4ebX.d.ts → static-loader-BzE9SRaj.d.ts} +2 -2
  80. package/dist/{static-loader-ClNkHZGn.js → static-loader-DOygOFj5.js} +52 -21
  81. package/dist/static-loader-DOygOFj5.js.map +1 -0
  82. package/dist/{stream-bgNCMcaA.js → stream-JaMHMdBD.js} +126 -61
  83. package/dist/stream-JaMHMdBD.js.map +1 -0
  84. package/dist/vite.d.ts +42 -1
  85. package/dist/vite.js +435 -55
  86. package/dist/vite.js.map +1 -1
  87. package/package.json +15 -2
  88. package/types.d.ts +9 -1
  89. package/dist/client-routes-DakuM32C.js.map +0 -1
  90. package/dist/context-BG8KCF3v.js +0 -15
  91. package/dist/context-BG8KCF3v.js.map +0 -1
  92. package/dist/context-aeo9esY9.d.ts +0 -16
  93. package/dist/devtools-BKjnHrnv.js.map +0 -1
  94. package/dist/devtools-panel-AWOn0VK2.js.map +0 -1
  95. package/dist/files-DdT84mPy.js.map +0 -1
  96. package/dist/html-DEeoepg3.js.map +0 -1
  97. package/dist/inspect-BPchdWbU.js.map +0 -1
  98. package/dist/loader-Dc9OwY5I.js.map +0 -1
  99. package/dist/navigate-CzLjnoPH.js.map +0 -1
  100. package/dist/produce-BRGHP7e0.js.map +0 -1
  101. package/dist/rpc-9fSqL_YK.js.map +0 -1
  102. package/dist/runtime/client.js.map +0 -1
  103. package/dist/server-DZsgnPKS.js +0 -1615
  104. package/dist/server-DZsgnPKS.js.map +0 -1
  105. package/dist/shared-CWYOd0H3.js +0 -40
  106. package/dist/shared-CWYOd0H3.js.map +0 -1
  107. package/dist/static-loader-ClNkHZGn.js.map +0 -1
  108. package/dist/stream-bgNCMcaA.js.map +0 -1
@@ -1,4 +1,5 @@
1
- import { i as strategy, n as boot, r as importCore } from "./static-loader-ClNkHZGn.js";
1
+ import { n as ROUTE_KEY, t as NAVIGATION_KEY } from "./context-CTiSzQRc.js";
2
+ import { i as strategy, n as boot, r as importCore } from "./static-loader-DOygOFj5.js";
2
3
  //#region src/runtime/loader.ts
3
4
  /**
4
5
  * Starts resuming the page. Listens to the events in `b-on` attributes
@@ -10,7 +11,7 @@ function start(options) {
10
11
  }
11
12
  /** Starts loading the page of a link, unless the link asks not to. */
12
13
  function prefetch(link) {
13
- if (link && strategy(link) !== "none") import("./navigate-CzLjnoPH.js").then((module) => module.prefetch(link.href));
14
+ if (link && strategy(link) !== "none") import("./navigate-BwuZveDF.js").then((module) => module.prefetch(link.href));
14
15
  }
15
16
  /**
16
17
  * Imports the code with which the core reads the pages that navigation adds.
@@ -18,25 +19,53 @@ function prefetch(link) {
18
19
  * later loads it with the core, when the page has records that navigation
19
20
  * marked.
20
21
  */
21
- const routes = () => import("./client-routes-DakuM32C.js").then((module) => module.ready);
22
+ const routes = () => import("./client-routes-JTbGtukf.js").then((module) => module.ready);
22
23
  /**
23
24
  * Loads pages without a full page load: links to the same origin, the back
24
25
  * and forward buttons, forms that post to a server function, and redirects
25
26
  * from server functions to the same origin. Returns how the loader imports
26
27
  * the core.
27
28
  */
28
- function navigation({ options, listen, core, scan }) {
29
+ function navigation({ options, listen, core, start: startCore, scan }) {
29
30
  const rpc = `${options.rpc ?? "/_brumate"}/`;
31
+ const settings = typeof options.navigate === "object" ? options.navigate : {};
30
32
  let page = String(location.href).split("#")[0];
31
- const go = (url, init, push = true, reload = false) => {
33
+ let skewed = false;
34
+ listen(document, "brumate:skew", () => {
35
+ skewed = true;
36
+ });
37
+ const reader = (key) => core() ?? ([...document.querySelectorAll("script[b-state]")].some((script) => script.textContent?.includes(key)) ? startCore() : void 0);
38
+ const state = (value) => {
39
+ reader(NAVIGATION_KEY)?.then((client) => client.setGlobal(NAVIGATION_KEY, value));
40
+ };
41
+ const go = (url, init, push = true, reload = false, scroll = true) => {
42
+ const from = location.href;
43
+ if (skewed) {
44
+ if (init) location.reload();
45
+ else location.assign(url);
46
+ return Promise.resolve();
47
+ }
32
48
  page = url.split("#")[0];
33
49
  if (core()) routes();
34
- import("./navigate-CzLjnoPH.js").then((module) => module.navigate({
50
+ document.documentElement.setAttribute("data-navigating", "");
51
+ state({
52
+ pending: true,
53
+ from,
54
+ to: new URL(url, from).href
55
+ });
56
+ const done = () => {
57
+ document.documentElement.removeAttribute("data-navigating");
58
+ state({ pending: false });
59
+ };
60
+ return import("./navigate-BwuZveDF.js").then((module) => module.navigate({
35
61
  url,
36
62
  init,
37
63
  push,
38
64
  reload,
39
- transition: typeof options.navigate === "object" && options.navigate.transition === true,
65
+ scroll,
66
+ build: options.build,
67
+ focus: settings.focus !== false,
68
+ transition: settings.transition === true,
40
69
  leave: async (partial) => {
41
70
  if (core()) (await routes())(partial);
42
71
  },
@@ -45,10 +74,16 @@ function navigation({ options, listen, core, scan }) {
45
74
  ...options,
46
75
  listen: scan
47
76
  }));
77
+ reader(ROUTE_KEY)?.then((client) => client.updateRoute());
48
78
  page = location.href.split("#")[0];
49
79
  }
50
- }));
80
+ })).finally(done);
51
81
  };
82
+ listen(document, "brumate:navigate", (event) => {
83
+ const detail = event.detail;
84
+ event.preventDefault();
85
+ go(detail.url, void 0, !detail.replace, false, detail.scroll).then(detail.done);
86
+ });
52
87
  const pageLink = (target) => {
53
88
  const link = target?.closest?.("a[href]");
54
89
  return link && !link.target && !link.matches("[download],[data-reload]") && link.origin === location.origin && !(link.hash && link.href.split("#")[0] === page) ? link : void 0;
@@ -75,7 +110,7 @@ function navigation({ options, listen, core, scan }) {
75
110
  const submitter = event.submitter;
76
111
  const action = submitter?.getAttribute("formaction") ?? form.getAttribute("action") ?? "";
77
112
  const method = submitter?.getAttribute("formmethod") ?? form.getAttribute("method");
78
- if (event.defaultPrevented || method?.toLowerCase() !== "post" || !action.startsWith(rpc)) return;
113
+ if (event.defaultPrevented || method?.toLowerCase() !== "post" || !action.startsWith(rpc) || skewed) return;
79
114
  event.preventDefault();
80
115
  go(action, {
81
116
  method: "POST",
@@ -89,7 +124,7 @@ function navigation({ options, listen, core, scan }) {
89
124
  go(url.href, void 0, true, true);
90
125
  }
91
126
  });
92
- listen(document, "brumate:reload", () => go(location.href, { method: "GET" }, false));
127
+ listen(document, "brumate:reload", () => void go(location.href, { method: "GET" }, false));
93
128
  listen(window, "popstate", () => {
94
129
  if (location.href.split("#")[0] !== page) go(location.href, void 0, false);
95
130
  });
@@ -98,4 +133,4 @@ function navigation({ options, listen, core, scan }) {
98
133
  //#endregion
99
134
  export { start as t };
100
135
 
101
- //# sourceMappingURL=loader-Dc9OwY5I.js.map
136
+ //# sourceMappingURL=loader-B18i3_-T.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loader-B18i3_-T.js","names":[],"sources":["../src/runtime/loader.ts"],"sourcesContent":["import type * as Routes from './client-routes.ts';\nimport { boot, importCore, strategy } from './boot.ts';\nimport { NAVIGATION_KEY, ROUTE_KEY } from './context.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({\n options,\n listen,\n core,\n start: startCore,\n scan,\n}: Navigation): () => Promise<Core> {\n const rpc = `${options.rpc ?? '/_brumate'}/`;\n const settings = typeof options.navigate === 'object' ? options.navigate : {};\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 // True once the site changed since the page loaded: the next page loads in full, with new code.\n let skewed = false;\n listen(document, 'brumate:skew', () => {\n skewed = true;\n });\n // The core when the page reads a context of navigation, which it starts for them, or when it runs.\n const reader = (key: string): Promise<Core> | undefined =>\n core() ??\n ([...document.querySelectorAll('script[b-state]')].some((script) =>\n script.textContent?.includes(key),\n )\n ? startCore()\n : undefined);\n const state = (value: { pending: boolean; from?: string; to?: string }): void => {\n void reader(NAVIGATION_KEY)?.then((client) => client.setGlobal(NAVIGATION_KEY, value));\n };\n const go = (\n url: string,\n init?: RequestInit,\n push = true,\n reload = false,\n scroll = true,\n ): Promise<void> => {\n const from = location.href;\n if (skewed) {\n // A form post cannot be a full page load: the page loads again, and the form is lost with\n // the rest of the state of the page.\n if (init) {\n location.reload();\n } else {\n location.assign(url);\n }\n return Promise.resolve();\n }\n page = url.split('#')[0]!;\n if (core()) {\n void routes();\n }\n // CSS can show a progress bar while a page loads, with no client code in the page.\n document.documentElement.setAttribute('data-navigating', '');\n state({ pending: true, from, to: new URL(url, from).href });\n const done = (): void => {\n document.documentElement.removeAttribute('data-navigating');\n state({ pending: false });\n };\n return import('./navigate.ts')\n .then((module) =>\n module.navigate({\n url,\n init,\n push,\n reload,\n scroll,\n build: options.build,\n focus: settings.focus !== false,\n transition: settings.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 // Code that reads the route, such as in a layout that stays, gets the new one.\n void reader(ROUTE_KEY)?.then((client) => client.updateRoute());\n page = location.href.split('#')[0]!;\n },\n }),\n )\n .finally(done);\n };\n // `navigate(href, options)` from `brumate/routes`.\n listen(document, 'brumate:navigate', (event) => {\n const detail = (\n event as CustomEvent<{ url: string; replace: boolean; scroll: boolean; done: () => void }>\n ).detail;\n event.preventDefault();\n void go(detail.url, undefined, !detail.replace, false, detail.scroll).then(detail.done);\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 void 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 (\n event.defaultPrevented ||\n method?.toLowerCase() !== 'post' ||\n !action.startsWith(rpc) ||\n // After a deploy, the browser posts the form itself, and the page that answers is new.\n skewed\n ) {\n return;\n }\n event.preventDefault();\n void 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 void 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', () => void 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 void 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":";;;;;;;;AAaA,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,EAClB,SACA,QACA,MACA,OAAO,WACP,QACkC;CAClC,MAAM,MAAM,GAAG,QAAQ,OAAO,YAAY;CAC1C,MAAM,WAAW,OAAO,QAAQ,aAAa,WAAW,QAAQ,WAAW,CAAC;CAE5E,IAAI,OAAO,OAAO,SAAS,IAAI,C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,aAAa,QAAQ,KAAK;EACvF,MAAM,SAAS,WAAW,aAAa,YAAY,KAAK,KAAK,aAAa,QAAQ;EAClF,IACE,MAAM,oBACN,QAAQ,YAAY,MAAM,UAC1B,CAAC,OAAO,WAAW,GAAG,KAEtB,QAEA;EAEF,MAAM,eAAe;EACrB,GAAQ,QAAQ;GAAE,QAAQ;GAAQ,MAAM,IAAI,SAAS,MAAM,SAAS;EAAE,CAAC;CACzE,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,GAAQ,IAAI,MAAM,KAAA,GAAW,MAAM,IAAI;EACzC;CACF,CAAC;CAGD,OAAO,UAAU,wBAAwB,KAAK,GAAG,SAAS,MAAM,EAAE,QAAQ,MAAM,GAAG,KAAK,CAAC;CACzF,OAAO,QAAQ,kBAAkB;EAE/B,IAAI,SAAS,KAAK,MAAM,GAAG,CAAC,CAAC,OAAO,MAClC,GAAQ,SAAS,MAAM,KAAA,GAAW,KAAK;CAE3C,CAAC;CACD,aACE,QAAQ,IAAI,CAAC,WAAW,GAAG,SAAS,cAAc,sBAAsB,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,MACrF,CAAC,YAAY,MAChB;AACJ"}
@@ -1,3 +1,4 @@
1
+ import { r as trustedScript, t as loadOnce } from "./skew-FRmAy9iy.js";
1
2
  //#region src/runtime/navigate.ts
2
3
  /**
3
4
  * Runs `update` inside a view transition, with a type that tells how the page
@@ -17,7 +18,7 @@ async function transition(visit, update) {
17
18
  }
18
19
  let controller;
19
20
  const STATE = "script[b-state]";
20
- const REGION = /^R(-?\d+):([^:]+):(\d+):(.*)$/;
21
+ const REGION = /^R(-?[\d.]+):([^:]+):([\d.]+):(.*)$/;
21
22
  /** Finds the route slots in a document, nested as the routes are. */
22
23
  function regions(root) {
23
24
  const top = [];
@@ -27,9 +28,9 @@ function regions(root) {
27
28
  const match = REGION.exec(node.data);
28
29
  if (match) {
29
30
  const region = {
30
- layout: Number(match[1]),
31
+ layout: match[1],
31
32
  name: match[2],
32
- root: Number(match[3]),
33
+ root: match[3],
33
34
  key: decodeURIComponent(match[4]),
34
35
  start: node,
35
36
  end: node,
@@ -101,6 +102,7 @@ function planRoutes(next, state, requested) {
101
102
  }
102
103
  /** Replaces the routes that change, and keeps the rest of the page. */
103
104
  function replaceRoutes(next, state, result) {
105
+ const added = [];
104
106
  const removed = [];
105
107
  for (const [before, region] of result.replace) {
106
108
  const nodes = between(before.start, before.end);
@@ -110,7 +112,10 @@ function replaceRoutes(next, state, result) {
110
112
  removed.push(...element.querySelectorAll("style[b-style]"));
111
113
  }
112
114
  const parent = before.start.parentNode;
113
- for (const node of between(region.start, region.end)) parent.insertBefore(document.adoptNode(node), before.start);
115
+ for (const node of between(region.start, region.end)) {
116
+ added.push(node);
117
+ parent.insertBefore(document.adoptNode(node), before.start);
118
+ }
114
119
  for (const node of nodes) node.parentNode?.removeChild(node);
115
120
  }
116
121
  keepStyles(removed);
@@ -118,6 +123,40 @@ function replaceRoutes(next, state, result) {
118
123
  state.setAttribute("b-roots", result.replace.map(([, region]) => region.root).join(","));
119
124
  state.setAttribute("b-alias", [...result.alias].map(([from, to]) => `${from}:${to}`).join(","));
120
125
  for (const script of next.body.querySelectorAll(STATE)) document.body.append(runnable(script));
126
+ return added;
127
+ }
128
+ /** Visually hidden, so only a screen reader reads it. */
129
+ const HIDDEN = "position:absolute;width:1px;height:1px;margin:-1px;padding:0;border:0;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap";
130
+ /**
131
+ * Tells a screen reader that the page changed, as a full page load does:
132
+ * the text of `<meta name="brumate-announce">` of the new page, or its title,
133
+ * or its first heading, in a live region of the loader.
134
+ */
135
+ function announce(text) {
136
+ let region = document.querySelector("[b-announcer]");
137
+ if (!region) {
138
+ region = document.createElement("div");
139
+ region.setAttribute("b-announcer", "");
140
+ region.setAttribute("aria-live", "assertive");
141
+ region.setAttribute("aria-atomic", "true");
142
+ region.setAttribute("style", HIDDEN);
143
+ document.body.append(region);
144
+ }
145
+ region.textContent = text;
146
+ }
147
+ /**
148
+ * Moves the focus to the first `<h1>` of the new content, or to `<main>`,
149
+ * so the next Tab starts there, as after a full page load. An element that
150
+ * cannot take the focus gets `tabindex="-1"` until it loses it.
151
+ */
152
+ function moveFocus(added) {
153
+ const elements = added.filter((node) => node.nodeType === 1);
154
+ const target = elements.find((element) => element.matches("h1")) ?? elements.map((element) => element.querySelector("h1")).find(Boolean) ?? document.querySelector("main") ?? document.body;
155
+ if (!target.hasAttribute("tabindex") && target !== document.body) {
156
+ target.setAttribute("tabindex", "-1");
157
+ target.addEventListener("blur", () => target.removeAttribute("tabindex"), { once: true });
158
+ }
159
+ target.focus({ preventScroll: true });
121
160
  }
122
161
  /**
123
162
  * A page whose IDs do not start where this page asked, such as a prerendered
@@ -132,7 +171,7 @@ function shiftFor(state, requested) {
132
171
  root: String(requested)
133
172
  };
134
173
  }
135
- const COMMENT_IDS = /^([tb])(\d+)(:.*)$|^([ilP])(\d+)$/;
174
+ const COMMENT_IDS = /^([tb])([\d.]+)(:.*)$|^([ilP])([\d.]+)$/;
136
175
  /** Attributes that hold a scope ID, then `:` and more. */
137
176
  const SCOPED = ["b-b", "b-result"];
138
177
  /** Attributes that hold only a scope or boundary ID. */
@@ -148,13 +187,16 @@ const IDS = [
148
187
  * the IDs inside a state record when it reads one with `b-offset`.
149
188
  */
150
189
  function shiftIds(root, shift) {
151
- const add = (value) => String(Number(value) + shift.by);
190
+ const add = (value) => {
191
+ const dot = value.indexOf(".");
192
+ return dot === -1 ? String(Number(value) + shift.by) : `${Number(value.slice(0, dot)) + shift.by}${value.slice(dot)}`;
193
+ };
152
194
  const visit = (node) => {
153
195
  if (node.nodeType === 8) {
154
196
  const comment = node;
155
197
  const region = REGION.exec(comment.data);
156
198
  if (region) {
157
- comment.data = `R${Number(region[1]) < 0 ? region[1] : add(region[1])}:${region[2]}:${add(region[3])}:${region[4]}`;
199
+ comment.data = `R${region[1].startsWith("-") ? region[1] : add(region[1])}:${region[2]}:${add(region[3])}:${region[4]}`;
158
200
  return;
159
201
  }
160
202
  const match = COMMENT_IDS.exec(comment.data);
@@ -174,10 +216,15 @@ function shiftIds(root, shift) {
174
216
  const value = element.getAttribute(name);
175
217
  if (value) element.setAttribute(name, add(value));
176
218
  }
219
+ const defer = element.getAttribute("b-defer");
220
+ if (defer) {
221
+ const [trigger, boundary, from] = defer.split(":");
222
+ element.setAttribute("b-defer", `${trigger}:${add(boundary)}:${add(from)}`);
223
+ }
177
224
  if (element.localName === "script" && element.matches(STATE)) {
178
225
  element.setAttribute("b-offset", String(shift.by));
179
226
  element.setAttribute("b-root", shift.root);
180
- } else if (element.tagName === "SCRIPT" && !element.hasAttribute("type")) element.textContent = element.textContent.replace(/\$b([SH])\((\d+)/g, (_, kind, id) => `$b${kind}(${add(id)}`);
227
+ } else if (element.tagName === "SCRIPT" && !element.hasAttribute("type")) element.textContent = trustedScript(element.textContent.replace(/\$b([SH])\(("?)([\d.]+)/g, (_, kind, quote, id) => `$b${kind}(${quote}${add(id)}`));
181
228
  for (const child of element.tagName === "TEMPLATE" ? element.content.childNodes : element.childNodes) visit(child);
182
229
  };
183
230
  visit(root);
@@ -214,7 +261,7 @@ function runnable(script) {
214
261
  copy.nonce = pageNonce() ?? nonce;
215
262
  copy.setAttribute("nonce", copy.nonce);
216
263
  }
217
- copy.textContent = script.textContent;
264
+ copy.textContent = trustedScript(script.textContent ?? "");
218
265
  return copy;
219
266
  }
220
267
  /** Moves nodes into the body. Inline scripts, such as the ones that swap in `#loading` bodies, run. */
@@ -368,6 +415,12 @@ async function navigate(visit) {
368
415
  }
369
416
  const next = new DOMParser().parseFromString(text.slice(0, end), "text/html");
370
417
  const state = next.body.querySelector(`${STATE}[b-route]`);
418
+ const nextBuild = state?.getAttribute("b-build") ?? void 0;
419
+ if (visit.build !== void 0 && nextBuild !== void 0 && nextBuild !== visit.build && loadOnce(nextBuild)) {
420
+ stop();
421
+ location.assign(url.href);
422
+ return;
423
+ }
371
424
  const shift = visit.init ? void 0 : shiftFor(state, requested);
372
425
  if (shift) shiftIds(next.body, shift);
373
426
  const routes = visit.init || visit.reload ? void 0 : planRoutes(next, state, requested);
@@ -380,20 +433,26 @@ async function navigate(visit) {
380
433
  for (const attribute of [...document.documentElement.attributes]) document.documentElement.removeAttribute(attribute.name);
381
434
  for (const attribute of next.documentElement.attributes) document.documentElement.setAttribute(attribute.name, attribute.value);
382
435
  const title = next.title;
436
+ const announced = next.head.querySelector("meta[name=\"brumate-announce\"]")?.getAttribute("content") || title || next.body.querySelector("h1")?.textContent || "";
383
437
  updateHead(next);
384
438
  document.title = title;
385
439
  const same = url.href === location.href;
440
+ const samePath = url.pathname === location.pathname;
386
441
  const top = window.scrollY;
387
- if (routes) replaceRoutes(next, state, routes);
442
+ let added;
443
+ if (routes) added = replaceRoutes(next, state, routes);
388
444
  else {
445
+ added = [next.body];
389
446
  document.body.replaceWith(document.adoptNode(next.body));
390
447
  for (const script of document.body.querySelectorAll(STATE)) script.replaceWith(runnable(script));
391
448
  }
392
449
  if (visit.push && !same) history.pushState({}, "", url);
393
450
  else if (!same) history.replaceState(history.state, "", url);
394
451
  visit.enter();
395
- if ((visit.init || visit.reload) && same) window.scrollTo(0, top);
452
+ if (visit.scroll === false || (visit.init || visit.reload) && same) window.scrollTo(0, top);
396
453
  else scroll(url, visit.push ? void 0 : history.state?.scroll);
454
+ if (!samePath && announced) announce(announced);
455
+ if (visit.focus && !samePath) moveFocus(added);
397
456
  });
398
457
  if (current.signal.aborted) {
399
458
  stop();
@@ -419,4 +478,4 @@ async function navigate(visit) {
419
478
  //#endregion
420
479
  export { navigate, prefetch };
421
480
 
422
- //# sourceMappingURL=navigate-CzLjnoPH.js.map
481
+ //# sourceMappingURL=navigate-BwuZveDF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"navigate-BwuZveDF.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\nimport { loadOnce } from './skew.ts';\nimport { trustedScript } from './trusted.ts';\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 /** Scrolls to the top of the new page, or to its hash. Defaults to true. */\n scroll?: boolean;\n /** Moves the focus to the new content, as a full page load does. Defaults to false. */\n focus?: 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 * The ID of the build of this page. A page of another build loads in\n * full, because the layouts that stay are code of this one.\n */\n build?: string;\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]';\n// A route that a block of its layout renders has a scope ID with a dot, such as `3.0`.\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, as the comment writes it. */\n layout: string;\n name: string;\n /** The scope of the route in the slot. */\n root: string;\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: match[1]!,\n name: match[2]!,\n root: 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<string, string>;\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): Node[] {\n const added: Node[] = [];\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 added.push(node);\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 return added;\n}\n\n/** Visually hidden, so only a screen reader reads it. */\nconst HIDDEN =\n 'position:absolute;width:1px;height:1px;margin:-1px;padding:0;border:0;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap';\n\n/**\n * Tells a screen reader that the page changed, as a full page load does:\n * the text of `<meta name=\"brumate-announce\">` of the new page, or its title,\n * or its first heading, in a live region of the loader.\n */\nfunction announce(text: string): void {\n let region = document.querySelector<HTMLElement>('[b-announcer]');\n if (!region) {\n region = document.createElement('div');\n region.setAttribute('b-announcer', '');\n region.setAttribute('aria-live', 'assertive');\n region.setAttribute('aria-atomic', 'true');\n region.setAttribute('style', HIDDEN);\n document.body.append(region);\n }\n region.textContent = text;\n}\n\n/**\n * Moves the focus to the first `<h1>` of the new content, or to `<main>`,\n * so the next Tab starts there, as after a full page load. An element that\n * cannot take the focus gets `tabindex=\"-1\"` until it loses it.\n */\nfunction moveFocus(added: Node[]): void {\n const elements = added.filter((node): node is Element => node.nodeType === 1);\n const heading =\n elements.find((element) => element.matches('h1')) ??\n elements.map((element) => element.querySelector('h1')).find(Boolean);\n const target = (heading ?? document.querySelector('main') ?? document.body) as HTMLElement;\n if (!target.hasAttribute('tabindex') && target !== document.body) {\n target.setAttribute('tabindex', '-1');\n target.addEventListener('blur', () => target.removeAttribute('tabindex'), { once: true });\n }\n target.focus({ preventScroll: true });\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\n// An ID inside a `#loading` body is the boundary's ID, a dot and more, such as `5.1`.\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 // An ID inside a boundary moves with its boundary, the number before the first dot.\n const add = (value: string): string => {\n const dot = value.indexOf('.');\n return dot === -1\n ? String(Number(value) + shift.by)\n : `${Number(value.slice(0, dot)) + shift.by}${value.slice(dot)}`;\n };\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 = region[1]!.startsWith('-') ? 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 // A `#defer` block: `<trigger>:<boundary>:<base>`. The page now renders from the new base.\n const defer = element.getAttribute('b-defer');\n if (defer) {\n const [trigger, boundary, from] = defer.split(':') as [string, string, string];\n element.setAttribute('b-defer', `${trigger}:${add(boundary)}:${add(from)}`);\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 = trustedScript(\n element.textContent!.replace(\n /\\$b([SH])\\((\"?)([\\d.]+)/g,\n (_, kind: string, quote: string, id: string) => `$b${kind}(${quote}${add(id)}`,\n ),\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 = trustedScript(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 // A page of another build: the site was deployed since this page loaded, so it loads in full,\n // once for each build. When two builds answer in turn during a deploy, the page swaps in.\n const nextBuild = state?.getAttribute('b-build') ?? undefined;\n if (\n visit.build !== undefined &&\n nextBuild !== undefined &&\n nextBuild !== visit.build &&\n loadOnce(nextBuild)\n ) {\n stop();\n location.assign(url.href);\n return;\n }\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 const announced =\n next.head.querySelector('meta[name=\"brumate-announce\"]')?.getAttribute('content') ||\n title ||\n next.body.querySelector('h1')?.textContent ||\n '';\n updateHead(next);\n document.title = title;\n const same = url.href === location.href;\n // A change of only the query string, such as a filter, keeps the focus, so typing goes on.\n const samePath = url.pathname === location.pathname;\n const top = window.scrollY;\n let added: Node[];\n if (routes) {\n added = replaceRoutes(next, state!, routes);\n } else {\n added = [next.body];\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.scroll === false || ((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 if (!samePath && announced) {\n announce(announced);\n }\n if (visit.focus && !samePath) {\n moveFocus(added);\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":";;;;;;;AA0CA,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;AAEd,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,MAAM;IACd,MAAM,MAAM;IACZ,MAAM,MA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GAAG,GAAG;OAEtB,OAAO,KAAK,MAAM,OAAO,KAAA,IAAa,QAAQ,OAAO,MAA6B;EAEpF,IAAI,CAAC,YAAY,WACf,SAAS,SAAS;EAEpB,IAAI,MAAM,SAAS,CAAC,UAClB,UAAU,KAAK;CAEnB,CAAC;CACD,IAAI,QAAQ,OAAO,SAAS;EAC1B,KAAK;EACL;CACF;CAIA,MAAM,OAAO,SAAS,eAAe,mBAAmB,EAAE;CAC1D,KAAK,KAAK;CACV,KAAK,MAAM,uBAAuB;CAClC,IAAI,OAAO,KAAK,MAAM,GAAG;CACzB,SAAS;EACP,IAAI,MAAM;GACR,KAAK,MAAM,IAAI;GACf,OAAO,CAAC,GAAG,KAAK,KAAK,UAAU,CAAC,CAAC,MAAM,GAAG,EAAE,GAAG,KAAK;EACtD;EAEA,MAAM,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,3 +1,44 @@
1
+ import { p as raw } from "./html-bHZbkK-h.js";
2
+ //#region src/runtime/shared.ts
3
+ /** Reads a scope or boundary ID from markup. */
4
+ function parseId(text) {
5
+ return /^-?\d+$/.test(text) ? Number(text) : text;
6
+ }
7
+ /** An element that the server rendered. The client finds it by its anchor. */
8
+ var ElementReference = class {
9
+ scope;
10
+ anchor;
11
+ constructor(scope, anchor) {
12
+ this.scope = scope;
13
+ this.anchor = anchor;
14
+ }
15
+ };
16
+ /** A client function: an export of a client module, and the scope it reads. */
17
+ var FunctionReference = class {
18
+ /** `<component id>#<export name>`. */
19
+ ref;
20
+ scope;
21
+ constructor(ref, scope) {
22
+ this.ref = ref;
23
+ this.scope = scope;
24
+ }
25
+ };
26
+ /**
27
+ * Makes the values of brumate's plugins. A state record calls them as `$b`,
28
+ * with one letter each, and the plugins read nodes of server function calls
29
+ * with them too, so both give the same values.
30
+ */
31
+ const stateValues = {
32
+ e: (scope, anchor) => new ElementReference(scope, anchor),
33
+ f: (ref, scope) => new FunctionReference(ref, scope),
34
+ r: raw,
35
+ c: (id) => Object.assign(() => "", { brumateId: id })
36
+ };
37
+ /** True for a value that `for await` reads, such as the result of an async generator. */
38
+ function isAsyncIterable(value) {
39
+ return value !== null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function";
40
+ }
41
+ //#endregion
1
42
  //#region src/runtime/produce.ts
2
43
  const DRAFT = Symbol("brumate.draft");
3
44
  /** Plain objects and arrays can be drafted. Other values, such as `Map`, are used as they are. */
@@ -121,6 +162,6 @@ function resolve(value, seen) {
121
162
  return value;
122
163
  }
123
164
  //#endregion
124
- export { produce as t };
165
+ export { parseId as a, isAsyncIterable as i, ElementReference as n, stateValues as o, FunctionReference as r, produce as t };
125
166
 
126
- //# sourceMappingURL=produce-BRGHP7e0.js.map
167
+ //# sourceMappingURL=produce-CWfJ4byV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"produce-CWfJ4byV.js","names":[],"sources":["../src/runtime/shared.ts","../src/runtime/produce.ts"],"sourcesContent":["// Values and types that the server and the browser share. It does not import\n// seroval, so the core, which reads the page state without it, stays small.\n// The plugins that write and read these values are in `serial.ts`.\n\nimport { raw } from './html.ts';\nimport type { Raw } from './html.ts';\n\n/**\n * The ID of a scope or of a `#loading` boundary. The rest of the page numbers\n * its scopes from the base of the render, such as `3`. A `#loading` body\n * numbers its own from 0 after the ID of its boundary and a dot, such as\n * `5.0` and `5.1`, so its IDs do not depend on when its data arrives.\n */\nexport type ScopeId = number | string;\n\n/** Reads a scope or boundary ID from markup. */\nexport function parseId(text: string): ScopeId {\n return /^-?\\d+$/.test(text) ? Number(text) : text;\n}\n\n/** Adds a number to an ID. An ID inside a boundary moves with its boundary. */\nexport function shiftId(id: ScopeId, by: number): ScopeId {\n if (typeof id === 'number') {\n return id + by;\n }\n const dot = id.indexOf('.');\n return `${Number(id.slice(0, dot)) + by}${id.slice(dot)}`;\n}\n\n/** An element that the server rendered. The client finds it by its anchor. */\nexport class ElementReference {\n readonly scope: ScopeId;\n readonly anchor: number;\n\n constructor(scope: ScopeId, anchor: number) {\n this.scope = scope;\n this.anchor = anchor;\n }\n}\n\n/** A client function: an export of a client module, and the scope it reads. */\nexport class FunctionReference {\n /** `<component id>#<export name>`. */\n readonly ref: string;\n readonly scope: ScopeId;\n\n constructor(ref: string, scope: ScopeId) {\n this.ref = ref;\n this.scope = scope;\n }\n}\n\n/** A component, which the compiler marks with its ID. */\nexport type ComponentValue = ((...args: never[]) => unknown) & { brumateId: string };\n\n/**\n * Makes the values of brumate's plugins. A state record calls them as `$b`,\n * with one letter each, and the plugins read nodes of server function calls\n * with them too, so both give the same values.\n */\nexport const stateValues: {\n /** An element that the server rendered, by its scope and anchor. */\n e: (scope: ScopeId, anchor: number) => ElementReference;\n /** A client function, by its reference and scope. */\n f: (ref: string, scope: ScopeId) => FunctionReference;\n /** HTML that the client may insert again. */\n r: (html: string) => Raw;\n /**\n * A component, such as the value of a dynamic tag. The client gets a\n * function with the same ID that renders nothing. The client code that\n * changes the value uses the component's render module instead.\n */\n c: (id: string) => ComponentValue;\n} = {\n e: (scope, anchor) => new ElementReference(scope, anchor),\n f: (ref, scope) => new FunctionReference(ref, scope),\n r: raw,\n c: (id) => Object.assign(() => '', { brumateId: id }),\n};\n\n/** True for a value that `for await` reads, such as the result of an async generator. */\nexport function isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {\n return (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as AsyncIterable<unknown>)[Symbol.asyncIterator] === 'function'\n );\n}\n\n/** The state of one scope in the page. */\nexport interface ScopeState {\n /** The scope's ID in the compiled component. */\n k?: number;\n /** The ID of the scope that contains this one. Component root scopes have none. */\n p?: ScopeId;\n /** The component ID of a component's root scope. */\n m?: string;\n /** The item of a list item scope. */\n i?: unknown;\n /** The scope that rendered a component's root scope, for finding contexts. */\n o?: ScopeId;\n /**\n * For a scope of children that a component inserted, the scope where they\n * are, which contexts are found from in place of `p` and `o`.\n */\n t?: ScopeId;\n /** The values that the scope provides, by context key. */\n v?: Record<string, unknown>;\n /** The slots that hold the contexts that the scope reads, by context key. */\n x?: Record<string, number>;\n /** Slot values, in the order of the scope's layout. */\n s?: unknown[];\n /** The scope IDs of child components, by anchor index. */\n c?: Record<number, ScopeId>;\n}\n\n/** The state of a page, by scope ID. */\nexport type PageState = Record<ScopeId, ScopeState>;\n\n/**\n * The flags of a group of scope records in `PackedState`:\n * - `ITEM_SLOT`: the item of each scope is its first slot.\n * - `ITEM`: each scope has its item after its slots.\n * - `CHILDREN`: each scope has its child components after that.\n * - `OWNER`: the scopes are component root scopes. `base` is the distance from the scope that\n * rendered each one, `o`, to the scope, and the first gap is from 0. Otherwise `base` is the\n * parent, `p`, of every scope.\n * - `MODULE`: the group has the component ID of its scopes after its header.\n * - `SOURCE`: the scopes are the items of a list whose list is a slot of an enclosing scope.\n * The header then has that scope's ID and the slot's index, and the items are not written:\n * the item of the scope at position `n` in the group is the value at `n` of the list, or of\n * `Array.from` of a Set. With `ITEM_SLOT`, each scope writes its slots after the first.\n * - `PREFIX`: the scopes are inside a `#loading` body. The header ends with the prefix of\n * their IDs, such as `5.`, and the gaps count the numbers after it.\n */\nexport const ITEM_SLOT = 1;\nexport const ITEM = 2;\nexport const CHILDREN = 4;\nexport const OWNER = 8;\nexport const MODULE = 16;\nexport const SOURCE = 32;\nexport const PREFIX = 64;\n\n/**\n * The page state as the server writes it. Records of scopes that share their\n * kind, their parent or owner, and their shape are in one group of `g`,\n * such as the items of a list, instead of one object each. A group is a flat\n * array: `[kind, base, flags, slotCount, module?, source?, sourceSlot?, prefix?, ...scopes]`, and each scope\n * is its ID as the gap from the one before it (the first from `base`), its\n * slots, and then its item and its child components, as `flags` says.\n */\nexport type PackedState = PageState & { g?: unknown[][] };\n","const DRAFT = Symbol('brumate.draft');\n\ninterface DraftState {\n base: Record<PropertyKey, unknown>;\n /** A shallow copy, made on the first change. */\n copy: Record<PropertyKey, unknown> | undefined;\n parent: DraftState | undefined;\n /** Drafts of the objects inside, by key. */\n children: Map<PropertyKey, DraftState & { proxy: object }>;\n modified: boolean;\n}\n\n/** Plain objects and arrays can be drafted. Other values, such as `Map`, are used as they are. */\nfunction isDraftable(value: unknown): value is Record<PropertyKey, unknown> {\n if (typeof value !== 'object' || value === null) {\n return false;\n }\n if (Array.isArray(value)) {\n return true;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction latest(state: DraftState): Record<PropertyKey, unknown> {\n return state.copy ?? state.base;\n}\n\n/** Copies an object and its parents on the first change. */\nfunction prepare(state: DraftState): Record<PropertyKey, unknown> {\n for (\n let current: DraftState | undefined = state;\n current && !current.modified;\n current = current.parent\n ) {\n current.modified = true;\n current.copy = (\n Array.isArray(current.base) ? [...current.base] : { ...current.base }\n ) as Record<PropertyKey, unknown>;\n }\n return state.copy!;\n}\n\nfunction stateOf(value: unknown): DraftState | undefined {\n return typeof value === 'object' && value !== null\n ? ((value as Record<PropertyKey, unknown>)[DRAFT] as DraftState | undefined)\n : undefined;\n}\n\nfunction createDraft(\n base: Record<PropertyKey, unknown>,\n parent: DraftState | undefined,\n): DraftState & { proxy: object } {\n const state = {\n base,\n copy: undefined,\n parent,\n children: new Map(),\n modified: false,\n } as DraftState & {\n proxy: object;\n };\n // An empty target, so the draft can report the keys of the copy.\n const target = Array.isArray(base) ? [] : Object.create(Object.getPrototypeOf(base));\n state.proxy = new Proxy(target, {\n get(_, key) {\n if (key === DRAFT) {\n return state;\n }\n const source = latest(state);\n const value = source[key];\n if (!Object.hasOwn(source, key) || !isDraftable(value) || value !== state.base[key]) {\n return value;\n }\n let child = state.children.get(key);\n if (!child) {\n child = createDraft(value, state);\n state.children.set(key, child);\n }\n return child.proxy;\n },\n set(_, key, value) {\n const source = latest(state);\n if (Object.is(source[key], value) && Object.hasOwn(source, key)) {\n return true;\n }\n prepare(state)[key] = value;\n state.children.delete(key);\n return true;\n },\n deleteProperty(_, key) {\n if (Object.hasOwn(latest(state), key)) {\n delete prepare(state)[key];\n state.children.delete(key);\n }\n return true;\n },\n has(_, key) {\n return key in latest(state);\n },\n ownKeys() {\n return Reflect.ownKeys(latest(state));\n },\n getOwnPropertyDescriptor(_, key) {\n const descriptor = Reflect.getOwnPropertyDescriptor(latest(state), key);\n if (descriptor && key !== 'length') {\n descriptor.configurable = true;\n descriptor.writable = true;\n }\n return descriptor;\n },\n defineProperty(_, key, descriptor) {\n prepare(state);\n return Reflect.defineProperty(state.copy!, key, descriptor);\n },\n });\n return state;\n}\n\n/** Returns the final value of a draft: the base if nothing changed, or a new object that shares what did not. */\nfunction finalize(state: DraftState): unknown {\n if (!state.modified) {\n // A child can change without its parent being copied yet.\n for (const child of state.children.values()) {\n if (child.modified) {\n prepare(state);\n break;\n }\n }\n if (!state.modified) {\n return state.base;\n }\n }\n const copy = state.copy!;\n for (const [key, child] of state.children) {\n if (copy[key] === child.base) {\n copy[key] = finalize(child);\n }\n }\n // Drafts can also be assigned to other keys, such as when an array is reordered.\n for (const key of Reflect.ownKeys(copy)) {\n const draft = stateOf(copy[key]);\n if (draft) {\n copy[key] = finalize(draft);\n }\n }\n return copy;\n}\n\n/**\n * Returns a changed copy of a value. The recipe changes a draft as if it\n * were the value. Objects that it does not change keep their identity, and\n * if it changes nothing, the value itself is returned. A recipe can also\n * return a new value. Only plain objects and arrays are drafted.\n */\nexport function produce<T>(base: T, recipe: (draft: T) => T | void): T {\n if (!isDraftable(base)) {\n const result = recipe(base);\n return result === undefined ? base : result;\n }\n const state = createDraft(base, undefined);\n const result = recipe(state.proxy as T);\n if (result !== undefined && result !== state.proxy) {\n return resolve(result, new Set()) as T;\n }\n return finalize(state) as T;\n}\n\n/** Replaces the drafts in a value that a recipe returns, such as the result of `draft.filter(…)`. */\nfunction resolve(value: unknown, seen: Set<unknown>): unknown {\n const draft = stateOf(value);\n if (draft) {\n return finalize(draft);\n }\n if (!isDraftable(value) || seen.has(value)) {\n return value;\n }\n seen.add(value);\n for (const key of Reflect.ownKeys(value)) {\n value[key] = resolve(value[key], seen);\n }\n return value;\n}\n"],"mappings":";;;AAgBA,SAAgB,QAAQ,MAAuB;CAC7C,OAAO,UAAU,KAAK,IAAI,IAAI,OAAO,IAAI,IAAI;AAC/C;;AAYA,IAAa,mBAAb,MAA8B;CAC5B;CACA;CAEA,YAAY,OAAgB,QAAgB;EAC1C,KAAK,QAAQ;EACb,KAAK,SAAS;CAChB;AACF;;AAGA,IAAa,oBAAb,MAA+B;;CAE7B;CACA;CAEA,YAAY,KAAa,OAAgB;EACvC,KAAK,MAAM;EACX,KAAK,QAAQ;CACf;AACF;;;;;;AAUA,MAAa,cAaT;CACF,IAAI,OAAO,WAAW,IAAI,iBAAiB,OAAO,MAAM;CACxD,IAAI,KAAK,UAAU,IAAI,kBAAkB,KAAK,KAAK;CACnD,GAAG;CACH,IAAI,OAAO,OAAO,aAAa,IAAI,EAAE,WAAW,GAAG,CAAC;AACtD;;AAGA,SAAgB,gBAAgB,OAAiD;CAC/E,OACE,UAAU,QACV,OAAO,UAAU,YACjB,OAAQ,MAAiC,OAAO,mBAAmB;AAEvE;;;ACvFA,MAAM,QAAQ,OAAO,eAAe;;AAapC,SAAS,YAAY,OAAuD;CAC1E,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO;CAET,IAAI,MAAM,QAAQ,KAAK,GACrB,OAAO;CAET,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD;AAEA,SAAS,OAAO,OAAiD;CAC/D,OAAO,MAAM,QAAQ,MAAM;AAC7B;;AAGA,SAAS,QAAQ,OAAiD;CAChE,KACE,IAAI,UAAkC,OACtC,WAAW,CAAC,QAAQ,UACpB,UAAU,QAAQ,QAClB;EACA,QAAQ,WAAW;EACnB,QAAQ,OACN,MAAM,QAAQ,QAAQ,IAAI,IAAI,CAAC,GAAG,QAAQ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B;CAC5D,MAAM,QAAQ,QAAQ,KAAK;CAC3B,IAAI,OACF,OAAO,SAAS,KAAK;CAEvB,IAAI,CAAC,YAAY,KAAK,KAAK,KAAK,IAAI,KAAK,GACvC,OAAO;CAET,KAAK,IAAI,KAAK;CACd,KAAK,MAAM,OAAO,QAAQ,QAAQ,KAAK,GACrC,MAAM,OAAO,QAAQ,MAAM,MAAM,IAAI;CAEvC,OAAO;AACT"}
@@ -1,29 +1,41 @@
1
1
  //#region src/runtime/shared.d.ts
2
+ /**
3
+ * The ID of a scope or of a `#loading` boundary. The rest of the page numbers
4
+ * its scopes from the base of the render, such as `3`. A `#loading` body
5
+ * numbers its own from 0 after the ID of its boundary and a dot, such as
6
+ * `5.0` and `5.1`, so its IDs do not depend on when its data arrives.
7
+ */
8
+ type ScopeId = number | string;
2
9
  /** An element that the server rendered. The client finds it by its anchor. */
3
10
  declare class ElementReference {
4
- readonly scope: number;
11
+ readonly scope: ScopeId;
5
12
  readonly anchor: number;
6
- constructor(scope: number, anchor: number);
13
+ constructor(scope: ScopeId, anchor: number);
7
14
  }
8
15
  /** A client function: an export of a client module, and the scope it reads. */
9
16
  declare class FunctionReference {
10
17
  /** `<component id>#<export name>`. */
11
18
  readonly ref: string;
12
- readonly scope: number;
13
- constructor(ref: string, scope: number);
19
+ readonly scope: ScopeId;
20
+ constructor(ref: string, scope: ScopeId);
14
21
  }
15
22
  /** The state of one scope in the page. */
16
23
  interface ScopeState {
17
24
  /** The scope's ID in the compiled component. */
18
25
  k?: number;
19
26
  /** The ID of the scope that contains this one. Component root scopes have none. */
20
- p?: number;
27
+ p?: ScopeId;
21
28
  /** The component ID of a component's root scope. */
22
29
  m?: string;
23
30
  /** The item of a list item scope. */
24
31
  i?: unknown;
25
32
  /** The scope that rendered a component's root scope, for finding contexts. */
26
- o?: number;
33
+ o?: ScopeId;
34
+ /**
35
+ * For a scope of children that a component inserted, the scope where they
36
+ * are, which contexts are found from in place of `p` and `o`.
37
+ */
38
+ t?: ScopeId;
27
39
  /** The values that the scope provides, by context key. */
28
40
  v?: Record<string, unknown>;
29
41
  /** The slots that hold the contexts that the scope reads, by context key. */
@@ -31,15 +43,15 @@ interface ScopeState {
31
43
  /** Slot values, in the order of the scope's layout. */
32
44
  s?: unknown[];
33
45
  /** The scope IDs of child components, by anchor index. */
34
- c?: Record<number, number>;
46
+ c?: Record<number, ScopeId>;
35
47
  }
36
48
  /** The state of a page, by scope ID. */
37
- type PageState = Record<number, ScopeState>;
49
+ type PageState = Record<ScopeId, ScopeState>;
38
50
  /**
39
51
  * The page state as the server writes it. Records of scopes that share their
40
52
  * kind, their parent or owner, and their shape are in one group of `g`,
41
53
  * 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
54
+ * array: `[kind, base, flags, slotCount, module?, source?, sourceSlot?, prefix?, ...scopes]`, and each scope
43
55
  * is its ID as the gap from the one before it (the first from `base`), its
44
56
  * slots, and then its item and its child components, as `flags` says.
45
57
  */
@@ -56,5 +68,5 @@ type PackedState = PageState & {
56
68
  */
57
69
  declare function produce<T>(base: T, recipe: (draft: T) => T | void): T;
58
70
  //#endregion
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
71
+ export { PageState as a, PackedState as i, ElementReference as n, ScopeId as o, FunctionReference as r, ScopeState as s, produce as t };
72
+ //# sourceMappingURL=produce-D4K7qpaL.d.ts.map
@@ -0,0 +1,38 @@
1
+ //#region src/runtime/routes.d.ts
2
+ /**
3
+ * The paths of the routes, with their params, such as
4
+ * `'/todos/[id]': { id: string }`. The Vite plugin adds them.
5
+ */
6
+ interface Routes {}
7
+ /** A route path, such as `/todos/[id]`. Any string while no routes are declared. */
8
+ type RoutePath = [keyof Routes] extends [never] ? string : keyof Routes & string;
9
+ /** The params of a route path, such as `{ id: string }` for `/todos/[id]`. */
10
+ type RouteParams<P extends RoutePath> = P extends keyof Routes ? Routes[P] : Record<string, string>;
11
+ /** The arguments after the path: none for a path without params. */
12
+ type ParamsArgument<P extends RoutePath> = [keyof RouteParams<P>] extends [never] ? [params?: RouteParams<P>] : [params: RouteParams<P>];
13
+ /**
14
+ * The URL of a route, with its params in place:
15
+ * `href('/todos/[id]', { id: '3' })` is `/todos/3`. A rest param, such as
16
+ * `[...path]`, keeps its slashes.
17
+ */
18
+ declare function href<P extends RoutePath>(path: P, ...[params]: ParamsArgument<P>): string;
19
+ interface NavigateOptions {
20
+ /** Replaces the current entry of the history instead of adding one. */
21
+ replace?: boolean;
22
+ /** Scrolls to the top of the new page, or to its hash. Defaults to true. False keeps the place. */
23
+ scroll?: boolean;
24
+ }
25
+ /**
26
+ * Loads a page as a link does: the layouts that stay keep their state. It
27
+ * returns when the page shows. A URL of another origin, or a page without
28
+ * the loader, loads in full.
29
+ *
30
+ * ```ts
31
+ * await navigate(href('/issues/[id]', { id: issue.id }));
32
+ * navigate(`?q=${query}`, { replace: true });
33
+ * ```
34
+ */
35
+ declare function navigate(to: string, options?: NavigateOptions): Promise<void>;
36
+ //#endregion
37
+ export { href as a, Routes as i, RouteParams as n, navigate as o, RoutePath as r, NavigateOptions as t };
38
+ //# sourceMappingURL=routes-BZNt7DSZ.d.ts.map