brumate 0.7.2 → 0.8.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 (90) hide show
  1. package/dist/{boot-CMy0f_iC.d.ts → boot-DQuAhAd5.d.ts} +2 -2
  2. package/dist/cli.js +3 -2
  3. package/dist/cli.js.map +1 -1
  4. package/dist/{client-DnFF9_lv.d.ts → client-4eabQtYJ.d.ts} +38 -12
  5. package/dist/{client-COm1iA6w.js → client-CwVcmymi.js} +145 -28
  6. package/dist/client-CwVcmymi.js.map +1 -0
  7. package/dist/{defer-Cesb-k2Q.js → defer-BaXWydb0.js} +2 -2
  8. package/dist/{defer-Cesb-k2Q.js.map → defer-BaXWydb0.js.map} +1 -1
  9. package/dist/{devtools-C9IEkgc1.js → devtools-CMuj12yR.js} +257 -118
  10. package/dist/devtools-CMuj12yR.js.map +1 -0
  11. package/dist/devtools-calls-DGW6nLZ2.js +249 -0
  12. package/dist/devtools-calls-DGW6nLZ2.js.map +1 -0
  13. package/dist/devtools-panel-Cq8LpsyW.js +3978 -0
  14. package/dist/devtools-panel-Cq8LpsyW.js.map +1 -0
  15. package/dist/error-catalog-DakxjSgj.js +308 -0
  16. package/dist/error-catalog-DakxjSgj.js.map +1 -0
  17. package/dist/error-catalog-VxLbz-6p.js +1 -0
  18. package/dist/{files-BuQvpBwF.js → files-DXS8RAtZ.js} +2 -2
  19. package/dist/{files-BuQvpBwF.js.map → files-DXS8RAtZ.js.map} +1 -1
  20. package/dist/index.d.ts +73 -18
  21. package/dist/index.js +11 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/{inspect-BSHv1_25.js → inspect-B5AoHh5O.js} +639 -412
  24. package/dist/inspect-B5AoHh5O.js.map +1 -0
  25. package/dist/{loader-CLKrJMqw.js → loader-CTeT6ie9.js} +4 -4
  26. package/dist/{loader-CLKrJMqw.js.map → loader-CTeT6ie9.js.map} +1 -1
  27. package/dist/{navigate-OHb0Uw1P.js → navigate-Bj73X4ZS.js} +22 -8
  28. package/dist/navigate-Bj73X4ZS.js.map +1 -0
  29. package/dist/{rpc-BAKbRWOT.js → rpc-kVB0Ujdx.js} +5 -4
  30. package/dist/rpc-kVB0Ujdx.js.map +1 -0
  31. package/dist/runtime/bundles.d.ts +3 -2
  32. package/dist/runtime/bundles.js +14 -3
  33. package/dist/runtime/bundles.js.map +1 -1
  34. package/dist/runtime/client.d.ts +2 -2
  35. package/dist/runtime/client.js +4 -3
  36. package/dist/runtime/devtools.d.ts +59 -1
  37. package/dist/runtime/devtools.js +1 -1
  38. package/dist/runtime/hot.d.ts +1 -1
  39. package/dist/runtime/hot.js +6 -2
  40. package/dist/runtime/hot.js.map +1 -1
  41. package/dist/runtime/loader.d.ts +2 -2
  42. package/dist/runtime/loader.js +2 -2
  43. package/dist/runtime/server.d.ts +1 -1
  44. package/dist/runtime/server.js +3 -2
  45. package/dist/runtime/signals.d.ts +1 -1
  46. package/dist/runtime/static-loader.d.ts +2 -2
  47. package/dist/runtime/static-loader.js +1 -1
  48. package/dist/runtime/store.d.ts +2 -2
  49. package/dist/runtime/store.js +1 -1
  50. package/dist/runtime/testing.d.ts +2 -2
  51. package/dist/runtime/testing.js +2 -2
  52. package/dist/search-params-Wg-0FsMj.js +148 -0
  53. package/dist/search-params-Wg-0FsMj.js.map +1 -0
  54. package/dist/{stream-RXLadXx1.js → serial-ioa17MuY.js} +67 -168
  55. package/dist/serial-ioa17MuY.js.map +1 -0
  56. package/dist/serial-ribg9NAj.js +1 -0
  57. package/dist/{server-BVObWh-w.js → server-BUuf7XPZ.js} +61 -16
  58. package/dist/server-BUuf7XPZ.js.map +1 -0
  59. package/dist/{server-0rS5vUW1.d.ts → server-DesBZv5g.d.ts} +8 -3
  60. package/dist/{search-params-C64liRBj.js → shared-CX_YacDm.js} +3 -148
  61. package/dist/shared-CX_YacDm.js.map +1 -0
  62. package/dist/{signals-DBnq9QRW.d.ts → signals-7VVD9C_H.d.ts} +2 -2
  63. package/dist/{static-loader-CxANokZ4.js → static-loader-BM0-wdIc.js} +2 -2
  64. package/dist/{static-loader-CxANokZ4.js.map → static-loader-BM0-wdIc.js.map} +1 -1
  65. package/dist/{static-loader-BYbXVJDY.d.ts → static-loader-BSAyFqG0.d.ts} +2 -2
  66. package/dist/{store-xlTzAM_r.d.ts → store-9_oa0HG1.d.ts} +15 -2
  67. package/dist/{store-BIBAYZo-.js → store-Cy4EEyZ7.js} +148 -2
  68. package/dist/store-Cy4EEyZ7.js.map +1 -0
  69. package/dist/stream-read-BTsYstJY.js +22 -0
  70. package/dist/stream-read-BTsYstJY.js.map +1 -0
  71. package/dist/stream-read-Dek3HnqO.js +1 -0
  72. package/dist/vite.d.ts +1 -1
  73. package/dist/vite.js +37 -5
  74. package/dist/vite.js.map +1 -1
  75. package/package.json +7 -4
  76. package/skills/brumate/SKILL.md +6 -2
  77. package/skills/brumate/references/errors.md +21 -2
  78. package/skills/brumate/references/state.md +31 -0
  79. package/skills/brumate/references/syntax.md +45 -1
  80. package/dist/client-COm1iA6w.js.map +0 -1
  81. package/dist/devtools-C9IEkgc1.js.map +0 -1
  82. package/dist/devtools-panel-Doit__YG.js +0 -2018
  83. package/dist/devtools-panel-Doit__YG.js.map +0 -1
  84. package/dist/inspect-BSHv1_25.js.map +0 -1
  85. package/dist/navigate-OHb0Uw1P.js.map +0 -1
  86. package/dist/rpc-BAKbRWOT.js.map +0 -1
  87. package/dist/search-params-C64liRBj.js.map +0 -1
  88. package/dist/server-BVObWh-w.js.map +0 -1
  89. package/dist/store-BIBAYZo-.js.map +0 -1
  90. package/dist/stream-RXLadXx1.js.map +0 -1
@@ -1,6 +1,6 @@
1
1
  import { m as HAS_SEARCH_PARAMS } from "./features-DwMYKBIC.js";
2
2
  import { n as ROUTE_KEY, t as NAVIGATION_KEY } from "./context-CU4Fpn5a.js";
3
- import { n as boot, r as importCore } from "./static-loader-CxANokZ4.js";
3
+ import { n as boot, r as importCore } from "./static-loader-BM0-wdIc.js";
4
4
  //#region src/runtime/loader.ts
5
5
  /**
6
6
  * Starts resuming the page. Listens to the events in `b-on` attributes
@@ -12,7 +12,7 @@ function start(options) {
12
12
  }
13
13
  /** Starts loading the page of a link, unless the link asks not to. */
14
14
  function prefetch(link) {
15
- if (link && link.getAttribute("data-prefetch") !== "none") import("./navigate-OHb0Uw1P.js").then((module) => module.prefetch(link.href));
15
+ if (link && link.getAttribute("data-prefetch") !== "none") import("./navigate-Bj73X4ZS.js").then((module) => module.prefetch(link.href));
16
16
  }
17
17
  /**
18
18
  * Imports the code with which the core reads the pages that navigation adds.
@@ -64,7 +64,7 @@ function navigation({ options, listen, core, start: startCore, scan }) {
64
64
  document.documentElement.removeAttribute("data-navigating");
65
65
  state({ pending: false });
66
66
  }
67
- return import("./navigate-OHb0Uw1P.js").then((module) => module.navigate({
67
+ return import("./navigate-Bj73X4ZS.js").then((module) => module.navigate({
68
68
  url,
69
69
  init,
70
70
  push,
@@ -148,4 +148,4 @@ function navigation({ options, listen, core, start: startCore, scan }) {
148
148
  //#endregion
149
149
  export { start as t };
150
150
 
151
- //# sourceMappingURL=loader-CLKrJMqw.js.map
151
+ //# sourceMappingURL=loader-CTeT6ie9.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"loader-CLKrJMqw.js","names":[],"sources":["../src/runtime/loader.ts"],"sourcesContent":["import type * as Routes from './client-routes.ts';\nimport { boot, importCore } from './boot.ts';\nimport { NAVIGATION_KEY, ROUTE_KEY } from './context.ts';\nimport { HAS_SEARCH_PARAMS } from './features.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 && link.getAttribute('data-prefetch') !== '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 */\nfunction routes(): (typeof Routes)['ready'] {\n return import('./client-routes.ts').then((module) => module.ready);\n}\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 function reader(key: string): Promise<Core> | undefined {\n const running = core();\n if (running) {\n return running;\n }\n for (const script of document.querySelectorAll('script[b-state]')) {\n if (script.textContent?.includes(key)) {\n return startCore();\n }\n }\n return undefined;\n }\n function state(value: { pending: boolean; from?: string; to?: string }): void {\n void reader(NAVIGATION_KEY)?.then((client) => client.setGlobal(NAVIGATION_KEY, value));\n }\n function 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 function 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 // The core took the serial entry when it started.\n void core()?.then((client) =>\n client.init({ ...options, serial: undefined, listen: scan }),\n );\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 function 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 // The query string moved by `$searchParam` stays on the page, so the next change is told from it.\n if (HAS_SEARCH_PARAMS) {\n listen(document, 'brumate:search', () => {\n page = location.href.split('#')[0]!;\n });\n }\n listen(window, 'popstate', () => {\n // A change of the hash only stays on the page.\n const target = location.href.split('#')[0]!;\n if (target !== page) {\n // `$searchParam` follows the history itself when only its parameters changed.\n const follow = HAS_SEARCH_PARAMS\n ? (globalThis as Record<symbol, ((from: string) => boolean) | undefined>)[\n Symbol.for('brumate.search')\n ]\n : undefined;\n if (follow?.(page)) {\n page = target;\n } else {\n void go(location.href, undefined, false);\n }\n }\n });\n return () =>\n Promise.all([importCore(), document.querySelector('[b-offset],[b-roots]') && routes()]).then(\n ([client]) => client,\n );\n}\n"],"mappings":";;;;;;;;;AAcA,SAAgB,MAAM,SAAoC;CACxD,OAAO,KAAK,SAAS,QAAQ,aAAa,QAAQ,KAAA,IAAY,UAAU;AAC1E;;AAGA,SAAS,SAAS,MAA2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xC,IAAI,WAAW,MAAM;GAOnB,KALe,oBACV,WACC,OAAO,IAAI,gBAAgB,KAE7B,KAAA,EAAA,GACS,IAAI,GACf,OAAO;QAEP,GAAQ,SAAS,MAAM,KAAA,GAAW,KAAK;EAE3C;CACF,CAAC;CACD,aACE,QAAQ,IAAI,CAAC,WAAW,GAAG,SAAS,cAAc,sBAAsB,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,MACrF,CAAC,YAAY,MAChB;AACJ"}
1
+ {"version":3,"file":"loader-CTeT6ie9.js","names":[],"sources":["../src/runtime/loader.ts"],"sourcesContent":["import type * as Routes from './client-routes.ts';\nimport { boot, importCore } from './boot.ts';\nimport { NAVIGATION_KEY, ROUTE_KEY } from './context.ts';\nimport { HAS_SEARCH_PARAMS } from './features.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 && link.getAttribute('data-prefetch') !== '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 */\nfunction routes(): (typeof Routes)['ready'] {\n return import('./client-routes.ts').then((module) => module.ready);\n}\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 function reader(key: string): Promise<Core> | undefined {\n const running = core();\n if (running) {\n return running;\n }\n for (const script of document.querySelectorAll('script[b-state]')) {\n if (script.textContent?.includes(key)) {\n return startCore();\n }\n }\n return undefined;\n }\n function state(value: { pending: boolean; from?: string; to?: string }): void {\n void reader(NAVIGATION_KEY)?.then((client) => client.setGlobal(NAVIGATION_KEY, value));\n }\n function 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 function 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 // The core took the serial entry when it started.\n void core()?.then((client) =>\n client.init({ ...options, serial: undefined, listen: scan }),\n );\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 function 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 // The query string moved by `$searchParam` stays on the page, so the next change is told from it.\n if (HAS_SEARCH_PARAMS) {\n listen(document, 'brumate:search', () => {\n page = location.href.split('#')[0]!;\n });\n }\n listen(window, 'popstate', () => {\n // A change of the hash only stays on the page.\n const target = location.href.split('#')[0]!;\n if (target !== page) {\n // `$searchParam` follows the history itself when only its parameters changed.\n const follow = HAS_SEARCH_PARAMS\n ? (globalThis as Record<symbol, ((from: string) => boolean) | undefined>)[\n Symbol.for('brumate.search')\n ]\n : undefined;\n if (follow?.(page)) {\n page = target;\n } else {\n void go(location.href, undefined, false);\n }\n }\n });\n return () =>\n Promise.all([importCore(), document.querySelector('[b-offset],[b-roots]') && routes()]).then(\n ([client]) => client,\n );\n}\n"],"mappings":";;;;;;;;;AAcA,SAAgB,MAAM,SAAoC;CACxD,OAAO,KAAK,SAAS,QAAQ,aAAa,QAAQ,KAAA,IAAY,UAAU;AAC1E;;AAGA,SAAS,SAAS,MAA2C;CAC3D,IAAI,QAAQ,KAAK,aAAa,eAAe,MAAM,QACjD,OAAY,yBAAgB,CAAC,MAAM,WAAW,OAAO,SAAS,KAAK,IAAI,CAAC;AAE5E;;;;;;;AAQA,SAAS,SAAmC;CAC1C,OAAO,OAAO,8BAAqB,CAAC,MAAM,WAAW,OAAO,KAAK;AACnE;;;;;;;AAQA,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,CAAC,CAAC,MAAM,GAAG,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aAAa,YAAY,KAAK,KAAK,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;CAEzF,IAAI,mBACF,OAAO,UAAU,wBAAwB;EACvC,OAAO,SAAS,KAAK,MAAM,GAAG,CAAC,CAAC;CAClC,CAAC;CAEH,OAAO,QAAQ,kBAAkB;EAE/B,MAAM,SAAS,SAAS,KAAK,MAAM,GAAG,CAAC,CAAC;EACxC,IAAI,WAAW,MAAM;GAOnB,KALe,oBACV,WACC,OAAO,IAAI,gBAAgB,KAE7B,KAAA,EAAA,GACS,IAAI,GACf,OAAO;QAEP,GAAQ,SAAS,MAAM,KAAA,GAAW,KAAK;EAE3C;CACF,CAAC;CACD,aACE,QAAQ,IAAI,CAAC,WAAW,GAAG,SAAS,cAAc,sBAAsB,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,MACrF,CAAC,YAAY,MAChB;AACJ"}
@@ -241,7 +241,7 @@ function shiftIds(root, shift) {
241
241
  }
242
242
  for (const name of IDS) {
243
243
  const value = element.getAttribute(name);
244
- if (value) element.setAttribute(name, add(value));
244
+ if (value) element.setAttribute(name, value.split(" ").map(add).join(" "));
245
245
  }
246
246
  const on = element.getAttribute("b-on");
247
247
  if (on?.includes("@")) {
@@ -318,16 +318,29 @@ function append(nodes, shift) {
318
318
  for (const script of scripts) if (!script.src && (!script.type || script.type === "text/javascript" || script.type === "module")) script.replaceWith(runnable(script));
319
319
  }
320
320
  }
321
- /** Makes the head of the page match the new one, keeping elements that are in both. */
321
+ /**
322
+ * The HTML of a head element, which says whether the new page has the same one. The nonce is left
323
+ * out: each response has its own, and the browser hides the one of the loaded page.
324
+ */
325
+ function headHTML(element) {
326
+ return element.outerHTML.replace(/^(<[^>]*?) nonce="[^"]*"/, "$1");
327
+ }
328
+ /**
329
+ * Makes the head of the page match the new one, keeping elements that are in both.
330
+ * Returns the scripts that ask to run again, which the caller adds once the body is in place.
331
+ */
322
332
  function updateHead(next) {
333
+ const rerun = [];
323
334
  const keep = /* @__PURE__ */ new Map();
324
- for (const element of document.head.children) keep.set(element.outerHTML, element);
335
+ for (const element of document.head.children) keep.set(headHTML(element), element);
325
336
  for (const element of [...next.head.children]) {
326
- const html = element.outerHTML;
327
- if (keep.has(html)) keep.delete(html);
337
+ const html = headHTML(element);
338
+ if (element.matches("script[data-rerun]")) rerun.push(element);
339
+ else if (keep.has(html)) keep.delete(html);
328
340
  else document.head.append(document.adoptNode(element));
329
341
  }
330
- for (const element of keep.values()) if (!(element.tagName === "SCRIPT" && element.src) && !element.hasAttribute("b-bundle")) element.remove();
342
+ for (const element of keep.values()) if (element.matches("script[data-rerun]") || !(element.tagName === "SCRIPT" && element.src) && !element.hasAttribute("b-bundle")) element.remove();
343
+ return rerun;
331
344
  }
332
345
  function scroll(url, saved) {
333
346
  if (saved !== void 0) {
@@ -521,7 +534,7 @@ async function navigate(visit) {
521
534
  for (const attribute of next.documentElement.attributes) root.setAttribute(attribute.name, attribute.value);
522
535
  const title = next.title;
523
536
  const announced = next.head.querySelector("meta[name=\"brumate-announce\"]")?.getAttribute("content") || title || next.body.querySelector("h1")?.textContent || "";
524
- updateHead(next);
537
+ const rerun = updateHead(next);
525
538
  document.title = title;
526
539
  const same = url.href === location.href;
527
540
  const samePath = url.pathname === location.pathname;
@@ -535,6 +548,7 @@ async function navigate(visit) {
535
548
  }
536
549
  if (visit.push && !same) history.pushState({}, "", url);
537
550
  else if (!same) history.replaceState(history.state, "", url);
551
+ for (const script of rerun) document.head.append(runnable(script));
538
552
  visit.enter();
539
553
  if (visit.scroll === false || (visit.init || visit.reload) && same) window.scrollTo(0, top);
540
554
  else scroll(url, visit.push ? void 0 : history.state?.scroll);
@@ -588,4 +602,4 @@ function failPending() {
588
602
  //#endregion
589
603
  export { navigate, prefetch };
590
604
 
591
- //# sourceMappingURL=navigate-OHb0Uw1P.js.map
605
+ //# sourceMappingURL=navigate-Bj73X4ZS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"navigate-Bj73X4ZS.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 { trustedHTML, 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 let type = 'traverse';\n if (visit.init || visit.reload) {\n type = 'form';\n } else if (visit.push) {\n type = 'push';\n }\n const types = [type];\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 let before: Region | undefined;\n for (const item of old) {\n if (item.name === region.name) {\n before = item;\n break;\n }\n }\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 `b-c-<hash>`.\n const attribute = `b-c-${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 (!result || result.replace.length === 0) {\n return undefined;\n }\n for (const [before, region] of result.replace) {\n if (!complete(before) || !complete(region)) {\n return undefined;\n }\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 const dropped: string[] = [];\n const roots: string[] = [];\n for (const [before, region] of result.replace) {\n dropped.push(before.root);\n roots.push(region.root);\n }\n const aliases: string[] = [];\n for (const [from, to] of result.alias) {\n aliases.push(`${from}:${to}`);\n }\n state.setAttribute('b-drop', dropped.join(','));\n state.setAttribute('b-roots', roots.join(','));\n state.setAttribute('b-alias', aliases.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: Element[] = [];\n for (const node of added) {\n if (node.nodeType === 1) {\n elements.push(node as Element);\n }\n }\n // An added element that is an `<h1>` wins over one that holds an `<h1>`.\n let heading: Element | null | undefined;\n for (const element of elements) {\n if (element.matches('h1')) {\n heading = element;\n break;\n }\n }\n if (!heading) {\n for (const element of elements) {\n heading = element.querySelector('h1');\n if (heading) {\n break;\n }\n }\n }\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 function 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 function 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 // `b-v` can list several IDs.\n element.setAttribute(name, value.split(' ').map(add).join(' '));\n }\n }\n // A handler that a spread passed on names the scope of its owner after `@`, such as\n // `change=Switch#h4@5.0` or `click=App#h2@5@%5B1%5D` with the arguments of `$handler`.\n const on = element.getAttribute('b-on');\n if (on?.includes('@')) {\n const entries: string[] = [];\n for (const entry of on.split(' ')) {\n const [ref, scope, ...args] = entry.split('@');\n entries.push(scope === undefined ? entry : [ref, add(scope), ...args].join('@'));\n }\n element.setAttribute('b-on', entries.join(' '));\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 readNonce(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 = readNonce(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 = readNonce(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/**\n * The HTML of a head element, which says whether the new page has the same one. The nonce is left\n * out: each response has its own, and the browser hides the one of the loaded page.\n */\nfunction headHTML(element: Element): string {\n return element.outerHTML.replace(/^(<[^>]*?) nonce=\"[^\"]*\"/, '$1');\n}\n\n/**\n * Makes the head of the page match the new one, keeping elements that are in both.\n * Returns the scripts that ask to run again, which the caller adds once the body is in place.\n */\nfunction updateHead(next: Document): HTMLScriptElement[] {\n const rerun: HTMLScriptElement[] = [];\n const keep = new Map<string, Element>();\n for (const element of document.head.children) {\n keep.set(headHTML(element), 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 = headHTML(element);\n if (element.matches('script[data-rerun]')) {\n // Never kept: the old copy leaves and a new one runs after the body.\n rerun.push(element as HTMLScriptElement);\n } else 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, and so do the stylesheets\n // of the bundles that the loader added, whose code stays too.\n if (\n element.matches('script[data-rerun]') ||\n (!(element.tagName === 'SCRIPT' && (element as HTMLScriptElement).src) &&\n !element.hasAttribute('b-bundle'))\n ) {\n element.remove();\n }\n }\n return rerun;\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\n/** What the devtools learn of a navigation. See `DevtoolsHooks.navigated`. */\nexport interface NavigationReport {\n url: string;\n /** `push` for a link, `traverse` for the back and forward buttons, `form` for a form or a reload. */\n kind: 'push' | 'traverse' | 'form';\n /** The routes that stayed, by their keys, when only some routes were replaced. */\n kept: string[];\n /** The slots whose route was replaced, with the keys of the old and the new route. */\n replaced: { slot: string; from: string; to: string }[];\n /** True when the whole page was replaced. */\n full: boolean;\n /** How much the IDs of the new page moved, when they did not start where this page asked. */\n shift?: number;\n /** When the navigation started, and how long it took until the page changed. */\n start: number;\n time: number;\n}\n\n/** True on the dev server, which has the devtools. A build leaves the report out. */\nconst DEV = (import.meta as { env?: { DEV?: boolean } }).env?.DEV;\n\n/** Tells the devtools what a navigation kept and replaced. */\nfunction report(\n visit: Visit,\n start: number,\n routes: Plan | undefined,\n shift: Shift | undefined,\n): void {\n const hooks = (globalThis as Record<symbol, { navigated?: (report: NavigationReport) => void }>)[\n Symbol.for('brumate.devtools')\n ];\n if (!hooks?.navigated) {\n return;\n }\n // The slots that were replaced, by their start comment, since each walk of the page makes new regions.\n const replaced = new Set<Comment>();\n for (const [before] of routes?.replace ?? []) {\n replaced.add(before.start);\n }\n // The routes of the page before, without those that were replaced or are inside one. The root\n // layout is outside every slot.\n const kept: string[] = [];\n function walk(list: Region[]): void {\n for (const region of list) {\n if (!replaced.has(region.start)) {\n kept.push(region.key);\n walk(region.children);\n }\n }\n }\n if (routes) {\n const scripts = document.querySelectorAll(`${STATE}[b-route]`);\n const root = scripts[scripts.length - 1]?.getAttribute('b-route');\n if (root) {\n kept.push(root);\n }\n walk(regions(document.body));\n }\n let kind: NavigationReport['kind'] = 'traverse';\n if (visit.init || visit.reload) {\n kind = 'form';\n } else if (visit.push) {\n kind = 'push';\n }\n const swaps: { slot: string; from: string; to: string }[] = [];\n for (const [before, after] of routes?.replace ?? []) {\n swaps.push({ slot: after.name, from: before.key, to: after.key });\n }\n hooks.navigated({\n url: visit.url,\n kind,\n kept,\n replaced: swaps,\n full: !routes,\n shift: shift?.by,\n start,\n time: performance.now() - start,\n });\n}\n\nexport async function navigate(visit: Visit): Promise<void> {\n const started = performance.now();\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 function stop(): void {\n reader.cancel().catch(() => {});\n }\n // The next chunk, or nothing once a later navigation started.\n async function read(): 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(trustedHTML(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 // The head holds markup of the page too, such as a `<title>` of `#head` with its anchor.\n shiftIds(next.head, 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 if (DEV) {\n report(visit, started, routes, shift);\n }\n await visit.leave(routes !== undefined);\n if (current.signal.aborted) {\n stop();\n return;\n }\n await transition(visit, () => {\n // Only the attributes that a server page sent change. `b-html` names those of this page.\n const root = document.documentElement;\n for (const name of [...(root.getAttribute('b-html') ?? '').split(' '), 'b-html']) {\n if (name && !next.documentElement.hasAttribute(name)) {\n root.removeAttribute(name);\n }\n }\n for (const attribute of next.documentElement.attributes) {\n root.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 const rerun = 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 // Scripts that ask to run again read the new body and the new URL.\n for (const script of rerun) {\n document.head.append(runnable(script));\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(trustedHTML('<!doctype html><body>'));\n let rest = text.slice(end);\n for (;;) {\n if (rest) {\n sink.write(trustedHTML(rest));\n append([...sink.body.childNodes].slice(0, -1), shift);\n }\n let chunk: ReadableStreamReadResult<string> | undefined;\n try {\n // oxlint-disable-next-line no-await-in-loop -- Chunks arrive in order.\n chunk = await read();\n } catch (error) {\n // The connection failed, so the bodies that are still missing will not come.\n failPending();\n throw error;\n }\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 failPending();\n}\n\n/**\n * Called when the stream of a page ends. A `#loading` boundary that still shows its fallback\n * lost its body, such as when the connection dropped. The page gets a `brumate:error` event for\n * each, and the fallback stays.\n */\nfunction failPending(): void {\n const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_COMMENT);\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n const id = /^l([\\d.]+)$/.exec((node as Comment).data)?.[1];\n // The body of a `#defer` block waits for its trigger. A body that failed on the server was\n // reported by its `b-fail` record.\n if (\n id !== undefined &&\n !(node.previousSibling as Element | null)?.hasAttribute?.('b-defer') &&\n !document.querySelector(`script[b-fail=\"${id}\"]`)\n ) {\n const error = new Error('The page stopped loading before this part arrived');\n window.dispatchEvent(new CustomEvent('brumate:error', { detail: { error } }));\n console.error(error);\n }\n }\n}\n"],"mappings":";;;;;;;;AA0CA,eAAe,WAAW,OAAc,QAAmC;CACzE,IAAI,CAAC,MAAM,cAAc,OAAO,SAAS,wBAAwB,YAAY;EAC3E,OAAO;EACP;CACF;CACA,IAAI,OAAO;CACX,IAAI,MAAM,QAAQ,MAAM,QACtB,OAAO;MACF,IAAI,MAAM,MACf,OAAO;CAET,MAAM,QAAQ,CAAC,IAAI;CAMnB,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,MAAM;IACZ,KAAK,mBAAmB,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,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,YAAY,uBAAuB,CAAC;CAC/C,IAAI,OAAO,KAAK,MAAM,GAAG;CACzB,SAAS;EACP,IAAI,MAAM;GACR,KAAK,MAAM,YAAY,IAAI,CAAC;GAC5B,OAAO,CAAC,GAAG,KAAK,KAAK,UAAU,CAAC,CAAC,MAAM,GAAG,EAAE,GAAG,KAAK;EACtD;EACA,IAAI;EACJ,IAAI;GAEF,QAAQ,MAAM,KAAK;EACrB,SAAS,OAAO;GAEd,YAAY;GACZ,MAAM;EACR;EACA,IAAI,CAAC,OACH;EAEF,IAAI,MAAM,MACR;EAEF,OAAO,MAAM;CACf;CACA,KAAK,MAAM;CACX,OAAO,CAAC,GAAG,KAAK,KAAK,UAAU,GAAG,KAAK;CACvC,YAAY;AACd;;;;;;AAOA,SAAS,cAAoB;CAC3B,MAAM,SAAS,SAAS,iBAAiB,SAAS,MAAM,WAAW,YAAY;CAC/E,KAAK,IAAI,OAAO,OAAO,SAAS,GAAG,MAAM,OAAO,OAAO,SAAS,GAAG;EACjE,MAAM,KAAK,cAAc,KAAM,KAAiB,IAAI,CAAC,GAAG;EAGxD,IACE,OAAO,KAAA,KACP,CAAE,KAAK,iBAAoC,eAAe,SAAS,KACnE,CAAC,SAAS,cAAc,kBAAkB,GAAG,GAAG,GAChD;GACA,MAAM,wBAAQ,IAAI,MAAM,mDAAmD;GAC3E,OAAO,cAAc,IAAI,YAAY,iBAAiB,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;GAC5E,QAAQ,MAAM,KAAK;EACrB;CACF;AACF"}
@@ -1,6 +1,7 @@
1
- import { a as callPlugins, n as fromChunkStream, s as serialOptions } from "./stream-RXLadXx1.js";
2
- import { hn as build, yn as skew } from "./client-COm1iA6w.js";
3
- import { toJSONAsync } from "seroval";
1
+ import { a as serialOptions, n as callPlugins } from "./serial-ioa17MuY.js";
2
+ import { n as fromChunkStream } from "./stream-read-BTsYstJY.js";
3
+ import { Sn as skew, vn as build } from "./client-CwVcmymi.js";
4
+ import { toJSONAsync } from "seroval/write";
4
5
  //#region src/runtime/rpc.ts
5
6
  /**
6
7
  * Calls a server function. It is a separate module, so pages that never call
@@ -146,4 +147,4 @@ function sendAction(form, submitter) {
146
147
  //#endregion
147
148
  export { call, sendAction };
148
149
 
149
- //# sourceMappingURL=rpc-BAKbRWOT.js.map
150
+ //# sourceMappingURL=rpc-kVB0Ujdx.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpc-kVB0Ujdx.js","names":[],"sources":["../src/runtime/rpc.ts"],"sourcesContent":["import { toJSONAsync } from 'seroval/write';\nimport { build, skew } from './client.ts';\nimport type { Scope } from './client.ts';\nimport { callPlugins, serialOptions } from './serial.ts';\nimport { fromChunkStream } from './stream-read.ts';\n\n/**\n * Calls a server function. It is a separate module, so pages that never call\n * one never load seroval's serializer.\n *\n * Files and blobs in the arguments, anywhere in them, go as parts of\n * multipart form data. `signal` aborts the call.\n */\nexport async function call(\n prefix: string,\n id: string,\n args: unknown[],\n signal?: AbortSignal,\n): Promise<unknown> {\n // The plugin of uploads takes each file and blob in the arguments, wherever it is.\n const files: Blob[] = [];\n const json = JSON.stringify(\n await toJSONAsync(args, { plugins: callPlugins(files), ...serialOptions() }),\n );\n let init: RequestInit;\n if (files.length > 0) {\n const form = new FormData();\n form.set('args', json);\n // A blob of another DOM is copied, because form data takes only its own.\n const copies: (Blob | Promise<Blob>)[] = [];\n for (const file of files) {\n // Typed as a Blob, so the check narrows a blob of another DOM to never.\n copies.push(\n file instanceof Blob\n ? file\n : (file as Blob)\n .arrayBuffer()\n .then((data) => new Blob([data], { type: (file as Blob).type })),\n );\n }\n const blobs = await Promise.all(copies);\n for (const [index, blob] of blobs.entries()) {\n form.set(`file${index}`, blob, (files[index] as Partial<File>).name ?? 'blob');\n }\n init = { headers: { 'x-brumate-args': 'form' }, body: form };\n } else {\n init = { headers: { 'content-type': 'application/json' }, body: json };\n }\n return post(prefix, id, { ...init, signal });\n}\n\n/**\n * Sends a form to a server function, and returns its result. The form data\n * goes as it is, files included, as when the browser posts the form.\n */\nexport async function submit(\n prefix: string,\n id: string,\n form: FormData,\n key?: string | null,\n): Promise<unknown> {\n return post(prefix, id, { headers: { 'x-brumate-result': '1' }, body: form }, key);\n}\n\n/** Posts to a server function, and reads its answer. */\nasync function post(\n prefix: string,\n id: string,\n init: RequestInit,\n key?: string | null,\n): Promise<unknown> {\n const headers = new Headers(init.headers);\n // The build of the page, so the server can tell a call from before a deploy.\n if (build !== undefined) {\n headers.set('x-brumate-build', build);\n }\n // The key of a form of a function that `idempotent` made.\n const query = key ? `?__key=${encodeURIComponent(key)}` : '';\n return answer(\n id,\n await fetch(`${prefix}/${encodeURIComponent(id)}${query}`, {\n ...init,\n headers,\n method: 'POST',\n }),\n );\n}\n\n/** Reads the answer of a server function: its result, a redirect or an error. */\nasync function answer(id: string, response: Response): Promise<unknown> {\n // The server functions whose memos load again, from `refresh` on the server.\n const refreshed = response.headers.get('x-brumate-refresh');\n if (refreshed) {\n const ids = refreshed.split(',');\n void refreshMemos(ids);\n document.dispatchEvent(new CustomEvent('brumate:refresh', { detail: ids }));\n }\n const location = response.headers.get('x-brumate-redirect');\n if (location !== null) {\n // The loader navigates on the client when it can. Without client navigation, the page loads in full.\n const redirect = new CustomEvent('brumate:redirect', { detail: location, cancelable: true });\n if (document.dispatchEvent(redirect)) {\n window.location.assign(location);\n }\n // The page is leaving, so the call never settles.\n return new Promise(() => {});\n }\n if (!response.ok) {\n // The site changed, and this page is from before. The next page loads in full.\n if (response.status === 409 && response.headers.get('x-brumate-build')) {\n skew('call');\n }\n let message = `Server function \"${id}\" failed with status ${response.status}`;\n try {\n message = ((await response.json()) as { error: string }).error;\n } catch {\n // The body is not the error of a server function.\n }\n const retryAfter = Number(response.headers.get('retry-after'));\n throw Object.assign(new Error(message), {\n name: 'ServerError',\n status: response.status,\n // The seconds to wait, for a call that a rate limit refused.\n ...(retryAfter > 0 ? { retryAfter } : {}),\n });\n }\n // Promises and async iterables in the result settle as the rest of the answer arrives.\n return fromChunkStream(response.body!);\n}\n\n// The code below reads the core with `import()`, not a static import: a module that imports\n// the core statically would make the package build move the core into a chunk of its own, behind\n// a module that only re-exports it, which a page loads one after the other. The core is loaded\n// already when it runs, so the import costs no request. It names the exports it uses, so a build\n// keeps only them.\n\n/**\n * Loads again the memos that call these server functions, after a server\n * function named them with `refresh`. Each component on the page knows its\n * own memos, from its client module. It is here, and not in the core, because\n * only the answer of a server call starts it.\n */\nexport function refreshMemos(ids: string[]): Promise<void> {\n return import('./client.ts').then(({ descendants, loadModule, scopes }) => {\n for (const root of scopes.values()) {\n if (!root.m) {\n continue;\n }\n void loadModule(root.m).then(async (module) => {\n const entries: NonNullable<typeof module.refresh>[string] = [];\n for (const id of ids) {\n entries.push(...(module.refresh?.[id] ?? []));\n }\n if (entries.length === 0) {\n return;\n }\n const updates = module as unknown as Record<string, unknown>;\n for (const [kind, name] of entries) {\n for (const target of kind === root.k ? [root] : descendants(root, kind)) {\n if (scopes.has(target.id)) {\n (updates[name] as (scope: Scope) => void)(target);\n }\n }\n }\n });\n }\n });\n}\n\n/** Gives a form a new key in its URL, for its next post. */\nfunction renewKey(form: HTMLFormElement, url: URL): void {\n url.searchParams.set('__key', crypto.randomUUID());\n form.setAttribute('action', `${url.pathname}${url.search}`);\n}\n\n/**\n * Sends a form to the server function of its `$action`, and writes the\n * result into the `$action` when it arrives. It is pending until then. See\n * `submitAction` in the core.\n */\nexport function sendAction(form: HTMLFormElement, submitter: HTMLElement | null): Promise<void> {\n const [scopeText, slotText] = form.getAttribute('b-result')!.split(':') as [string, string];\n const scopeId = Number(scopeText);\n const slot = Number(slotText);\n const data = new FormData(form, submitter);\n const action = form.getAttribute('b-action')!;\n return import('./client.ts').then(({ asyncMemo, rpcPrefix, scopes, track }) => {\n const scope = scopes.get(scopeId);\n if (scope) {\n // A form of a function that `idempotent` made sends its key, and gets a new one once the\n // server answered, so a post that the user means again runs again.\n const url = new URL(form.getAttribute('action') ?? '', location.href);\n const key = url.searchParams.get('__key');\n const result = submit(rpcPrefix, action, data, key);\n if (key) {\n void result.then(\n () => renewKey(form, url),\n () => {},\n );\n }\n const answered = result.catch((error: unknown) => {\n // The site changed since the page loaded. The form posts again without scripts, and the\n // page that answers is of the new build.\n if ((error as { status?: number }).status === 409 && build !== undefined) {\n form.submit();\n return new Promise(() => {});\n }\n throw error;\n });\n asyncMemo(scope, slot, track(answered));\n }\n });\n}\n"],"mappings":";;;;;;;;;;;;AAaA,eAAsB,KACpB,QACA,IACA,MACA,QACkB;CAElB,MAAM,QAAgB,CAAC;CACvB,MAAM,OAAO,KAAK,UAChB,MAAM,YAAY,MAAM;EAAE,SAAS,YAAY,KAAK;EAAG,GAAG,cAAc;CAAE,CAAC,CAC7E;CACA,IAAI;CACJ,IAAI,MAAM,SAAS,GAAG;EACpB,MAAM,OAAO,IAAI,SAAS;EAC1B,KAAK,IAAI,QAAQ,IAAI;EAErB,MAAM,SAAmC,CAAC;EAC1C,KAAK,MAAM,QAAQ,OAEjB,OAAO,KACL,gBAAgB,OACZ,OACC,KACE,YAAY,CAAC,CACb,MAAM,SAAS,IAAI,KAAK,CAAC,IAAI,GAAG,EAAE,MAAO,KAAc,KAAK,CAAC,CAAC,CACvE;EAEF,MAAM,QAAQ,MAAM,QAAQ,IAAI,MAAM;EACtC,KAAK,MAAM,CAAC,OAAO,SAAS,MAAM,QAAQ,GACxC,KAAK,IAAI,OAAO,SAAS,MAAO,MAAM,MAAM,CAAmB,QAAQ,MAAM;EAE/E,OAAO;GAAE,SAAS,EAAE,kBAAkB,OAAO;GAAG,MAAM;EAAK;CAC7D,OACE,OAAO;EAAE,SAAS,EAAE,gBAAgB,mBAAmB;EAAG,MAAM;CAAK;CAEvE,OAAO,KAAK,QAA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AO,OAAO,sBAAc,CAAC,MAAM,EAAE,WAAW,WAAW,QAAQ,YAAY;EAC7E,MAAM,QAAQ,OAAO,IAAI,OAAO;EAChC,IAAI,OAAO;GAGT,MAAM,MAAM,IAAI,IAAI,KAAK,aAAa,QAAQ,KAAK,IAAI,SAAS,IAAI;GACpE,MAAM,MAAM,IAAI,aAAa,IAAI,OAAO;GACxC,MAAM,SAAS,OAAO,WAAW,QAAQ,MAAM,GAAG;GAClD,IAAI,KACF,OAAY,WACJ,SAAS,MAAM,GAAG,SAClB,CAAC,CACT;GAEF,MAAM,WAAW,OAAO,OAAO,UAAmB;IAGhD,IAAK,MAA8B,WAAW,OAAO,UAAU,KAAA,GAAW;KACxE,KAAK,OAAO;KACZ,OAAO,IAAI,cAAc,CAAC,CAAC;IAC7B;IACA,MAAM;GACR,CAAC;GACD,UAAU,OAAO,MAAM,MAAM,QAAQ,CAAC;EACxC;CACF,CAAC;AACH"}
@@ -1,8 +1,9 @@
1
- import { qt as ClientModule } from "../client-DnFF9_lv.js";
1
+ import { Yt as ClientModule } from "../client-4eabQtYJ.js";
2
2
  //#region src/runtime/bundles.d.ts
3
3
  /**
4
4
  * The client module of a component, from the bundles that the state records of the page name.
5
- * Undefined for a component with no client code.
5
+ * Undefined for a component with no client code. Rejects when a bundle failed to load and the
6
+ * component is not in the others.
6
7
  */
7
8
  export declare function load(id: string): Promise<ClientModule> | undefined;
8
9
  //#endregion
@@ -4,6 +4,8 @@ import { i as HAS_BRIDGES } from "../features-DwMYKBIC.js";
4
4
  const loaded = /* @__PURE__ */ new Map();
5
5
  /** The bundles that load or loaded, by URL. */
6
6
  const pending = /* @__PURE__ */ new Map();
7
+ /** Why the bundles that failed to load failed, by URL, until a load of them lands. */
8
+ const failed = /* @__PURE__ */ new Map();
7
9
  /** The state records whose `b-load` was read. */
8
10
  const read = /* @__PURE__ */ new WeakSet();
9
11
  /**
@@ -29,10 +31,14 @@ function loadBundle(url, nonce) {
29
31
  /* @vite-ignore */
30
32
  href
31
33
  ).then((bundle) => {
34
+ failed.delete(url);
32
35
  for (const [id, module] of Object.entries(bundle.modules)) loaded.set(id, module);
33
36
  });
34
37
  pending.set(url, promise);
35
- promise.catch(() => pending.delete(url));
38
+ promise.catch((error) => {
39
+ pending.delete(url);
40
+ failed.set(url, error);
41
+ });
36
42
  }
37
43
  return promise;
38
44
  }
@@ -47,14 +53,19 @@ readRecords();
47
53
  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", readRecords);
48
54
  /**
49
55
  * The client module of a component, from the bundles that the state records of the page name.
50
- * Undefined for a component with no client code.
56
+ * Undefined for a component with no client code. Rejects when a bundle failed to load and the
57
+ * component is not in the others.
51
58
  */
52
59
  function load(id) {
53
60
  if (HAS_BRIDGES && id.startsWith("bridge:")) id = id.slice(7);
54
61
  if (loaded.has(id)) return Promise.resolve(loaded.get(id));
55
62
  readRecords();
56
63
  const waiting = [...pending.values()];
57
- return waiting.length > 0 ? Promise.allSettled(waiting).then(() => loaded.get(id)) : void 0;
64
+ if (waiting.length === 0 && failed.size === 0) return;
65
+ return Promise.allSettled(waiting).then(() => {
66
+ if (!loaded.has(id)) for (const error of failed.values()) throw error;
67
+ return loaded.get(id);
68
+ });
58
69
  }
59
70
  //#endregion
60
71
  export { load };
@@ -1 +1 @@
1
- {"version":3,"file":"bundles.js","names":[],"sources":["../../src/runtime/bundles.ts"],"sourcesContent":["// The `load` of a build, which `virtual:brumate/manifest` exports. The server names the bundles\n// that a page needs in the `b-load` attribute of its state records, so the client entry holds\n// no table of the bundles of the app.\n\nimport type { ClientModule } from './client.ts';\nimport { HAS_BRIDGES } from './features.ts';\n\n/** The client modules of the bundles that loaded, by component ID. */\nconst loaded = new Map<string, ClientModule>();\n/** The bundles that load or loaded, by URL. */\nconst pending = new Map<string, Promise<void>>();\n/** The state records whose `b-load` was read. */\nconst read = new WeakSet<Element>();\n\n/**\n * Loads a URL that a state record names: a bundle, with the client modules of the components\n * that it holds, or a stylesheet that a module of a bundle imports. A URL is relative to this\n * chunk, as the server writes it for a base of \"./\".\n */\nfunction loadBundle(url: string, nonce: string | null): Promise<void> | undefined {\n const href = new URL(url, import.meta.url).href;\n // A stylesheet goes in the head unless the page has it, such as from the head of the page.\n if (url.endsWith('.css')) {\n for (const link of document.querySelectorAll<HTMLLinkElement>('link[rel=stylesheet]')) {\n if (link.href === href) {\n return undefined;\n }\n }\n const link = document.createElement('link');\n link.rel = 'stylesheet';\n link.href = href;\n // The nonce of the record, for a policy on styles. A navigation keeps the link (`b-bundle`),\n // as it keeps the code of the bundle.\n if (nonce) {\n link.setAttribute('nonce', nonce);\n }\n link.setAttribute('b-bundle', '');\n document.head.append(link);\n return undefined;\n }\n let promise = pending.get(url);\n if (!promise) {\n promise = import(/* @vite-ignore */ href).then(\n (bundle: { modules: Record<string, ClientModule> }) => {\n for (const [id, module] of Object.entries(bundle.modules)) {\n loaded.set(id, module);\n }\n },\n );\n pending.set(url, promise);\n // A load that fails can start again, such as after the network comes back.\n promise.catch(() => pending.delete(url));\n }\n return promise;\n}\n\n/** Loads what the state records of the page that were not read yet name. */\nfunction readRecords(): void {\n for (const script of document.querySelectorAll('script[b-load]')) {\n if (!read.has(script)) {\n read.add(script);\n for (const url of script.getAttribute('b-load')!.split(' ')) {\n // Browsers hide the attribute once the page loads, and keep the property.\n const nonce = (script as HTMLScriptElement).nonce || script.getAttribute('nonce');\n void loadBundle(url, nonce)?.catch(() => {});\n }\n }\n }\n}\n\n// The bundles of the page start with the entry, so the code of the page comes in the same round\n// trip as the core. The rest of a page that the browser reads after an `async` entry comes later.\nreadRecords();\nif (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', readRecords);\n}\n\n/**\n * The client module of a component, from the bundles that the state records of the page name.\n * Undefined for a component with no client code.\n */\nexport function load(id: string): Promise<ClientModule> | undefined {\n // A bridge of `<script module>` is named by its component, which holds its code.\n if (HAS_BRIDGES && id.startsWith('bridge:')) {\n id = id.slice(7);\n }\n if (loaded.has(id)) {\n return Promise.resolve(loaded.get(id)!);\n }\n // The records that the page added since, such as those of a navigation or a `#defer` body.\n readRecords();\n const waiting = [...pending.values()];\n return waiting.length > 0 ? Promise.allSettled(waiting).then(() => loaded.get(id)!) : undefined;\n}\n"],"mappings":";;;AAQA,MAAM,yBAAS,IAAI,IAA0B;;AAE7C,MAAM,0BAAU,IAAI,IAA2B;;AAE/C,MAAM,uBAAO,IAAI,QAAiB;;;;;;AAOlC,SAAS,WAAW,KAAa,OAAiD;CAChF,MAAM,OAAO,IAAI,IAAI,KAAK,YAAY,GAAG,CAAC,CAAC;CAE3C,IAAI,IAAI,SAAS,MAAM,GAAG;EACxB,KAAK,MAAM,QAAQ,SAAS,iBAAkC,sBAAsB,GAClF,IAAI,KAAK,SAAS,MAChB;EAGJ,MAAM,OAAO,SAAS,cAAc,MAAM;EAC1C,KAAK,MAAM;EACX,KAAK,OAAO;EAGZ,IAAI,OACF,KAAK,aAAa,SAAS,KAAK;EAElC,KAAK,aAAa,YAAY,EAAE;EAChC,SAAS,KAAK,OAAO,IAAI;EACzB;CACF;CACA,IAAI,UAAU,QAAQ,IAAI,GAAG;CAC7B,IAAI,CAAC,SAAS;EACZ,UAAU;;GAA0B;CAAK,CAAC,MACvC,WAAsD;GACrD,KAAK,MAAM,CAAC,IAAI,WAAW,OAAO,QAAQ,OAAO,OAAO,GACtD,OAAO,IAAI,IAAI,MAAM;EAEzB,CACF;EACA,QAAQ,IAAI,KAAK,OAAO;EAExB,QAAQ,YAAY,QAAQ,OAAO,GAAG,CAAC;CACzC;CACA,OAAO;AACT;;AAGA,SAAS,cAAoB;CAC3B,KAAK,MAAM,UAAU,SAAS,iBAAiB,gBAAgB,GAC7D,IAAI,CAAC,KAAK,IAAI,MAAM,GAAG;EACrB,KAAK,IAAI,MAAM;EACf,KAAK,MAAM,OAAO,OAAO,aAAa,QAAQ,CAAC,CAAE,MAAM,GAAG,GAGxD,WAAgB,KADD,OAA6B,SAAS,OAAO,aAAa,OAAO,CACtD,CAAC,EAAE,YAAY,CAAC,CAAC;CAE/C;AAEJ;AAIA,YAAY;AACZ,IAAI,SAAS,eAAe,WAC1B,SAAS,iBAAiB,oBAAoB,WAAW;;;;;AAO3D,SAAgB,KAAK,IAA+C;CAElE,IAAI,eAAe,GAAG,WAAW,SAAS,GACxC,KAAK,GAAG,MAAM,CAAC;CAEjB,IAAI,OAAO,IAAI,EAAE,GACf,OAAO,QAAQ,QAAQ,OAAO,IAAI,EAAE,CAAE;CAGxC,YAAY;CACZ,MAAM,UAAU,CAAC,GAAG,QAAQ,OAAO,CAAC;CACpC,OAAO,QAAQ,SAAS,IAAI,QAAQ,WAAW,OAAO,CAAC,CAAC,WAAW,OAAO,IAAI,EAAE,CAAE,IAAI,KAAA;AACxF"}
1
+ {"version":3,"file":"bundles.js","names":[],"sources":["../../src/runtime/bundles.ts"],"sourcesContent":["// The `load` of a build, which `virtual:brumate/manifest` exports. The server names the bundles\n// that a page needs in the `b-load` attribute of its state records, so the client entry holds\n// no table of the bundles of the app.\n\nimport type { ClientModule } from './client.ts';\nimport { HAS_BRIDGES } from './features.ts';\n\n/** The client modules of the bundles that loaded, by component ID. */\nconst loaded = new Map<string, ClientModule>();\n/** The bundles that load or loaded, by URL. */\nconst pending = new Map<string, Promise<void>>();\n/** Why the bundles that failed to load failed, by URL, until a load of them lands. */\nconst failed = new Map<string, unknown>();\n/** The state records whose `b-load` was read. */\nconst read = new WeakSet<Element>();\n\n/**\n * Loads a URL that a state record names: a bundle, with the client modules of the components\n * that it holds, or a stylesheet that a module of a bundle imports. A URL is relative to this\n * chunk, as the server writes it for a base of \"./\".\n */\nfunction loadBundle(url: string, nonce: string | null): Promise<void> | undefined {\n const href = new URL(url, import.meta.url).href;\n // A stylesheet goes in the head unless the page has it, such as from the head of the page.\n if (url.endsWith('.css')) {\n for (const link of document.querySelectorAll<HTMLLinkElement>('link[rel=stylesheet]')) {\n if (link.href === href) {\n return undefined;\n }\n }\n const link = document.createElement('link');\n link.rel = 'stylesheet';\n link.href = href;\n // The nonce of the record, for a policy on styles. A navigation keeps the link (`b-bundle`),\n // as it keeps the code of the bundle.\n if (nonce) {\n link.setAttribute('nonce', nonce);\n }\n link.setAttribute('b-bundle', '');\n document.head.append(link);\n return undefined;\n }\n let promise = pending.get(url);\n if (!promise) {\n promise = import(/* @vite-ignore */ href).then(\n (bundle: { modules: Record<string, ClientModule> }) => {\n failed.delete(url);\n for (const [id, module] of Object.entries(bundle.modules)) {\n loaded.set(id, module);\n }\n },\n );\n pending.set(url, promise);\n // A load that fails starts again only when a new record names the URL.\n promise.catch((error: unknown) => {\n pending.delete(url);\n failed.set(url, error);\n });\n }\n return promise;\n}\n\n/** Loads what the state records of the page that were not read yet name. */\nfunction readRecords(): void {\n for (const script of document.querySelectorAll('script[b-load]')) {\n if (!read.has(script)) {\n read.add(script);\n for (const url of script.getAttribute('b-load')!.split(' ')) {\n // Browsers hide the attribute once the page loads, and keep the property.\n const nonce = (script as HTMLScriptElement).nonce || script.getAttribute('nonce');\n void loadBundle(url, nonce)?.catch(() => {});\n }\n }\n }\n}\n\n// The bundles of the page start with the entry, so the code of the page comes in the same round\n// trip as the core. The rest of a page that the browser reads after an `async` entry comes later.\nreadRecords();\nif (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', readRecords);\n}\n\n/**\n * The client module of a component, from the bundles that the state records of the page name.\n * Undefined for a component with no client code. Rejects when a bundle failed to load and the\n * component is not in the others.\n */\nexport function load(id: string): Promise<ClientModule> | undefined {\n // A bridge of `<script module>` is named by its component, which holds its code.\n if (HAS_BRIDGES && id.startsWith('bridge:')) {\n id = id.slice(7);\n }\n if (loaded.has(id)) {\n return Promise.resolve(loaded.get(id)!);\n }\n // The records that the page added since, such as those of a navigation or a `#defer` body.\n readRecords();\n const waiting = [...pending.values()];\n if (waiting.length === 0 && failed.size === 0) {\n return undefined;\n }\n return Promise.allSettled(waiting).then(() => {\n if (!loaded.has(id)) {\n // A bundle that failed may hold the code, so the caller gets the error, as it does for a\n // module that throws. After a deploy, a gone bundle takes the page to the skew reload.\n for (const error of failed.values()) {\n throw error;\n }\n }\n return loaded.get(id)!;\n });\n}\n"],"mappings":";;;AAQA,MAAM,yBAAS,IAAI,IAA0B;;AAE7C,MAAM,0BAAU,IAAI,IAA2B;;AAE/C,MAAM,yBAAS,IAAI,IAAqB;;AAExC,MAAM,uBAAO,IAAI,QAAiB;;;;;;AAOlC,SAAS,WAAW,KAAa,OAAiD;CAChF,MAAM,OAAO,IAAI,IAAI,KAAK,YAAY,GAAG,CAAC,CAAC;CAE3C,IAAI,IAAI,SAAS,MAAM,GAAG;EACxB,KAAK,MAAM,QAAQ,SAAS,iBAAkC,sBAAsB,GAClF,IAAI,KAAK,SAAS,MAChB;EAGJ,MAAM,OAAO,SAAS,cAAc,MAAM;EAC1C,KAAK,MAAM;EACX,KAAK,OAAO;EAGZ,IAAI,OACF,KAAK,aAAa,SAAS,KAAK;EAElC,KAAK,aAAa,YAAY,EAAE;EAChC,SAAS,KAAK,OAAO,IAAI;EACzB;CACF;CACA,IAAI,UAAU,QAAQ,IAAI,GAAG;CAC7B,IAAI,CAAC,SAAS;EACZ,UAAU;;GAA0B;CAAK,CAAC,MACvC,WAAsD;GACrD,OAAO,OAAO,GAAG;GACjB,KAAK,MAAM,CAAC,IAAI,WAAW,OAAO,QAAQ,OAAO,OAAO,GACtD,OAAO,IAAI,IAAI,MAAM;EAEzB,CACF;EACA,QAAQ,IAAI,KAAK,OAAO;EAExB,QAAQ,OAAO,UAAmB;GAChC,QAAQ,OAAO,GAAG;GAClB,OAAO,IAAI,KAAK,KAAK;EACvB,CAAC;CACH;CACA,OAAO;AACT;;AAGA,SAAS,cAAoB;CAC3B,KAAK,MAAM,UAAU,SAAS,iBAAiB,gBAAgB,GAC7D,IAAI,CAAC,KAAK,IAAI,MAAM,GAAG;EACrB,KAAK,IAAI,MAAM;EACf,KAAK,MAAM,OAAO,OAAO,aAAa,QAAQ,CAAC,CAAE,MAAM,GAAG,GAGxD,WAAgB,KADD,OAA6B,SAAS,OAAO,aAAa,OAAO,CACtD,CAAC,EAAE,YAAY,CAAC,CAAC;CAE/C;AAEJ;AAIA,YAAY;AACZ,IAAI,SAAS,eAAe,WAC1B,SAAS,iBAAiB,oBAAoB,WAAW;;;;;;AAQ3D,SAAgB,KAAK,IAA+C;CAElE,IAAI,eAAe,GAAG,WAAW,SAAS,GACxC,KAAK,GAAG,MAAM,CAAC;CAEjB,IAAI,OAAO,IAAI,EAAE,GACf,OAAO,QAAQ,QAAQ,OAAO,IAAI,EAAE,CAAE;CAGxC,YAAY;CACZ,MAAM,UAAU,CAAC,GAAG,QAAQ,OAAO,CAAC;CACpC,IAAI,QAAQ,WAAW,KAAK,OAAO,SAAS,GAC1C;CAEF,OAAO,QAAQ,WAAW,OAAO,CAAC,CAAC,WAAW;EAC5C,IAAI,CAAC,OAAO,IAAI,EAAE,GAGhB,KAAK,MAAM,SAAS,OAAO,OAAO,GAChC,MAAM;EAGV,OAAO,OAAO,IAAI,EAAE;CACtB,CAAC;AACH"}
@@ -1,5 +1,5 @@
1
1
  import { c as navigationContext, l as routeContext, o as createContext } from "../context-BNgBXVUQ.js";
2
2
  import { A as mergeAttributes, C as escape, D as internal, P as raw, _ as affix, d as unbind, j as onAttribute, m as Raw, s as SCOPE_IDS, u as gateValue, v as attribute, x as classAttribute, z as vars } from "../shared-CuJdWifz.js";
3
- import { $ as list, $t as hooks, A as nodes, At as leavePage, B as descendants, Bt as consumeContext, C as clone, Cn as rekey, Ct as wait, D as keepText, Dt as dispose, E as keep, Et as nameComment, F as setOn, Ft as handle, G as sink, Gt as toStore, H as makeId, Ht as provideValue, I as setSpread, It as handlerProp, J as addHead, Jt as CoreOptions, K as prop, Kt as updateRoute, L as template, Lt as rpc, M as setAttr, Mt as remount, N as setAttrText, Nt as removeRoot, O as listNodes, Ot as forget, P as setContent, Pt as action, Q as setVar, Qt as build, R as afterInsert, Rt as spread, S as branchNodes, Sn as offscreen, St as started, T as fillList, Tn as retag, Tt as loadModule, U as removeScope, Ut as setGlobal, V as getScope, Vt as consumeStore, W as setOwner, Wt as storeUpdate, X as addStyle, Xt as DevtoolsHooks, Y as addPortal, Yt as DEVTOOLS, Z as deferInBrowser, Zt as Scope, _ as updated, _n as templateCall, _t as fillSpread, a as cells, an as componentNodes, at as content, b as searchParam, bn as fill, bt as loading, c as get, cn as elementAt, ct as text, d as pending, dn as readMemo, dt as track, en as rpcPrefix, et as toList, f as resolve, fn as renderMemo, ft as after, g as update, gn as insert, gt as fillSettled, h as unreadMemo, hn as children, ht as fillAttrs, i as bindings, in as component, it as attrs, j as putText, jt as leaveRoutes, k as markBlock, kt as init, l as isBound, ln as foreignNodes, lt as writeText, m as timed, mn as setSlots, mt as countLoads, n as asyncMemo, nn as skew, nt as windowStart, o as effect, on as dynamic, ot as portalTo, p as set, pn as setItem, pt as attempt, q as spreadProps, qt as ClientModule, r as binding, rn as Component, rt as attr, s as gate, sn as dynamicNodes, st as restRef, t as loader, tn as scopes, tt as windowList, u as memo, un as place, ut as guess, v as title, vn as HiddenBody, vt as fillValue, w as fillBranch, wn as reset, wt as fail, x as appendText, xn as held, xt as reveal, y as paramEffect, yn as branch, yt as keepValue, z as createScope, zt as submitAction } from "../client-DnFF9_lv.js";
3
+ import { $ as setVar, $t as Scope, A as markBlock, At as forget, B as createScope, Bt as spread, C as branchNodes, Cn as fill, Ct as reveal, D as keep, Dn as reset, Dt as loadModule, E as fillList, En as rekey, Et as fail, F as setContent, Ft as removeRoot, G as setOwner, Gt as setGlobal, H as getScope, Ht as consumeContext, I as setOn, It as action, J as spreadProps, Jt as updateRoute, K as sink, Kt as storeUpdate, L as setSpread, Lt as handle, M as putText, Mt as leavePage, N as setAttr, Nt as leaveRoutes, O as keepText, On as retag, Ot as nameComment, P as setAttrText, Pt as remount, Q as deferInBrowser, Qt as DevtoolsHooks, R as template, Rt as handlerProp, S as appendText, Sn as branch, St as loading, T as fillBranch, Tn as offscreen, Tt as wait, U as makeId, Ut as consumeStore, V as descendants, Vt as submitAction, W as removeScope, Wt as provideValue, X as addPortal, Xt as CoreOptions, Y as addHead, Yt as ClientModule, Z as addStyle, Zt as DEVTOOLS, _ as update, _n as setSlots, _t as fillPend, a as cells, an as Component, at as attrs, b as paramEffect, bn as templateCall, bt as fillValue, c as get, cn as dynamic, ct as restRef, d as pend, dn as foreignNodes, dt as guess, en as build, et as list, f as pending, fn as memoNow, ft as track, g as unreadMemo, gn as setItem, gt as fillAttrs, h as timed, hn as renderMemo, ht as countLoads, i as bindings, in as skew, it as attr, j as nodes, jt as init, k as listNodes, kt as dispose, l as isBound, ln as dynamicNodes, lt as text, m as set, mn as readMemo, mt as attempt, n as asyncMemo, nn as rpcPrefix, nt as windowList, o as effect, on as component, ot as content, p as resolve, pn as place, pt as after, q as prop, qt as toStore, r as binding, rn as scopes, rt as windowStart, s as gate, sn as componentNodes, st as portalTo, t as loader, tn as hooks, tt as toList, u as memo, un as elementAt, ut as writeText, v as updated, vn as children, vt as fillSettled, w as clone, wn as held, wt as started, x as searchParam, xn as HiddenBody, xt as keepValue, y as title, yn as insert, yt as fillSpread, z as afterInsert, zt as rpc } from "../client-4eabQtYJ.js";
4
4
  import { t as produce } from "../produce-CLABZ8k2.js";
5
- export { type ClientModule, type Component, type CoreOptions, DEVTOOLS, type DevtoolsHooks, type HiddenBody, type Raw, type Scope, action, addHead, addPortal, addStyle, affix, after, afterInsert, appendText, asyncMemo, attempt, attr, attribute, attrs, binding, bindings, branch, branchNodes, build, cells, children, classAttribute, clone, component, componentNodes, consumeContext, consumeStore, content, countLoads, createContext, createScope, deferInBrowser, descendants, dispose, dynamic, dynamicNodes, effect, elementAt, escape, fail, fill, fillAttrs, fillBranch, fillList, fillSettled, fillSpread, fillValue, foreignNodes, forget, gate, gateValue, get, getScope, guess, handle, handlerProp, held, hooks, init, insert, internal, isBound, keep, keepText, keepValue, leavePage, leaveRoutes, list, listNodes, loadModule, loader, loading, makeId, markBlock, memo, mergeAttributes, nameComment, navigationContext, nodes, offscreen, onAttribute, paramEffect, pending, place, portalTo, produce, prop, provideValue, putText, raw, readMemo, rekey, remount, removeRoot, removeScope, renderMemo, reset, resolve, restRef, retag, reveal, routeContext, rpc, rpcPrefix, SCOPE_IDS as scopeIds, scopes, searchParam, set, setAttr, setAttrText, setContent, setGlobal, setItem, setOn, setOwner, setSlots, setSpread, setVar, sink, skew, spread, spreadProps, started, storeUpdate, submitAction, template, templateCall, text, timed, title, toList, toStore, track, unbind, unreadMemo, update, updateRoute, updated, vars, wait, windowList, windowStart, writeText };
5
+ export { type ClientModule, type Component, type CoreOptions, DEVTOOLS, type DevtoolsHooks, type HiddenBody, type Raw, type Scope, action, addHead, addPortal, addStyle, affix, after, afterInsert, appendText, asyncMemo, attempt, attr, attribute, attrs, binding, bindings, branch, branchNodes, build, cells, children, classAttribute, clone, component, componentNodes, consumeContext, consumeStore, content, countLoads, createContext, createScope, deferInBrowser, descendants, dispose, dynamic, dynamicNodes, effect, elementAt, escape, fail, fill, fillAttrs, fillBranch, fillList, fillPend, fillSettled, fillSpread, fillValue, foreignNodes, forget, gate, gateValue, get, getScope, guess, handle, handlerProp, held, hooks, init, insert, internal, isBound, keep, keepText, keepValue, leavePage, leaveRoutes, list, listNodes, loadModule, loader, loading, makeId, markBlock, memo, memoNow, mergeAttributes, nameComment, navigationContext, nodes, offscreen, onAttribute, paramEffect, pend, pending, place, portalTo, produce, prop, provideValue, putText, raw, readMemo, rekey, remount, removeRoot, removeScope, renderMemo, reset, resolve, restRef, retag, reveal, routeContext, rpc, rpcPrefix, SCOPE_IDS as scopeIds, scopes, searchParam, set, setAttr, setAttrText, setContent, setGlobal, setItem, setOn, setOwner, setSlots, setSpread, setVar, sink, skew, spread, spreadProps, started, storeUpdate, submitAction, template, templateCall, text, timed, title, toList, toStore, track, unbind, unreadMemo, update, updateRoute, updated, vars, wait, windowList, windowStart, writeText };
@@ -1,5 +1,6 @@
1
1
  import { E as vars, _ as mergeAttributes, a as attribute, c as classAttribute, i as affix, m as internal, u as escape, v as onAttribute, x as raw } from "../html-Cf5uKhLs.js";
2
- import { D as unbind, g as gateValue, i as produce, p as SCOPE_IDS } from "../search-params-C64liRBj.js";
2
+ import { C as unbind, f as gateValue, l as SCOPE_IDS } from "../shared-CX_YacDm.js";
3
+ import { i as produce } from "../search-params-Wg-0FsMj.js";
3
4
  import { a as navigationContext, o as routeContext, r as createContext } from "../context-CU4Fpn5a.js";
4
- import { $ as branchNodes, $t as fail, A as started, At as consumeContext, B as spreadProps, Bt as cells, C as fillAttrs, Ct as handle, D as keepValue, Dt as submitAction, E as fillValue, Et as spread, F as portalTo, Ft as toStore, G as elementAt, Gt as memo, H as componentNodes, Ht as gate, I as restRef, It as updateRoute, J as readMemo, Jt as set, K as foreignNodes, Kt as pending, L as text, Lt as asyncMemo, M as attr, Mt as provideValue, N as attrs, Nt as setGlobal, O as loading, Ot as guess, P as content, Pt as storeUpdate, Q as appendText, Qt as updated, R as writeText, Rt as binding, S as countLoads, St as action, T as fillSpread, Tt as rpc, U as dynamic, Ut as get, V as component, Vt as effect, W as dynamicNodes, Wt as isBound, X as setItem, Xt as unreadMemo, Y as renderMemo, Yt as timed, Z as setSlots, Zt as update, _ as rekey, _n as rpcPrefix, _t as init, a as addPortal, an as createScope, at as listNodes, b as after, bt as remount, c as setVar, cn as makeId, ct as putText, d as windowList, dn as sink, dt as setContent, en as children, et as clone, f as windowStart, fn as nameComment, ft as setOn, g as offscreen, gn as hooks, gt as forget, h as held, hn as build, ht as dispose, i as addHead, in as afterInsert, it as keepText, j as wait, jt as consumeStore, k as reveal, kt as track, l as list, ln as removeScope, lt as setAttr, m as fill, mn as DEVTOOLS, mt as template, n as paramEffect, nn as templateCall, nt as fillList, o as addStyle, on as descendants, ot as markBlock, p as branch, pn as loadModule, pt as setSpread, q as place, qt as resolve, r as searchParam, rn as title, rt as keep, s as deferInBrowser, sn as getScope, st as nodes, t as loader, tn as insert, tt as fillBranch, u as toList, un as setOwner, ut as setAttrText, v as reset, vn as scopes, vt as leavePage, w as fillSettled, wt as handlerProp, x as attempt, xt as removeRoot, y as retag, yn as skew, yt as leaveRoutes, z as prop, zt as bindings } from "../client-COm1iA6w.js";
5
- export { DEVTOOLS, action, addHead, addPortal, addStyle, affix, after, afterInsert, appendText, asyncMemo, attempt, attr, attribute, attrs, binding, bindings, branch, branchNodes, build, cells, children, classAttribute, clone, component, componentNodes, consumeContext, consumeStore, content, countLoads, createContext, createScope, deferInBrowser, descendants, dispose, dynamic, dynamicNodes, effect, elementAt, escape, fail, fill, fillAttrs, fillBranch, fillList, fillSettled, fillSpread, fillValue, foreignNodes, forget, gate, gateValue, get, getScope, guess, handle, handlerProp, held, hooks, init, insert, internal, isBound, keep, keepText, keepValue, leavePage, leaveRoutes, list, listNodes, loadModule, loader, loading, makeId, markBlock, memo, mergeAttributes, nameComment, navigationContext, nodes, offscreen, onAttribute, paramEffect, pending, place, portalTo, produce, prop, provideValue, putText, raw, readMemo, rekey, remount, removeRoot, removeScope, renderMemo, reset, resolve, restRef, retag, reveal, routeContext, rpc, rpcPrefix, SCOPE_IDS as scopeIds, scopes, searchParam, set, setAttr, setAttrText, setContent, setGlobal, setItem, setOn, setOwner, setSlots, setSpread, setVar, sink, skew, spread, spreadProps, started, storeUpdate, submitAction, template, templateCall, text, timed, title, toList, toStore, track, unbind, unreadMemo, update, updateRoute, updated, vars, wait, windowList, windowStart, writeText };
5
+ import { $ as setSlots, $t as unreadMemo, A as reveal, At as guess, B as prop, Bt as binding, C as fillAttrs, Ct as removeRoot, D as fillValue, Dt as rpc, E as fillSpread, Et as handlerProp, F as content, Ft as setGlobal, G as dynamicNodes, Gt as get, H as component, Ht as cells, I as portalTo, It as storeUpdate, J as memoNow, Jt as pend, K as elementAt, Kt as isBound, L as restRef, Lt as toStore, M as wait, Mt as consumeContext, N as attr, Nt as consumeStore, O as keepValue, Ot as spread, P as attrs, Pt as provideValue, Q as setItem, Qt as timed, R as text, Rt as updateRoute, S as countLoads, Sn as skew, St as remount, T as fillSettled, Tt as handle, U as componentNodes, Ut as effect, V as spreadProps, Vt as bindings, W as dynamic, Wt as gate, X as readMemo, Xt as resolve, Y as place, Yt as pending, Z as renderMemo, Zt as set, _ as rekey, _n as DEVTOOLS, _t as dispose, a as addPortal, an as templateCall, at as keep, b as after, bn as rpcPrefix, bt as leavePage, c as setVar, cn as createScope, ct as markBlock, d as windowList, dn as makeId, dt as setAttr, en as update, et as appendText, f as windowStart, fn as removeScope, ft as setAttrText, g as offscreen, gn as loadModule, gt as template, h as held, hn as nameComment, ht as setSpread, i as addHead, in as insert, it as fillList, j as started, jt as track, k as loading, kt as submitAction, l as list, ln as descendants, lt as nodes, m as fill, mn as sink, mt as setOn, n as paramEffect, nn as fail, nt as clone, o as addStyle, on as title, ot as keepText, p as branch, pn as setOwner, pt as setContent, q as foreignNodes, qt as memo, r as searchParam, rn as children, rt as fillBranch, s as deferInBrowser, sn as afterInsert, st as listNodes, t as loader, tn as updated, tt as branchNodes, u as toList, un as getScope, ut as putText, v as reset, vn as build, vt as forget, w as fillPend, wt as action, x as attempt, xn as scopes, xt as leaveRoutes, y as retag, yn as hooks, yt as init, z as writeText, zt as asyncMemo } from "../client-CwVcmymi.js";
6
+ export { DEVTOOLS, action, addHead, addPortal, addStyle, affix, after, afterInsert, appendText, asyncMemo, attempt, attr, attribute, attrs, binding, bindings, branch, branchNodes, build, cells, children, classAttribute, clone, component, componentNodes, consumeContext, consumeStore, content, countLoads, createContext, createScope, deferInBrowser, descendants, dispose, dynamic, dynamicNodes, effect, elementAt, escape, fail, fill, fillAttrs, fillBranch, fillList, fillPend, fillSettled, fillSpread, fillValue, foreignNodes, forget, gate, gateValue, get, getScope, guess, handle, handlerProp, held, hooks, init, insert, internal, isBound, keep, keepText, keepValue, leavePage, leaveRoutes, list, listNodes, loadModule, loader, loading, makeId, markBlock, memo, memoNow, mergeAttributes, nameComment, navigationContext, nodes, offscreen, onAttribute, paramEffect, pend, pending, place, portalTo, produce, prop, provideValue, putText, raw, readMemo, rekey, remount, removeRoot, removeScope, renderMemo, reset, resolve, restRef, retag, reveal, routeContext, rpc, rpcPrefix, SCOPE_IDS as scopeIds, scopes, searchParam, set, setAttr, setAttrText, setContent, setGlobal, setItem, setOn, setOwner, setSlots, setSpread, setVar, sink, skew, spread, spreadProps, started, storeUpdate, submitAction, template, templateCall, text, timed, title, toList, toStore, track, unbind, unreadMemo, update, updateRoute, updated, vars, wait, windowList, windowStart, writeText };
@@ -1,5 +1,5 @@
1
1
  import { c as ScopeId } from "../shared-CuJdWifz.js";
2
- import { En as NavigationReport, Zt as Scope } from "../client-DnFF9_lv.js";
2
+ import { $t as Scope, kn as NavigationReport } from "../client-4eabQtYJ.js";
3
3
  //#region src/runtime/logo.d.ts
4
4
  /**
5
5
  * The logo of brumate: the pole and the bowl of a b, in outline, where the
@@ -21,6 +21,8 @@ export interface DevtoolsEntry {
21
21
  k: number;
22
22
  slot: number;
23
23
  };
24
+ /** For a call: its timing and record, which the call detail of the dock shows. */
25
+ call?: CallTiming;
24
26
  }
25
27
  /** What the plugin tells the devtools about the dev server. */
26
28
  export interface DevtoolsMeta {
@@ -70,6 +72,62 @@ export interface CallTiming {
70
72
  status?: number | "redirect" | "failed";
71
73
  /** How long the function took on the server, from the `Server-Timing` of the dev server. */
72
74
  server?: number;
75
+ /** The arguments, the result and what ran on the server. It arrives after the answer. */
76
+ record?: CallRecord;
77
+ /** What was sent, so the dock can run the call again and write it as a `fetch`. Dev only. */
78
+ request?: {
79
+ url: string;
80
+ /** Only `content-type` and the `x-brumate-` headers, never cookies. */
81
+ headers: Record<string, string>;
82
+ body?: string | FormData;
83
+ };
84
+ }
85
+ /**
86
+ * What a server call needs for its detail, for the dock. The browser decodes the arguments and the
87
+ * result, and the dev server sends `server` and the stack in the `x-brumate-dev` header, so a
88
+ * production build has none of them. Values are cut at a length, and no cookies or headers are in it.
89
+ */
90
+ export interface CallRecord {
91
+ name: string;
92
+ /** The decoded arguments, cut. */
93
+ args: unknown[];
94
+ /** The decoded result, cut. Absent for an error or a redirect. */
95
+ result?: unknown;
96
+ /** The error that the server function threw, with the real message and the stack of the server. */
97
+ error?: {
98
+ message: string;
99
+ stack?: string;
100
+ };
101
+ /** Milliseconds: `module` before the request left, `network` there and back, `server` in the function, `decode` reading the answer. */
102
+ timing: {
103
+ module: number;
104
+ network: number;
105
+ server: number;
106
+ decode: number;
107
+ };
108
+ /** What ran on the server. Absent when the answer did not come from the dev server. */
109
+ server?: ServerRecord;
110
+ }
111
+ /** What ran on the server during a call. */
112
+ export interface ServerRecord {
113
+ /** The server functions whose memos the answer asked to load again (`refresh`). */
114
+ reads: string[];
115
+ /** The IDs of the server functions that the function called. */
116
+ calls: string[];
117
+ /** The `console.*` output of the call, in order. */
118
+ logs: {
119
+ level: string;
120
+ text: string;
121
+ }[];
122
+ /** True when logs were left out to fit the header. */
123
+ truncated?: boolean;
124
+ }
125
+ /** The content of the `x-brumate-dev` header of the dev server. */
126
+ export interface DevAnswer extends ServerRecord {
127
+ error?: {
128
+ message: string;
129
+ stack?: string;
130
+ };
73
131
  }
74
132
  /** A batch of updates that a write ran, with its effects. */
75
133
  export interface UpdateTiming {
@@ -1,3 +1,3 @@
1
+ import { a as preview, i as nextBlockState, n as installDevtools, o as reportError, r as moveBlock, s as scanBlocks, t as findRootScope } from "../devtools-CMuj12yR.js";
1
2
  import { t as LOGO } from "../logo-DQ_OYhBi.js";
2
- import { a as preview, i as nextBlockState, n as installDevtools, o as reportError, r as moveBlock, s as scanBlocks, t as findRootScope } from "../devtools-C9IEkgc1.js";
3
3
  export { LOGO, findRootScope, installDevtools, moveBlock, nextBlockState, preview, reportError, scanBlocks };
@@ -1,4 +1,4 @@
1
- import { qt as ClientModule } from "../client-DnFF9_lv.js";
1
+ import { Yt as ClientModule } from "../client-4eabQtYJ.js";
2
2
  //#region src/runtime/hot.d.ts
3
3
  /** What `brumate:update` holds for each component that changed. */
4
4
  export interface HotUpdate {
@@ -1,11 +1,13 @@
1
1
  //#region src/runtime/hot.ts
2
+ /** The loads that `hotLoad` returned. */
3
+ const hotLoads = /* @__PURE__ */ new WeakSet();
2
4
  /**
3
5
  * Listens for updates of components, and returns a `load` for the loader
4
6
  * that loads the new code of a component that changed. Pass
5
7
  * `import.meta.hot`, which only the module that reads it gets.
6
8
  */
7
9
  function hotLoad(hot, load) {
8
- if (!hot) return load;
10
+ if (!hot || hotLoads.has(load)) return load;
9
11
  const fresh = /* @__PURE__ */ new Map();
10
12
  hot.on("brumate:update", ({ updates, timestamp }) => {
11
13
  const changed = [];
@@ -33,13 +35,15 @@ function hotLoad(hot, load) {
33
35
  }
34
36
  });
35
37
  });
36
- return (id) => {
38
+ const wrapped = (id) => {
37
39
  const url = fresh.get(id);
38
40
  return url ? import(
39
41
  /* @vite-ignore */
40
42
  url
41
43
  ) : load(id);
42
44
  };
45
+ hotLoads.add(wrapped);
46
+ return wrapped;
43
47
  }
44
48
  //#endregion
45
49
  export { hotLoad };