brumate 0.0.1 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -72
- package/dist/boot-DN1ZU8Hg.d.ts +37 -0
- package/dist/cli.js +2 -2
- package/dist/{client-DuDTDePF.d.ts → client-DwJInP_a.d.ts} +133 -44
- package/dist/client-routes-DakuM32C.js +94 -0
- package/dist/client-routes-DakuM32C.js.map +1 -0
- package/dist/{cookies-rgIAc8IE.js → cookies-Av5WFmcf.js} +18 -8
- package/dist/cookies-Av5WFmcf.js.map +1 -0
- package/dist/{devtools-Bm8cS7hX.js → devtools-BKjnHrnv.js} +10 -5
- package/dist/devtools-BKjnHrnv.js.map +1 -0
- package/dist/{devtools-panel-CTbDSBBA.js → devtools-panel-AWOn0VK2.js} +23 -26
- package/dist/devtools-panel-AWOn0VK2.js.map +1 -0
- package/dist/{files-D_JUcSU5.js → files-DdT84mPy.js} +22 -3
- package/dist/{files-D_JUcSU5.js.map → files-DdT84mPy.js.map} +1 -1
- package/dist/{html-CxWpXngy.js → html-DEeoepg3.js} +47 -10
- package/dist/html-DEeoepg3.js.map +1 -0
- package/dist/{html-DV-Tezgq.d.ts → html-Du8jY2Cc.d.ts} +14 -2
- package/dist/index.d.ts +65 -6
- package/dist/index.js +20 -4
- package/dist/index.js.map +1 -1
- package/dist/{inspect-CGCWfaEx.js → inspect-BPchdWbU.js} +887 -172
- package/dist/inspect-BPchdWbU.js.map +1 -0
- package/dist/loader-Dc9OwY5I.js +101 -0
- package/dist/loader-Dc9OwY5I.js.map +1 -0
- package/dist/{navigate-C5dP89YL.js → navigate-CzLjnoPH.js} +112 -59
- package/dist/navigate-CzLjnoPH.js.map +1 -0
- package/dist/{produce-BjQGMpqL.d.ts → produce-CtZ32UGG.d.ts} +13 -3
- package/dist/{rpc-B86KKjzx.js → rpc-9fSqL_YK.js} +57 -12
- package/dist/rpc-9fSqL_YK.js.map +1 -0
- package/dist/runtime/client.d.ts +4 -4
- package/dist/runtime/client.js +599 -306
- package/dist/runtime/client.js.map +1 -1
- package/dist/runtime/devtools.d.ts +3 -1
- package/dist/runtime/devtools.js +1 -1
- package/dist/runtime/hot.d.ts +1 -1
- package/dist/runtime/hot.js +9 -5
- package/dist/runtime/hot.js.map +1 -1
- package/dist/runtime/html.d.ts +2 -2
- package/dist/runtime/html.js +1 -1
- package/dist/runtime/loader.d.ts +12 -2
- package/dist/runtime/loader.js +3 -1
- package/dist/runtime/server.d.ts +4 -4
- package/dist/runtime/server.js +5 -5
- package/dist/runtime/signals.d.ts +2 -2
- package/dist/runtime/signals.js +5 -5
- package/dist/runtime/signals.js.map +1 -1
- package/dist/runtime/static-loader.d.ts +3 -0
- package/dist/runtime/static-loader.js +1 -0
- package/dist/runtime/testing.d.ts +21 -2
- package/dist/runtime/testing.js +83 -7
- package/dist/runtime/testing.js.map +1 -1
- package/dist/{server-sQCvduOz.d.ts → server-BxqjLUnV.d.ts} +211 -20
- package/dist/{server-CX3JnPCs.js → server-DZsgnPKS.js} +595 -185
- package/dist/server-DZsgnPKS.js.map +1 -0
- package/dist/shared-CWYOd0H3.js +40 -0
- package/dist/shared-CWYOd0H3.js.map +1 -0
- package/dist/static-loader-BcFh4ebX.d.ts +11 -0
- package/dist/static-loader-ClNkHZGn.js +185 -0
- package/dist/static-loader-ClNkHZGn.js.map +1 -0
- package/dist/stream-bgNCMcaA.js +280 -0
- package/dist/stream-bgNCMcaA.js.map +1 -0
- package/dist/vite.d.ts +30 -5
- package/dist/vite.js +501 -62
- package/dist/vite.js.map +1 -1
- package/package.json +7 -2
- package/types.d.ts +5 -0
- package/dist/cookies-rgIAc8IE.js.map +0 -1
- package/dist/devtools-Bm8cS7hX.js.map +0 -1
- package/dist/devtools-panel-CTbDSBBA.js.map +0 -1
- package/dist/html-CxWpXngy.js.map +0 -1
- package/dist/inspect-CGCWfaEx.js.map +0 -1
- package/dist/loader-BUhNqDHw.d.ts +0 -30
- package/dist/loader-py4qu6tQ.js +0 -215
- package/dist/loader-py4qu6tQ.js.map +0 -1
- package/dist/navigate-C5dP89YL.js.map +0 -1
- package/dist/rpc-B86KKjzx.js.map +0 -1
- package/dist/server-CX3JnPCs.js.map +0 -1
- package/dist/shared-BE_oBSDM.js +0 -176
- package/dist/shared-BE_oBSDM.js.map +0 -1
- package/dist/stream-cvhqOzfs.js +0 -145
- package/dist/stream-cvhqOzfs.js.map +0 -1
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
import { t as ClientModule } from "./client-DuDTDePF.js";
|
|
2
|
-
//#region src/runtime/loader.d.ts
|
|
3
|
-
interface LoaderOptions {
|
|
4
|
-
/** Imports the client module of a component, by component ID. */
|
|
5
|
-
load: (id: string) => Promise<ClientModule>;
|
|
6
|
-
/** The URL prefix of server function calls. */
|
|
7
|
-
rpc?: string;
|
|
8
|
-
/**
|
|
9
|
-
* Loads pages without a full page load: links to the same origin, the back
|
|
10
|
-
* and forward buttons, and forms that post to a server function. Defaults to true.
|
|
11
|
-
*/
|
|
12
|
-
navigate?: boolean | NavigateOptions;
|
|
13
|
-
}
|
|
14
|
-
interface NavigateOptions {
|
|
15
|
-
/**
|
|
16
|
-
* Swaps the page inside a view transition, where the browser has them.
|
|
17
|
-
* CSS can tell links, the back and forward buttons and forms apart with
|
|
18
|
-
* the types `push`, `traverse` and `form`.
|
|
19
|
-
*/
|
|
20
|
-
transition?: boolean;
|
|
21
|
-
}
|
|
22
|
-
/**
|
|
23
|
-
* Starts resuming the page. Listens to the events in `data-on` attributes
|
|
24
|
-
* and loads `brumate/client` and the component's module on the first one.
|
|
25
|
-
* Returns a function that removes the listeners and stops the core.
|
|
26
|
-
*/
|
|
27
|
-
declare function start(options: LoaderOptions): () => void;
|
|
28
|
-
//#endregion
|
|
29
|
-
export { NavigateOptions as n, start as r, LoaderOptions as t };
|
|
30
|
-
//# sourceMappingURL=loader-BUhNqDHw.d.ts.map
|
package/dist/loader-py4qu6tQ.js
DELETED
|
@@ -1,215 +0,0 @@
|
|
|
1
|
-
//#region src/runtime/loader.ts
|
|
2
|
-
function entries(element) {
|
|
3
|
-
return (element.getAttribute("data-on") ?? "").split(" ").filter(Boolean).map((entry) => {
|
|
4
|
-
const [name, ref] = entry.split("=");
|
|
5
|
-
const [type, ...modifiers] = name.split(":");
|
|
6
|
-
return {
|
|
7
|
-
raw: entry,
|
|
8
|
-
type,
|
|
9
|
-
modifiers,
|
|
10
|
-
ref
|
|
11
|
-
};
|
|
12
|
-
});
|
|
13
|
-
}
|
|
14
|
-
function strategy(element) {
|
|
15
|
-
return element.getAttribute("data-prefetch") ?? "hover";
|
|
16
|
-
}
|
|
17
|
-
/** Starts loading the page of a link, unless the link asks not to. */
|
|
18
|
-
function prefetch(link) {
|
|
19
|
-
if (link && link.getAttribute("data-prefetch") !== "none") import("./navigate-C5dP89YL.js").then((module) => module.prefetch(link.href));
|
|
20
|
-
}
|
|
21
|
-
/**
|
|
22
|
-
* Starts resuming the page. Listens to the events in `data-on` attributes
|
|
23
|
-
* and loads `brumate/client` and the component's module on the first one.
|
|
24
|
-
* Returns a function that removes the listeners and stops the core.
|
|
25
|
-
*/
|
|
26
|
-
function start(options) {
|
|
27
|
-
let core;
|
|
28
|
-
const types = /* @__PURE__ */ new Set();
|
|
29
|
-
const removers = [];
|
|
30
|
-
const listen = (target, type, listener, flags) => {
|
|
31
|
-
target.addEventListener(type, listener, flags);
|
|
32
|
-
removers.push(() => target.removeEventListener(type, listener, flags));
|
|
33
|
-
};
|
|
34
|
-
const loadCore = () => core ??= import("./runtime/client.js").then((client) => {
|
|
35
|
-
client.init({
|
|
36
|
-
...options,
|
|
37
|
-
listen: scan
|
|
38
|
-
});
|
|
39
|
-
return client;
|
|
40
|
-
});
|
|
41
|
-
listen(document, "brumate:core", () => void loadCore());
|
|
42
|
-
const run = (element, ref, event) => {
|
|
43
|
-
loadCore().then((client) => client.handle(element, ref, event));
|
|
44
|
-
};
|
|
45
|
-
const apply = (event, element, entry) => {
|
|
46
|
-
if (entry.modifiers.includes("prevent")) event.preventDefault();
|
|
47
|
-
if (entry.modifiers.includes("once")) {
|
|
48
|
-
const rest = (element.getAttribute("data-on") ?? "").split(" ").filter((item) => item !== entry.raw);
|
|
49
|
-
element.setAttribute("data-on", rest.join(" "));
|
|
50
|
-
}
|
|
51
|
-
run(element, entry.ref, event);
|
|
52
|
-
return entry.modifiers.includes("stop");
|
|
53
|
-
};
|
|
54
|
-
const onEvent = (event) => {
|
|
55
|
-
for (let node = event.target; node && node !== document; node = node.parentNode) {
|
|
56
|
-
if (node.nodeType !== 1 || !node.hasAttribute("data-on")) continue;
|
|
57
|
-
let stop = false;
|
|
58
|
-
for (const entry of entries(node)) if (entry.type === event.type && apply(event, node, entry)) stop = true;
|
|
59
|
-
if (stop) {
|
|
60
|
-
event.stopPropagation();
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
};
|
|
65
|
-
const started = /* @__PURE__ */ new WeakSet();
|
|
66
|
-
const select = (root, selector) => {
|
|
67
|
-
const found = [...root.querySelectorAll(selector)];
|
|
68
|
-
if (root.matches?.(selector)) found.unshift(root);
|
|
69
|
-
return found.filter((element) => {
|
|
70
|
-
if (element.tagName !== "TEMPLATE") return true;
|
|
71
|
-
if (started.has(element)) return false;
|
|
72
|
-
started.add(element);
|
|
73
|
-
return true;
|
|
74
|
-
});
|
|
75
|
-
};
|
|
76
|
-
const visible = typeof IntersectionObserver === "undefined" ? void 0 : new IntersectionObserver((records) => {
|
|
77
|
-
for (const record of records) if (record.isIntersecting) {
|
|
78
|
-
visible.unobserve(record.target);
|
|
79
|
-
preload(record.target);
|
|
80
|
-
}
|
|
81
|
-
});
|
|
82
|
-
removers.push(() => visible?.disconnect());
|
|
83
|
-
const scan = (root) => {
|
|
84
|
-
for (const element of select(root, "[data-prefetch=\"visible\"], [data-prefetch=\"idle\"]")) if (strategy(element) === "idle" || !visible) (window.requestIdleCallback ?? setTimeout)(() => preload(element));
|
|
85
|
-
else visible.observe(element);
|
|
86
|
-
for (const element of select(root, "[data-on]:not(template)")) for (const { type } of entries(element)) if (!types.has(type)) {
|
|
87
|
-
types.add(type);
|
|
88
|
-
listen(document, type, onEvent, true);
|
|
89
|
-
}
|
|
90
|
-
for (const template of select(root, "template[data-listen]")) {
|
|
91
|
-
const target = template.getAttribute("data-listen") === "window" ? window : document;
|
|
92
|
-
for (const entry of entries(template)) listen(target, entry.type, (event) => apply(event, template, entry));
|
|
93
|
-
}
|
|
94
|
-
for (const template of select(root, "template[data-client]")) {
|
|
95
|
-
const [trigger, ref] = template.getAttribute("data-client").split("=");
|
|
96
|
-
const go = () => run(template, ref);
|
|
97
|
-
const next = template.nextElementSibling;
|
|
98
|
-
if (trigger === "idle") (window.requestIdleCallback ?? setTimeout)(go);
|
|
99
|
-
else if (trigger === "visible" && next && typeof IntersectionObserver !== "undefined") {
|
|
100
|
-
const observer = new IntersectionObserver((records) => {
|
|
101
|
-
if (records.some((record) => record.isIntersecting)) {
|
|
102
|
-
observer.disconnect();
|
|
103
|
-
go();
|
|
104
|
-
}
|
|
105
|
-
});
|
|
106
|
-
observer.observe(next);
|
|
107
|
-
} else go();
|
|
108
|
-
}
|
|
109
|
-
};
|
|
110
|
-
const preloaded = /* @__PURE__ */ new WeakSet();
|
|
111
|
-
const preload = (element) => {
|
|
112
|
-
if (preloaded.has(element)) return;
|
|
113
|
-
preloaded.add(element);
|
|
114
|
-
import("./runtime/client.js");
|
|
115
|
-
for (const entry of entries(element)) {
|
|
116
|
-
const [id, name] = entry.ref.split("#");
|
|
117
|
-
options.load(id).then((module) => module.load(/^[hc]\d/.test(name) ? name : "update"));
|
|
118
|
-
}
|
|
119
|
-
};
|
|
120
|
-
listen(document, "pointerover", (event) => {
|
|
121
|
-
const element = event.target.closest?.("[data-on]");
|
|
122
|
-
if (element && strategy(element) === "hover") preload(element);
|
|
123
|
-
}, { passive: true });
|
|
124
|
-
listen(document, "focusin", (event) => {
|
|
125
|
-
const element = event.target.closest?.("[data-on]");
|
|
126
|
-
if (element && strategy(element) === "hover") preload(element);
|
|
127
|
-
});
|
|
128
|
-
listen(document, "submit", (event) => {
|
|
129
|
-
const form = event.target;
|
|
130
|
-
if (event.defaultPrevented || !form.hasAttribute?.("data-result")) return;
|
|
131
|
-
event.preventDefault();
|
|
132
|
-
const submitter = event.submitter;
|
|
133
|
-
loadCore().then((client) => client.submitAction(form, submitter));
|
|
134
|
-
});
|
|
135
|
-
if (options.navigate === false) listen(document, "brumate:reload", () => location.reload());
|
|
136
|
-
if (options.navigate !== false) {
|
|
137
|
-
const rpc = `${options.rpc ?? "/_brumate"}/`;
|
|
138
|
-
let page = String(location.href).split("#")[0];
|
|
139
|
-
const go = (url, init, push = true) => {
|
|
140
|
-
page = url.split("#")[0];
|
|
141
|
-
import("./navigate-C5dP89YL.js").then(({ navigate }) => navigate({
|
|
142
|
-
url,
|
|
143
|
-
init,
|
|
144
|
-
push,
|
|
145
|
-
transition: typeof options.navigate === "object" && options.navigate.transition === true,
|
|
146
|
-
leave: async (partial) => {
|
|
147
|
-
const client = await core;
|
|
148
|
-
if (partial) client?.dispose();
|
|
149
|
-
else client?.leavePage();
|
|
150
|
-
},
|
|
151
|
-
enter: () => {
|
|
152
|
-
core?.then((client) => client.init({
|
|
153
|
-
...options,
|
|
154
|
-
listen: scan
|
|
155
|
-
}));
|
|
156
|
-
page = location.href.split("#")[0];
|
|
157
|
-
}
|
|
158
|
-
}));
|
|
159
|
-
};
|
|
160
|
-
const pageLink = (target) => {
|
|
161
|
-
const link = target?.closest?.("a[href]");
|
|
162
|
-
return link && !link.target && !link.hasAttribute("download") && !link.hasAttribute("data-reload") && link.origin === location.origin && !(link.hash && link.href.split("#")[0] === page) ? link : void 0;
|
|
163
|
-
};
|
|
164
|
-
listen(document, "click", (event) => {
|
|
165
|
-
const mouse = event;
|
|
166
|
-
const link = pageLink(event.target);
|
|
167
|
-
if (!link || event.defaultPrevented || mouse.button || mouse.metaKey || mouse.ctrlKey || mouse.shiftKey || mouse.altKey) return;
|
|
168
|
-
event.preventDefault();
|
|
169
|
-
go(link.href);
|
|
170
|
-
});
|
|
171
|
-
let resting;
|
|
172
|
-
listen(document, "pointerover", (event) => {
|
|
173
|
-
const link = pageLink(event.target);
|
|
174
|
-
if (link) {
|
|
175
|
-
clearTimeout(resting);
|
|
176
|
-
resting = setTimeout(() => prefetch(link), 80);
|
|
177
|
-
}
|
|
178
|
-
}, { passive: true });
|
|
179
|
-
listen(document, "pointerout", () => clearTimeout(resting), { passive: true });
|
|
180
|
-
listen(document, "focusin", (event) => prefetch(pageLink(event.target)));
|
|
181
|
-
listen(document, "submit", (event) => {
|
|
182
|
-
const form = event.target;
|
|
183
|
-
const submitter = event.submitter;
|
|
184
|
-
const action = submitter?.getAttribute("formaction") ?? form.getAttribute("action") ?? "";
|
|
185
|
-
const method = submitter?.getAttribute("formmethod") ?? form.getAttribute("method");
|
|
186
|
-
if (event.defaultPrevented || method?.toLowerCase() !== "post" || !action.startsWith(rpc)) return;
|
|
187
|
-
event.preventDefault();
|
|
188
|
-
go(action, {
|
|
189
|
-
method: "POST",
|
|
190
|
-
body: new FormData(form, submitter)
|
|
191
|
-
});
|
|
192
|
-
});
|
|
193
|
-
listen(document, "brumate:reload", () => go(location.href, { method: "GET" }, false));
|
|
194
|
-
listen(window, "popstate", () => {
|
|
195
|
-
if (location.href.split("#")[0] !== page) go(location.href, void 0, false);
|
|
196
|
-
});
|
|
197
|
-
}
|
|
198
|
-
scan(document);
|
|
199
|
-
const observer = new MutationObserver((records) => {
|
|
200
|
-
for (const record of records) for (const node of record.addedNodes) if (node.nodeType === 1) scan(node);
|
|
201
|
-
});
|
|
202
|
-
observer.observe(document, {
|
|
203
|
-
childList: true,
|
|
204
|
-
subtree: true
|
|
205
|
-
});
|
|
206
|
-
return () => {
|
|
207
|
-
observer.disconnect();
|
|
208
|
-
for (const remove of removers.splice(0)) remove();
|
|
209
|
-
core?.then((client) => client.dispose());
|
|
210
|
-
};
|
|
211
|
-
}
|
|
212
|
-
//#endregion
|
|
213
|
-
export { start as t };
|
|
214
|
-
|
|
215
|
-
//# sourceMappingURL=loader-py4qu6tQ.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"loader-py4qu6tQ.js","names":[],"sources":["../src/runtime/loader.ts"],"sourcesContent":["import type * as Client from './client.ts';\nimport type { ClientModule } from './client.ts';\n\nexport interface LoaderOptions {\n /** Imports the client module of a component, by component ID. */\n load: (id: string) => Promise<ClientModule>;\n /** The URL prefix of server function calls. */\n rpc?: string;\n /**\n * Loads pages without a full page load: links to the same origin, the back\n * and forward buttons, and forms that post to a server function. Defaults to true.\n */\n navigate?: boolean | NavigateOptions;\n}\n\nexport interface NavigateOptions {\n /**\n * Swaps the page inside a view transition, where the browser has them.\n * CSS can tell links, the back and forward buttons and forms apart with\n * the types `push`, `traverse` and `form`.\n */\n transition?: boolean;\n}\n\ninterface Entry {\n raw: string;\n type: string;\n modifiers: string[];\n ref: string;\n}\n\nfunction entries(element: Element): Entry[] {\n return (element.getAttribute('data-on') ?? '')\n .split(' ')\n .filter(Boolean)\n .map((entry) => {\n const [name, ref] = entry.split('=') as [string, string];\n const [type, ...modifiers] = name.split(':') as [string, ...string[]];\n return { raw: entry, type, modifiers, ref };\n });\n}\n\nfunction strategy(element: Element): string {\n return element.getAttribute('data-prefetch') ?? 'hover';\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 * Starts resuming the page. Listens to the events in `data-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 let core: Promise<typeof Client> | undefined;\n const types = new Set<string>();\n const removers: (() => void)[] = [];\n const listen = (\n target: EventTarget,\n type: string,\n listener: (event: Event) => void,\n flags?: AddEventListenerOptions | boolean,\n ): void => {\n target.addEventListener(type, listener, flags);\n removers.push(() => target.removeEventListener(type, listener, flags));\n };\n\n const loadCore = (): Promise<typeof Client> =>\n (core ??= import('./client.ts').then((client) => {\n client.init({ ...options, listen: scan });\n return client;\n }));\n\n // The devtools panel asks for the core when it opens, so it can show the page before any event.\n listen(document, 'brumate:core', () => void loadCore());\n\n const run = (element: Element, ref: string, event?: Event): void => {\n void loadCore().then((client) => client.handle(element, ref, event));\n };\n\n const apply = (event: Event, element: Element, entry: Entry): boolean => {\n if (entry.modifiers.includes('prevent')) {\n event.preventDefault();\n }\n if (entry.modifiers.includes('once')) {\n const rest = (element.getAttribute('data-on') ?? '')\n .split(' ')\n .filter((item) => item !== entry.raw);\n element.setAttribute('data-on', rest.join(' '));\n }\n run(element, entry.ref, event);\n return entry.modifiers.includes('stop');\n };\n\n // Handlers run from the target outwards, as if each element had its own listener.\n const onEvent = (event: Event): void => {\n for (\n let node = event.target as Node | null;\n node && node !== document;\n node = node.parentNode\n ) {\n if (node.nodeType !== 1 || !(node as Element).hasAttribute('data-on')) {\n continue;\n }\n let stop = false;\n for (const entry of entries(node as Element)) {\n if (entry.type === event.type && apply(event, node as Element, entry)) {\n stop = true;\n }\n }\n if (stop) {\n event.stopPropagation();\n return;\n }\n }\n };\n\n // Templates are started once, even when markup is scanned again.\n const started = new WeakSet<Element>();\n const select = (root: ParentNode, selector: string): Element[] => {\n const found = [...root.querySelectorAll(selector)];\n if ((root as Element).matches?.(selector)) {\n found.unshift(root as Element);\n }\n return found.filter((element) => {\n if (element.tagName !== 'TEMPLATE') {\n return true;\n }\n if (started.has(element)) {\n return false;\n }\n started.add(element);\n return true;\n });\n };\n\n const visible =\n typeof IntersectionObserver === 'undefined'\n ? undefined\n : new IntersectionObserver((records) => {\n for (const record of records) {\n if (record.isIntersecting) {\n visible!.unobserve(record.target);\n preload(record.target);\n }\n }\n });\n removers.push(() => visible?.disconnect());\n\n const scan = (root: ParentNode): void => {\n for (const element of select(root, '[data-prefetch=\"visible\"], [data-prefetch=\"idle\"]')) {\n if (strategy(element) === 'idle' || !visible) {\n (window.requestIdleCallback ?? setTimeout)(() => preload(element));\n } else {\n visible.observe(element);\n }\n }\n for (const element of select(root, '[data-on]:not(template)')) {\n for (const { type } of entries(element)) {\n if (!types.has(type)) {\n types.add(type);\n listen(document, type, onEvent, true);\n }\n }\n }\n for (const template of select(root, 'template[data-listen]')) {\n const target = template.getAttribute('data-listen') === 'window' ? window : document;\n for (const entry of entries(template)) {\n listen(target, entry.type, (event) => apply(event, template, entry));\n }\n }\n for (const template of select(root, 'template[data-client]')) {\n const [trigger, ref] = template.getAttribute('data-client')!.split('=') as [string, string];\n const go = (): void => run(template, ref);\n const next = template.nextElementSibling;\n if (trigger === 'idle') {\n (window.requestIdleCallback ?? setTimeout)(go);\n } else if (trigger === 'visible' && next && typeof IntersectionObserver !== 'undefined') {\n const observer = new IntersectionObserver((records) => {\n if (records.some((record) => record.isIntersecting)) {\n observer.disconnect();\n go();\n }\n });\n observer.observe(next);\n } else {\n go();\n }\n }\n };\n\n // Preloads the core and the parts of an element's handlers, so its first event does not wait for them.\n const preloaded = new WeakSet<Element>();\n const preload = (element: Element): void => {\n if (preloaded.has(element)) {\n return;\n }\n preloaded.add(element);\n void import('./client.ts');\n for (const entry of entries(element)) {\n const [id, name] = entry.ref.split('#') as [string, string];\n void options.load(id).then((module) => module.load(/^[hc]\\d/.test(name) ? name : 'update'));\n }\n };\n\n listen(\n document,\n 'pointerover',\n (event) => {\n const element = (event.target as Element).closest?.('[data-on]');\n if (element && strategy(element) === 'hover') {\n preload(element);\n }\n },\n { passive: true },\n );\n listen(document, 'focusin', (event) => {\n const element = (event.target as Element).closest?.('[data-on]');\n if (element && strategy(element) === 'hover') {\n preload(element);\n }\n });\n\n // A form of an `$action` sends its data with `fetch`, and the core writes the result into the page.\n listen(document, 'submit', (event) => {\n const form = event.target as HTMLFormElement;\n if (event.defaultPrevented || !form.hasAttribute?.('data-result')) {\n return;\n }\n event.preventDefault();\n const submitter = (event as SubmitEvent).submitter;\n void loadCore().then((client) => client.submitAction(form, submitter));\n });\n\n if (options.navigate === false) {\n // A hot update whose markup changed loads the page again.\n listen(document, 'brumate:reload', () => location.reload());\n }\n if (options.navigate !== false) {\n const rpc = `${options.rpc ?? '/_brumate'}/`;\n // The page without its hash, to tell a change of the hash from a change of the page.\n let page = String(location.href).split('#')[0];\n const go = (url: string, init?: RequestInit, push = true): void => {\n page = url.split('#')[0]!;\n void import('./navigate.ts').then(({ navigate }) =>\n navigate({\n url,\n init,\n push,\n transition: typeof options.navigate === 'object' && options.navigate.transition === true,\n // The core forgets the old page, or only stops reading, when layouts stay.\n leave: async (partial) => {\n const client = await core;\n if (partial) {\n client?.dispose();\n } else {\n client?.leavePage();\n }\n },\n enter: () => {\n void core?.then((client) => client.init({ ...options, listen: scan }));\n page = location.href.split('#')[0]!;\n },\n }),\n );\n };\n // A link to another page of this site, which the loader loads itself.\n const pageLink = (target: EventTarget | null): HTMLAnchorElement | undefined => {\n const link = (target as Element | null)?.closest?.('a[href]') as HTMLAnchorElement | null;\n return link &&\n !link.target &&\n !link.hasAttribute('download') &&\n !link.hasAttribute('data-reload') &&\n link.origin === location.origin &&\n // A link to a place in the same page scrolls there.\n !(link.hash && link.href.split('#')[0] === page)\n ? link\n : undefined;\n };\n listen(document, 'click', (event) => {\n const mouse = event as MouseEvent;\n const link = pageLink(event.target);\n if (\n !link ||\n event.defaultPrevented ||\n mouse.button ||\n mouse.metaKey ||\n mouse.ctrlKey ||\n mouse.shiftKey ||\n mouse.altKey\n ) {\n return;\n }\n event.preventDefault();\n go(link.href);\n });\n // A page loads when the pointer rests on its link, or the link gets focus, so a click finds it loading.\n let resting: ReturnType<typeof setTimeout> | undefined;\n listen(\n document,\n 'pointerover',\n (event) => {\n const link = pageLink(event.target);\n if (link) {\n clearTimeout(resting);\n resting = setTimeout(() => prefetch(link), 80);\n }\n },\n { passive: true },\n );\n listen(document, 'pointerout', () => clearTimeout(resting), { passive: true });\n listen(document, 'focusin', (event) => prefetch(pageLink(event.target)));\n listen(document, 'submit', (event) => {\n const form = event.target as HTMLFormElement;\n const submitter = (event as SubmitEvent).submitter;\n const action = submitter?.getAttribute('formaction') ?? form.getAttribute('action') ?? '';\n const method = submitter?.getAttribute('formmethod') ?? form.getAttribute('method');\n if (event.defaultPrevented || method?.toLowerCase() !== 'post' || !action.startsWith(rpc)) {\n return;\n }\n event.preventDefault();\n go(action, { method: 'POST', body: new FormData(form, submitter) });\n });\n // A hot update whose markup changed loads the page again, in place. With `init`, the whole\n // page is replaced, as for a form, so layouts render again too, and it keeps the scroll.\n listen(document, 'brumate:reload', () => go(location.href, { method: 'GET' }, false));\n listen(window, 'popstate', () => {\n // A change of the hash only stays on the page.\n if (location.href.split('#')[0] !== page) {\n go(location.href, undefined, false);\n }\n });\n }\n\n scan(document);\n // Markup that streams in later, such as a `#loading` body, has handlers too.\n const observer = new MutationObserver((records) => {\n for (const record of records) {\n for (const node of record.addedNodes) {\n if (node.nodeType === 1) {\n scan(node as Element);\n }\n }\n }\n });\n observer.observe(document, { childList: true, subtree: true });\n return () => {\n observer.disconnect();\n for (const remove of removers.splice(0)) {\n remove();\n }\n void core?.then((client) => client.dispose());\n };\n}\n"],"mappings":";AA+BA,SAAS,QAAQ,SAA2B;CAC1C,QAAQ,QAAQ,aAAa,SAAS,KAAK,GAAA,CACxC,MAAM,GAAG,CAAC,CACV,OAAO,OAAO,CAAC,CACf,KAAK,UAAU;EACd,MAAM,CAAC,MAAM,OAAO,MAAM,MAAM,GAAG;EACnC,MAAM,CAAC,MAAM,GAAG,aAAa,KAAK,MAAM,GAAG;EAC3C,OAAO;GAAE,KAAK;GAAO;GAAM;GAAW;EAAI;CAC5C,CAAC;AACL;AAEA,SAAS,SAAS,SAA0B;CAC1C,OAAO,QAAQ,aAAa,eAAe,KAAK;AAClD;;AAGA,SAAS,SAAS,MAA2C;CAC3D,IAAI,QAAQ,KAAK,aAAa,eAAe,MAAM,QACjD,OAAY,yBA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,KAAK,aAAa,GACpB,KAAK,IAAe;CAI5B,CAAC;CACD,SAAS,QAAQ,UAAU;EAAE,WAAW;EAAM,SAAS;CAAK,CAAC;CAC7D,aAAa;EACX,SAAS,WAAW;EACpB,KAAK,MAAM,UAAU,SAAS,OAAO,CAAC,GACpC,OAAO;EAET,MAAW,MAAM,WAAW,OAAO,QAAQ,CAAC;CAC9C;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"navigate-C5dP89YL.js","names":[],"sources":["../src/runtime/navigate.ts"],"sourcesContent":["// Client navigation. The loader imports it on the first navigation, so pages\n// that never navigate do not load it.\n\nexport interface Visit {\n url: string;\n /** For a form that posts to a server function. */\n init?: RequestInit;\n /** False for the back and forward buttons, which already changed the history. */\n push: boolean;\n /**\n * Runs before the new page replaces the old one. `partial` is true when\n * the page keeps its layouts and replaces only some routes.\n */\n leave: (partial: boolean) => Promise<void>;\n /** Runs after the first render of the new page is in the document. */\n enter: () => void;\n /** Swaps the page inside a view transition, where the browser has them. */\n transition?: boolean;\n}\n\n/**\n * Runs `update` inside a view transition, with a type that tells how the page\n * was reached: `push` for a link, `traverse` for the back and forward\n * buttons, and `form` for a form. Without transitions, it runs `update`.\n */\nasync function transition(visit: Visit, update: () => void): Promise<void> {\n if (!visit.transition || typeof document.startViewTransition !== 'function') {\n update();\n return;\n }\n const types = [visit.init ? 'form' : visit.push ? 'push' : 'traverse'];\n // Browsers that have transitions without types take only a callback.\n const started =\n typeof ViewTransition !== 'undefined' && 'types' in ViewTransition.prototype\n ? document.startViewTransition({ update, types })\n : document.startViewTransition(update);\n await started.updateCallbackDone;\n}\n\nlet controller: AbortController | undefined;\n\nconst STATE = 'script[type=\"brumate/state\"]';\n\n/** A route slot in the page, between `<!--R…-->` and `<!--/R-->`. */\ninterface Region {\n /** The scope of the layout that renders the slot. */\n layout: number;\n name: string;\n /** The scope of the route in the slot. */\n root: number;\n key: string;\n start: Comment;\n end: Comment;\n children: Region[];\n}\n\n/** Finds the route slots in a document, nested as the routes are. */\nfunction regions(root: Node): Region[] {\n const top: Region[] = [];\n const stack: Region[] = [];\n const walker = (root.ownerDocument ?? (root as Document)).createTreeWalker(root, 128);\n for (\n let node = walker.nextNode() as Comment | null;\n node;\n node = walker.nextNode() as Comment | null\n ) {\n const match = /^R(-?\\d+):([^:]+):(\\d+):(.*)$/.exec(node.data);\n if (match) {\n const region: Region = {\n layout: Number(match[1]),\n name: match[2]!,\n root: Number(match[3]),\n key: decodeURIComponent(match[4]!),\n start: node,\n end: node,\n children: [],\n };\n (stack.at(-1)?.children ?? top).push(region);\n stack.push(region);\n } else if (node.data === '/R' && stack.length > 0) {\n stack.pop()!.end = node;\n }\n }\n return top;\n}\n\ninterface Plan {\n /** Old slots and the new slots that replace them. */\n replace: [Region, Region][];\n alias: Map<number, number>;\n}\n\n/**\n * Pairs the slots of the old and the new page by name. A layout with the\n * same key stays, and its slots are compared in turn. Any other route is\n * replaced. Returns undefined when the pages do not line up.\n */\nfunction plan(old: Region[], next: Region[], result: Plan): Plan | undefined {\n for (const region of next) {\n const before = old.find((item) => item.name === region.name);\n if (!before) {\n return undefined;\n }\n result.alias.set(region.layout, before.layout);\n if (before.key === region.key && region.children.length > 0) {\n // The layout stays, so its new scope stands for the old one.\n result.alias.set(region.root, before.root);\n if (!plan(before.children, region.children, result)) {\n return undefined;\n }\n } else {\n result.replace.push([before, region]);\n }\n }\n return result;\n}\n\nfunction between(start: Node, end: Node): Node[] {\n const nodes = [start];\n for (let node = start.nextSibling; node && nodes.at(-1) !== end; node = node.nextSibling) {\n nodes.push(node);\n }\n return nodes;\n}\n\n/**\n * The server writes a component's stylesheet before its first instance, so\n * an old route can hold the stylesheet of a component that a kept layout\n * still shows. Such a stylesheet moves to the head. The others go with the\n * route, so the page keeps only the CSS of the components that it shows.\n */\nfunction keepStyles(removed: HTMLStyleElement[]): void {\n for (const style of removed) {\n const id = style.getAttribute('data-brm')!;\n // The component ID ends with the hash that scopes its elements, as `s-<hash>`.\n const attribute = `s-${id.slice(id.lastIndexOf('_') + 1)}`;\n const present = document.querySelector(`style[data-brm=\"${CSS.escape(id)}\"]`);\n if (!present && document.querySelector(`[${attribute}]`)) {\n document.head.append(style);\n }\n }\n}\n\n/** True when a slot's end comment is a sibling of its start comment. */\nfunction complete(region: Region): boolean {\n return between(region.start, region.end).at(-1) === region.end;\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, requested: number): Plan | undefined {\n const scripts = document.querySelectorAll(`${STATE}[data-route]`);\n const route = scripts[scripts.length - 1]?.getAttribute('data-route');\n const state = next.body.querySelector(`${STATE}[data-route]`);\n if (!route || state?.getAttribute('data-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('data-root') !== String(requested)) {\n return undefined;\n }\n const result = plan(regions(document.body), regions(next.body), {\n replace: [],\n alias: new Map(),\n });\n if (\n !result ||\n result.replace.length === 0 ||\n !result.replace.every(([before, region]) => complete(before) && complete(region))\n ) {\n return undefined;\n }\n return result;\n}\n\n/** Replaces the routes that change, and keeps the rest of the page. */\nfunction replaceRoutes(next: Document, result: Plan): void {\n const state = next.body.querySelector(`${STATE}[data-route]`)!;\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 removed.push(\n ...(element.matches('style[data-brm]') ? [element as HTMLStyleElement] : []),\n ...element.querySelectorAll<HTMLStyleElement>('style[data-brm]'),\n );\n }\n }\n const parent = before.start.parentNode!;\n for (const node of between(region.start, region.end)) {\n parent.insertBefore(document.adoptNode(node), before.start);\n }\n for (const node of nodes) {\n node.parentNode?.removeChild(node);\n }\n }\n keepStyles(removed);\n // The core drops the scopes of the old routes, and adds only the scopes of the new ones.\n state.setAttribute('data-drop', result.replace.map(([before]) => before.root).join(','));\n state.setAttribute('data-roots', result.replace.map(([, region]) => region.root).join(','));\n state.setAttribute(\n 'data-alias',\n [...result.alias].map(([from, to]) => `${from}:${to}`).join(','),\n );\n for (const script of next.body.querySelectorAll(STATE)) {\n document.body.append(document.adoptNode(script));\n }\n}\n\n/** Moves the IDs of a page above the IDs of the page in the browser. */\ninterface Shift {\n /** The number to add to each scope and boundary ID. */\n by: number;\n /** The `data-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(next: Document, requested: number): Shift | undefined {\n const state = next.body.querySelector(`${STATE}[data-route]`);\n if (!state) {\n return undefined;\n }\n const root = Number(state.getAttribute('data-root') ?? 0);\n return root === requested ? undefined : { by: requested - root, root: String(requested) };\n}\n\nconst COMMENT_IDS = /^([tb])(\\d+)(:.*)$|^([ilP])(\\d+)$/;\nconst REGION = /^R(-?\\d+):([^:]+):(\\d+):(.*)$/;\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 `data-offset`.\n */\nfunction shiftIds(root: Node, shift: Shift): void {\n const add = (value: string): string => String(Number(value) + shift.by);\n const visit = (node: Node): void => {\n if (node.nodeType === 8) {\n const comment = node as Comment;\n const region = REGION.exec(comment.data);\n if (region) {\n const layout = Number(region[1]) < 0 ? region[1]! : add(region[1]!);\n comment.data = `R${layout}:${region[2]}:${add(region[3]!)}:${region[4]}`;\n return;\n }\n const match = COMMENT_IDS.exec(comment.data);\n if (match) {\n comment.data = match[1]\n ? `${match[1]}${add(match[2]!)}${match[3]}`\n : `${match[4]}${add(match[5]!)}`;\n }\n return;\n }\n if (node.nodeType !== 1) {\n return;\n }\n const element = node as Element;\n for (const name of ['data-b', 'data-result']) {\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 ['data-v', 'data-l', 'data-h', 'data-next']) {\n const value = element.getAttribute(name);\n if (value) {\n element.setAttribute(name, add(value));\n }\n }\n if (element.matches(STATE)) {\n element.setAttribute('data-offset', String(shift.by));\n element.setAttribute('data-root', shift.root);\n } else if (element.tagName === 'SCRIPT' && !element.hasAttribute('type')) {\n // The scripts that swap in `#loading` bodies and their head name the boundary.\n element.textContent = element.textContent!.replace(\n /\\$b([SH])\\((\\d+)/g,\n (_, kind: string, id: string) => `$b${kind}(${add(id)}`,\n );\n }\n for (const child of element.tagName === 'TEMPLATE'\n ? (element as HTMLTemplateElement).content.childNodes\n : element.childNodes) {\n visit(child);\n }\n };\n visit(root);\n}\n\n/** A number above every scope and boundary ID in the page, for the server to start the next page at. */\nfunction base(): number {\n let value = 0;\n for (const script of document.querySelectorAll(`${STATE}[data-next]`)) {\n value = Math.max(value, Number(script.getAttribute('data-next')));\n }\n return value;\n}\n\n/**\n * The Content Security Policy nonce of the page that the browser loaded.\n * Its policy stays for the whole visit, so scripts of later pages need it,\n * not the nonce of their own response. Read once, while a script holds it.\n */\nlet loadedNonce: string | undefined;\n\n/** The nonce of a script. Browsers hide the attribute once the page loads, and keep the property. */\nfunction nonceOf(script: HTMLScriptElement): string | null {\n return script.nonce || script.getAttribute('nonce');\n}\n\nfunction pageNonce(): string | undefined {\n for (const script of loadedNonce ? [] : document.querySelectorAll('script')) {\n loadedNonce = nonceOf(script) || undefined;\n if (loadedNonce) {\n break;\n }\n }\n return loadedNonce;\n}\n\n/** Copies a script, so the browser runs it. Scripts from a parser that has no window do not run. */\nfunction runnable(script: HTMLScriptElement): HTMLScriptElement {\n const copy = document.createElement('script');\n for (const attribute of script.attributes) {\n if (attribute.name !== 'nonce') {\n copy.setAttribute(attribute.name, attribute.value);\n }\n }\n // A script that its server gave a nonce runs under the policy of the loaded page.\n const nonce = nonceOf(script);\n if (nonce) {\n copy.nonce = pageNonce() ?? nonce;\n // A DOM without the property, such as in tests, reads the attribute.\n copy.setAttribute('nonce', copy.nonce);\n }\n copy.textContent = script.textContent;\n return copy;\n}\n\n/** Moves nodes into the body. Inline scripts, such as the ones that swap in `#loading` bodies, run. */\nfunction append(nodes: Node[], shift: Shift | undefined): void {\n for (const node of nodes) {\n if (shift) {\n shiftIds(node, shift);\n }\n const adopted = document.adoptNode(node);\n const scripts =\n adopted.nodeType === 1\n ? [\n ...((adopted as Element).matches('script') ? [adopted as HTMLScriptElement] : []),\n ...(adopted as Element).querySelectorAll('script'),\n ]\n : [];\n document.body.append(adopted);\n for (const script of scripts) {\n if (\n !script.src &&\n (!script.type || script.type === 'text/javascript' || script.type === 'module')\n ) {\n script.replaceWith(runnable(script));\n }\n }\n }\n}\n\n/** Makes the head of the page match the new one, keeping elements that are in both. */\nfunction updateHead(next: Document): void {\n const keep = new Map<string, Element>();\n for (const element of document.head.children) {\n keep.set(element.outerHTML, element);\n }\n // A copy, because adopting an element removes it from the live list.\n // oxlint-disable-next-line unicorn/no-useless-spread\n for (const element of [...next.head.children]) {\n const html = element.outerHTML;\n if (keep.has(html)) {\n keep.delete(html);\n } else {\n document.head.append(document.adoptNode(element));\n }\n }\n for (const element of keep.values()) {\n // Module scripts stay, because removing them does not unload them.\n if (!(element.tagName === 'SCRIPT' && (element as HTMLScriptElement).src)) {\n element.remove();\n }\n }\n}\n\nfunction scroll(url: URL, saved: number | undefined): void {\n if (saved !== undefined) {\n window.scrollTo(0, saved);\n return;\n }\n const target = url.hash && document.getElementById(decodeURIComponent(url.hash.slice(1)));\n if (target) {\n target.scrollIntoView();\n } else {\n window.scrollTo(0, 0);\n }\n}\n\n/**\n * Loads a page and replaces the current one with it. The first render of the\n * page replaces the document as soon as it arrives. Markup that the server\n * streams after it, such as `#loading` bodies, follows as it arrives.\n */\n// Pages that a link started to load before its click, by URL without the hash.\nconst prefetched = new Map<string, { at: number; base: number; response: Promise<Response> }>();\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 const requested = base();\n const response = fetch(key, { headers: { 'x-brumate-base': String(requested) } });\n // A failed load is not used. The click loads the page again.\n response.catch(() => prefetched.delete(key));\n prefetched.set(key, { at: performance.now(), base: requested, response });\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 return entry && entry.base === requested && performance.now() - entry.at < FRESH\n ? entry.response\n : undefined;\n}\n\nexport async function navigate(visit: Visit): Promise<void> {\n // Read before the page changes, while the scripts of the loaded page are in it.\n pageNonce();\n controller?.abort();\n const requested = base();\n const current = new AbortController();\n controller = current;\n // The scroll position of the page that is left, for the back button.\n history.replaceState({ ...history.state, scroll: window.scrollY }, '');\n let response: Response;\n try {\n const early = visit.init ? 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 prefetched.clear();\n } catch (error) {\n if (!current.signal.aborted) {\n location.assign(visit.url);\n }\n throw error;\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 === '&' ? '&' : '<'))}</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\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 reader.read();\n if (current.signal.aborted) {\n return;\n }\n if (chunk.done) {\n end = text.length;\n break;\n }\n text += chunk.value;\n const index = text.search(/<\\/html\\s*>/i);\n if (index !== -1) {\n end = index + text.slice(index).indexOf('>') + 1;\n }\n }\n const next = new DOMParser().parseFromString(text.slice(0, end), 'text/html');\n const shift = visit.init ? undefined : shiftFor(next, requested);\n if (shift) {\n shiftIds(next.body, shift);\n }\n // A link keeps the layouts that stay the same. A form replaces the whole page,\n // because what it changed can show anywhere on it.\n const routes = visit.init ? undefined : planRoutes(next, requested);\n await visit.leave(routes !== undefined);\n if (current.signal.aborted) {\n return;\n }\n await transition(visit, () => {\n // A copy, because removing an attribute changes the live list.\n // oxlint-disable-next-line unicorn/no-useless-spread\n for (const attribute of [...document.documentElement.attributes]) {\n document.documentElement.removeAttribute(attribute.name);\n }\n for (const attribute of next.documentElement.attributes) {\n document.documentElement.setAttribute(attribute.name, attribute.value);\n }\n // Read before the head moves, because moving the <title> clears it in `next`.\n const title = next.title;\n updateHead(next);\n document.title = title;\n const same = url.href === location.href;\n const top = window.scrollY;\n if (routes) {\n replaceRoutes(next, routes);\n } else {\n document.body.replaceWith(document.adoptNode(next.body));\n }\n // A link to the page itself, or a form that comes back to it, does not add to the history.\n if (visit.push && !same) {\n history.pushState({}, '', url);\n } else if (!same) {\n history.replaceState(history.state, '', url);\n }\n visit.enter();\n if (visit.init && same) {\n // A form that comes back to its page keeps the place on the page.\n window.scrollTo(0, top);\n } else {\n scroll(url, visit.push ? undefined : (history.state?.scroll as number | undefined));\n }\n });\n if (current.signal.aborted) {\n return;\n }\n\n // Later markup is parsed in a document without a window, so it can arrive\n // in any pieces. A node is complete once the parser has moved past it.\n const sink = document.implementation.createHTMLDocument('');\n sink.open();\n sink.write('<!doctype html><body>');\n let rest = text.slice(end);\n for (;;) {\n if (rest) {\n sink.write(rest);\n append([...sink.body.childNodes].slice(0, -1), shift);\n }\n // oxlint-disable-next-line no-await-in-loop -- Chunks arrive in order.\n const chunk = await reader.read();\n if (current.signal.aborted) {\n return;\n }\n if (chunk.done) {\n break;\n }\n rest = chunk.value;\n }\n sink.close();\n append([...sink.body.childNodes], shift);\n}\n"],"mappings":";;;;;;AAyBA,eAAe,WAAW,OAAc,QAAmC;CACzE,IAAI,CAAC,MAAM,cAAc,OAAO,SAAS,wBAAwB,YAAY;EAC3E,OAAO;EACP;CACF;CACA,MAAM,QAAQ,CAAC,MAAM,OAAO,SAAS,MAAM,OAAO,SAAS,UAAU;CAMrE,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;;AAgBd,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,gCAAgC,KAAK,KAAK,IAAI;EAC5D,IAAI,OAAO;GACT,MAAM,SAAiB;IACrB,QAAQ,OAAO,MAAM,EAAE;IACvB,MAAM,MAAM;IACZ,MAAM,OAAO,MAAM,EAAE;IACrB,KAAK,mBAAmB,MAAM,EAAG;IACjC,OAAO;IACP,KAAK;IACL,UAAU,CAAC;GACb;GACA,CAAC,MAAM,GAAG,EAAE,CAAC,EAAE,YAAY,IAAA,CAAK,KAAK,MAAM;GAC3C,MAAM,KAAK,MAAM;EACnB,OAAO,IAAI,KAAK,SAAS,QAAQ,MAAM,SAAS,GAC9C,MAAM,IAAI,CAAC,CAAE,MAAM;CAEvB;CACA,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AG,KAAK,KAAK,UAAU,CAAC,CAAC,MAAM,GAAG,EAAE,GAAG,KAAK;EACtD;EAEA,MAAM,QAAQ,MAAM,OAAO,KAAK;EAChC,IAAI,QAAQ,OAAO,SACjB;EAEF,IAAI,MAAM,MACR;EAEF,OAAO,MAAM;CACf;CACA,KAAK,MAAM;CACX,OAAO,CAAC,GAAG,KAAK,KAAK,UAAU,GAAG,KAAK;AACzC"}
|
package/dist/rpc-B86KKjzx.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"rpc-B86KKjzx.js","names":[],"sources":["../src/runtime/rpc.ts"],"sourcesContent":["import { toJSONAsync } from 'seroval';\nimport { Upload, disabledFeatures, plugins, replaceDeep } from './shared.ts';\nimport { fromChunkStream } from './stream.ts';\n\n/**\n * True for a file or a blob. One from another frame, or another DOM, is an\n * instance of another `Blob` class, so its methods tell instead.\n */\nfunction isBlob(value: unknown): value is Blob {\n if (value instanceof Blob) {\n return true;\n }\n const blob = value as Partial<Blob> | null;\n return (\n typeof blob === 'object' &&\n blob !== null &&\n typeof blob.size === 'number' &&\n typeof blob.type === 'string' &&\n typeof blob.arrayBuffer === 'function' &&\n typeof blob.slice === 'function'\n );\n}\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, in arrays and plain objects, go as parts\n * of 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 const files: Blob[] = [];\n const sent = replaceDeep(args, (value) =>\n isBlob(value) ? new Upload(files.push(value) - 1) : undefined,\n );\n const json = JSON.stringify(await toJSONAsync(sent, { plugins, disabledFeatures }));\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 blobs = await Promise.all(\n files.map(async (file: Blob) =>\n // Typed as a Blob, so the check narrows a blob of another DOM to never.\n file instanceof Blob\n ? file\n : new Blob([await (file as Blob).arrayBuffer()], { type: (file as Blob).type }),\n ),\n );\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 answer(\n id,\n await fetch(`${prefix}/${encodeURIComponent(id)}`, { ...init, method: 'POST', signal }),\n );\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(prefix: string, id: string, form: FormData): Promise<unknown> {\n return answer(\n id,\n await fetch(`${prefix}/${encodeURIComponent(id)}`, {\n method: 'POST',\n headers: { 'x-brumate-result': '1' },\n body: form,\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. The core listens.\n const refreshed = response.headers.get('x-brumate-refresh');\n if (refreshed) {\n document.dispatchEvent(new CustomEvent('brumate:refresh', { detail: refreshed.split(',') }));\n }\n const location = response.headers.get('x-brumate-redirect');\n if (location !== null) {\n window.location.assign(location);\n // The page is leaving, so the call never settles.\n return new Promise(() => {});\n }\n if (!response.ok) {\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 throw Object.assign(new Error(message), { name: 'ServerError', status: response.status });\n }\n // Promises and async iterables in the result settle as the rest of the answer arrives.\n return fromChunkStream(response.body!);\n}\n"],"mappings":";;;;;;;;AAQA,SAAS,OAAO,OAA+B;CAC7C,IAAI,iBAAiB,MACnB,OAAO;CAET,MAAM,OAAO;CACb,OACE,OAAO,SAAS,YAChB,SAAS,QACT,OAAO,KAAK,SAAS,YACrB,OAAO,KAAK,SAAS,YACrB,OAAO,KAAK,gBAAgB,cAC5B,OAAO,KAAK,UAAU;AAE1B;;;;;;;;AASA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B,EAAE,QAAQ,UAAU,MAAM,GAAG,EAAE,CAAC,CAAC;CAE7F,MAAM,WAAW,SAAS,QAAQ,IAAI,oBAAoB;CAC1D,IAAI,aAAa,MAAM;EACrB,OAAO,SAAS,OAAO,QAAQ;EAE/B,OAAO,IAAI,cAAc,CAAC,CAAC;CAC7B;CACA,IAAI,CAAC,SAAS,IAAI;EAChB,IAAI,UAAU,oBAAoB,GAAG,uBAAuB,SAAS;EACrE,IAAI;GACF,WAAY,MAAM,SAAS,KAAK,EAAA,CAAyB;EAC3D,QAAQ,CAER;EACA,MAAM,OAAO,OAAO,IAAI,MAAM,OAAO,GAAG;GAAE,MAAM;GAAe,QAAQ,SAAS;EAAO,CAAC;CAC1F;CAEA,OAAO,gBAAgB,SAAS,IAAK;AACvC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"server-CX3JnPCs.js","names":[],"sources":["../src/runtime/request.ts","../src/runtime/router.ts","../src/runtime/server.ts"],"sourcesContent":["import { toJSON } from 'seroval';\nimport { deleteCookie, getCookies, setCookie } from './cookies.ts';\nimport type { CookieOptions } from './cookies.ts';\nimport { disabledFeatures, plugins } from './shared.ts';\n\n/**\n * A request that the server handles: a server function call, a form post,\n * a page render, or a call of middleware or an endpoint. Its methods read\n * the request and change the response. Get it with `getEvent()`.\n */\nexport class RequestEvent {\n readonly request: Request;\n /** Headers to add to the response, such as `cache-control`. */\n readonly headers: Headers = new Headers();\n /** The status that `setStatus` set. */\n status?: number;\n /** Server functions that `refresh` named, whose memos the client loads again. */\n refreshed?: Set<unknown>;\n /** Cookies that this request set, or deleted with undefined, so later reads see them. */\n cookies?: Map<string, string | undefined>;\n\n constructor(request: Request) {\n this.request = request;\n }\n\n /**\n * Sets the status of the page response, such as 404 for a page that shows\n * that nothing was found. It works while the first render of a page runs.\n * Markup that streams later, such as a `#loading` body, cannot change it,\n * because the response has started by then.\n */\n setStatus(status: number): void {\n this.status = status;\n }\n\n /**\n * Asks the client to load again the memos that call a server function, such\n * as a list after a server function adds to it. The compiler gives those\n * memos client code, so they can load.\n */\n refresh(fn: (...args: never[]) => unknown): void {\n this.refreshed ??= new Set();\n this.refreshed.add(unwrap(fn));\n }\n\n /** The cookies of the request, with the ones that this request set or deleted. */\n getCookies(): Record<string, string> {\n return getCookies(this);\n }\n\n /** A cookie of the request, or the value that this request set. */\n getCookie(name: string): string | undefined {\n return getCookies(this)[name];\n }\n\n /**\n * Sets a cookie on the response. It is `HttpOnly`, `SameSite=Lax` and on\n * the path `/` unless the options say otherwise, and `Secure` on HTTPS.\n * Markup that streams later, such as a `#loading` body, cannot set cookies,\n * because the response has started.\n */\n setCookie(name: string, value: string, options: CookieOptions = {}): void {\n setCookie(this, name, value, options);\n }\n\n /** Deletes a cookie. Pass the `path` and `domain` that it was set with, if they were not the defaults. */\n deleteCookie(name: string, options: Pick<CookieOptions, 'path' | 'domain'> = {}): void {\n deleteCookie(this, name, options);\n }\n}\n\n/**\n * The event of the code that runs now. The runtime sets it while it calls a\n * server function, middleware, an endpoint or a memo, and clears it as soon\n * as the call returns, which is at its first `await`. One request at a time\n * runs until an `await`, so it is never the event of another request.\n */\nlet current: RequestEvent | undefined;\n/** The results of server function calls of the render that runs now, by function and arguments. */\nlet currentCalls: Map<string, unknown> | undefined;\n\n/**\n * Runs a callback with an event, so `getEvent()` in its code before its first\n * `await` returns it. Returns what the callback returns, such as its promise.\n * `calls`, while a page renders, lets calls with the same arguments share a result.\n */\nexport function withEvent<T>(\n event: RequestEvent | undefined,\n callback: () => T,\n calls?: Map<string, unknown>,\n): T {\n const outer = current;\n const outerCalls = currentCalls;\n current = event;\n currentCalls = calls;\n try {\n return callback();\n } finally {\n current = outer;\n currentCalls = outerCalls;\n }\n}\n\n/**\n * Returns the event of the request that the server handles: in a server\n * function, middleware or an endpoint, or while a component renders.\n *\n * Call it before the first `await` of the function, and keep it in a\n * variable. After an `await`, other requests may have run, so it throws.\n *\n * ```ts\n * async function save(todo: Todo) {\n * 'use server';\n * const event = getEvent();\n * await db.save(todo);\n * event.setCookie('saved', todo.id);\n * }\n * ```\n */\nexport function getEvent(): RequestEvent {\n if (!current) {\n throw new Error(\n 'getEvent() works in server functions, middleware and endpoints before their first await, and while a component renders. Call it at the start of the function, keep the event in a variable, and pass it to helpers',\n );\n }\n return current;\n}\n\n/**\n * Wraps a server function, so its calls while a page renders share a result\n * when their arguments are the same. Calls from the browser, which are\n * requests of their own, always run, so a function that changes something\n * runs each time.\n */\n// oxlint-disable-next-line typescript/no-explicit-any -- Server functions take any arguments.\nexport function dedupe<F extends (...args: any[]) => unknown>(fn: F, id: string): F {\n const wrapper = ((...args: unknown[]) => {\n const cache = currentCalls;\n if (!cache) {\n return fn(...args);\n }\n let key: string;\n try {\n key = `${id} ${JSON.stringify(toJSON(args, { plugins, disabledFeatures }))}`;\n } catch {\n // Arguments that cannot be compared, such as a promise.\n return fn(...args);\n }\n if (!cache.has(key)) {\n cache.set(key, fn(...args));\n }\n return cache.get(key);\n }) as F;\n Object.defineProperty(wrapper, ORIGINAL, { value: fn });\n return wrapper;\n}\n\n/**\n * The function that `dedupe` wrapped, on its wrapper. A symbol of the\n * registry, so two copies of the runtime agree on it.\n */\nconst ORIGINAL = Symbol.for('brumate.original');\n\n/**\n * The server function itself, for a wrapper that `dedupe` made. `refresh`\n * and `$action` compare server functions, and the registry holds them unwrapped.\n */\nexport function unwrap<T>(fn: T): T {\n return ((fn as Record<symbol, T | undefined> | null)?.[ORIGINAL] ?? fn) as T;\n}\n\n/**\n * An error whose message reaches the client. A server function call that\n * throws it rejects with the message, and the response has its status.\n * Other errors reach the client as a generic message, so server details stay\n * on the server.\n */\nexport class ServerError extends Error {\n readonly status: number;\n\n constructor(message: string, options: { status?: number } = {}) {\n super(message);\n this.name = 'ServerError';\n this.status = options.status ?? 400;\n }\n}\n\n/** Thrown by `redirect`. */\nexport class Redirect extends Error {\n readonly location: string;\n readonly status: number;\n\n constructor(location: string, status: number) {\n super(`Redirect to ${location}`);\n this.name = 'Redirect';\n this.location = location;\n this.status = status;\n }\n}\n\n/**\n * Stops a server function and sends the browser to another page. While a\n * page renders, the error reaches the caller of `render`, which can\n * answer with a redirect.\n */\nexport function redirect(location: string, status = 303): never {\n throw new Redirect(location, status);\n}\n\nexport function isRedirect(error: unknown): error is Redirect {\n return error instanceof Redirect;\n}\n","import type { Component } from './server.ts';\n\n/** Imports the module of a route file. */\nexport type Loader = () => Promise<{ default: Component }>;\n\n/** Answers a request at the path of an endpoint, for one method. */\nexport type Handler = (\n request: Request,\n params: Record<string, string>,\n) => Response | Promise<Response>;\n\n/**\n * Runs before the routes of a folder. It answers the request itself, or\n * calls `next` for the answer of the route and returns it, changed or not.\n */\nexport type Middleware = (\n request: Request,\n next: () => Promise<Response>,\n) => Response | Promise<Response>;\n\n/** Imports `_middleware.ts`. */\nexport type MiddlewareLoader = () => Promise<{ middleware: Middleware }>;\n\n/** Imports an endpoint: a module that exports a handler for each method, such as `GET`. */\nexport type EndpointLoader = () => Promise<Partial<Record<string, Handler>>>;\n\n/** A folder of routes, as `virtual:brumate/routes` describes it. */\nexport interface RouteNode {\n /** `_layout.brm`. */\n layout?: Loader;\n /** `index.brm`, or the file of a segment, such as `about.brm`. */\n page?: Loader;\n /** `_default.brm`: what a slot renders when its routes do not match. */\n fallback?: Loader;\n /** `_error.brm`: renders when a route of the folder throws, or when no route matches. */\n error?: Loader;\n /** `_loading.brm`: shows while a route of the folder streams in. */\n loading?: Loader;\n /** `_middleware.ts`: runs before the routes of the folder. */\n middleware?: MiddlewareLoader;\n /** A `.ts` file at this path, such as `api/todos.ts`. */\n endpoint?: EndpointLoader;\n /** Folders and files with a fixed segment. */\n static?: Record<string, RouteNode>;\n /** `[name]`: one segment, read as `params.name`. */\n dynamic?: { name: string; node: RouteNode };\n /** `[...name]`: the rest of the path, read as `params.name`. */\n rest?: { name: string; node: RouteNode };\n /** `@name` folders: routes that render in the `name` slot of the layout. */\n slots?: Record<string, RouteNode>;\n}\n\n/** A matched route: the component to render, and what renders in its slots. */\nexport interface RouteView {\n load: Loader;\n /**\n * The file and the params that the view depends on, such as\n * `/todos/[id]/_layout {\"id\":\"3\"}`. Two pages with the same key for a\n * layout render the same layout, so the client can keep it.\n */\n key: string;\n /** `children` and the named slots of a layout. */\n slots: Record<string, RouteView>;\n /** `_loading.brm` of the folder: the view streams in, and this shows until then. */\n loading?: Loader;\n}\n\nexport interface RouteMatch {\n view: RouteView;\n params: Record<string, string>;\n /** The endpoint at the path, if the folder has one. */\n endpoint?: EndpointLoader;\n /** The middleware of the folders on the path, from the outside in. */\n middleware: MiddlewareLoader[];\n /**\n * Views that show an error in place of the route, from the innermost\n * `_error.brm` to the outermost. Each renders inside the layouts above it.\n * The error view is the `errorView` of its tree.\n */\n errors: RouteView[];\n}\n\n/** The error file and the slots that a layout renders around it. */\ninterface Wrapper {\n layout?: Loader;\n key: string;\n slots: Record<string, RouteView>;\n}\n\nfunction key(path: string, file: string, params: Record<string, string>): string {\n return `${path}/${file} ${JSON.stringify(params)}`;\n}\n\n/** Puts a view in the children slot of a layout, with its other slots. */\nfunction wrap(view: RouteView, wrapper: Wrapper): RouteView {\n return wrapper.layout\n ? { load: wrapper.layout, key: wrapper.key, slots: { ...wrapper.slots, children: view } }\n : view;\n}\n\n/** The slots of a layout other than `children`, each matched against the same path. */\nfunction namedSlots(\n node: RouteNode,\n segments: string[],\n params: Record<string, string>,\n path: string,\n): Record<string, RouteView> {\n const slots: Record<string, RouteView> = {};\n for (const [name, slot] of Object.entries(node.slots ?? {})) {\n const match = matchNode(slot, segments, params, `${path}/@${name}`);\n if (match) {\n slots[name] = match.view;\n } else if (slot.fallback) {\n slots[name] = {\n load: slot.fallback,\n key: key(`${path}/@${name}`, '_default', params),\n slots: {},\n };\n }\n }\n return slots;\n}\n\n/** The view of an `_error.brm`. Its component gets the error as a prop. */\nexport const ERROR_VIEW = '_error';\n\n/** `path` is the folders of `node` in the route files, such as `/todos/[id]`. */\nfunction matchNode(\n node: RouteNode,\n segments: string[],\n params: Record<string, string>,\n path = '',\n): RouteMatch | undefined {\n let inner: RouteMatch | undefined;\n if (segments.length === 0) {\n if (node.page || node.endpoint) {\n inner = {\n view: { load: node.page ?? missingPage, key: key(path, 'index', params), slots: {} },\n params,\n endpoint: node.endpoint,\n middleware: [],\n errors: [],\n };\n }\n } else {\n const [first, ...rest] = segments as [string, ...string[]];\n const fixed = node.static?.[first];\n inner = fixed && matchNode(fixed, rest, params, `${path}/${first}`);\n if (!inner && node.dynamic) {\n const { name } = node.dynamic;\n inner = matchNode(node.dynamic.node, rest, { ...params, [name]: first }, `${path}/[${name}]`);\n }\n if (!inner && node.rest) {\n const { name } = node.rest;\n inner = matchNode(\n node.rest.node,\n [],\n { ...params, [name]: segments.join('/') },\n `${path}/[...${name}]`,\n );\n }\n }\n if (!inner) {\n return undefined;\n }\n // The route of the folder streams in after its layout, with the loading file until then.\n const content: RouteView = node.loading ? { ...inner.view, loading: node.loading } : inner.view;\n const wrapper: Wrapper = {\n layout: node.layout,\n key: key(path, '_layout', params),\n slots: node.layout ? namedSlots(node, segments, params, path) : {},\n };\n const errors = inner.errors.map((view) => wrap(view, wrapper));\n if (node.error) {\n errors.push(wrap({ load: node.error, key: key(path, ERROR_VIEW, params), slots: {} }, wrapper));\n }\n return {\n view: wrap(content, wrapper),\n params: inner.params,\n endpoint: inner.endpoint,\n middleware: node.middleware ? [node.middleware, ...inner.middleware] : inner.middleware,\n errors,\n };\n}\n\n/** An endpoint without a page: a GET that it does not answer has no page either. */\nexport const missingPage: Loader = () => {\n throw new Error('This path has an endpoint and no page');\n};\n\n/** Finds the route for a path. */\nexport function matchRoute(tree: RouteNode, pathname: string): RouteMatch | undefined {\n const segments = pathname\n .split('/')\n .filter(Boolean)\n .map((segment) => decodeURIComponent(segment));\n return matchNode(tree, segments, {});\n}\n\n/**\n * The views for a path that no route matches: the `_error.brm` of the\n * root, inside the root layout, and the root middleware.\n */\nexport function notFound(tree: RouteNode): Pick<RouteMatch, 'errors' | 'middleware'> {\n const wrapper: Wrapper = {\n layout: tree.layout,\n key: key('', '_layout', {}),\n slots: tree.layout ? namedSlots(tree, [], {}, '') : {},\n };\n return {\n errors: tree.error\n ? [wrap({ load: tree.error, key: key('', ERROR_VIEW, {}), slots: {} }, wrapper)]\n : [],\n middleware: tree.middleware ? [tree.middleware] : [],\n };\n}\n","import { fromJSON, toCrossJSONStream } from 'seroval';\nimport type { SerovalJSON, SerovalNode } from 'seroval';\nimport {\n VOID_ELEMENTS,\n actionAttributes,\n escape,\n escapeAttribute,\n insertValue,\n isRaw,\n rawHTML,\n spread,\n styleElement,\n} from './html.ts';\nimport type { Raw } from './html.ts';\nimport {\n ElementReference,\n FunctionReference,\n disabledFeatures,\n Upload,\n functionReferences,\n isAsyncIterable,\n plugins,\n replaceDeep,\n} from './shared.ts';\nimport { STREAM_TYPE, toChunkStream } from './stream.ts';\nimport type { PageState, ScopeState } from './shared.ts';\nimport { Redirect, RequestEvent, ServerError, isRedirect, unwrap, withEvent } from './request.ts';\nimport type { Context as ContextValue } from './context.ts';\n\nexport { affix, attribute, escape, escapeAttribute, raw, spread, vars } from './html.ts';\nexport type { Raw } from './html.ts';\nexport { produce } from './produce.ts';\nexport { createContext } from './context.ts';\nimport { matchRoute, missingPage, notFound } from './router.ts';\nimport type { MiddlewareLoader, RouteMatch, RouteNode, RouteView } from './router.ts';\nexport { matchRoute } from './router.ts';\nexport type {\n EndpointLoader,\n Handler,\n Loader,\n Middleware,\n MiddlewareLoader,\n RouteMatch,\n RouteNode,\n RouteView,\n} from './router.ts';\nexport {\n RequestEvent,\n ServerError,\n dedupe,\n getEvent,\n isRedirect,\n redirect,\n withEvent,\n} from './request.ts';\nexport type { Redirect } from './request.ts';\nexport { createSession, parseCookies, serializeCookie, toNodeHeaders } from './cookies.ts';\nexport type { CookieOptions, Session, SessionOptions } from './cookies.ts';\nexport { ElementReference, FunctionReference };\nexport type { PageState, ScopeState };\n\n/** A `#loading` body that renders after the rest of the page. */\ninterface Boundary {\n id: number;\n /** Resolves to the body's markup, and its scopes in `ctx.state`. */\n render: Promise<{ html: string; ctx: Context }>;\n}\n\n/**\n * Tracks the scopes of one render. A `#loading` body renders in a child\n * context, so its scopes are written with its markup.\n */\nexport class Context {\n readonly state: PageState = {};\n private readonly root: Context;\n private nextScope = 0;\n private nextBoundary = 0;\n private readonly boundaries: Boundary[] = [];\n private readonly styles = new Set<string>();\n /** Markup of `#portal` blocks, written at the end of the page. */\n readonly portals: string[] = [];\n /** Markup of `#head` blocks. */\n private readonly heads: string[] = [];\n private pageTitle: string | undefined;\n private onBoundary: ((boundary: Boundary) => void) | undefined;\n /** The scope tree of the whole page, for finding contexts across `#loading` bodies. */\n private readonly tree = new Map<number, { parent?: number; values?: Map<string, unknown> }>();\n /** The scope that renders the next component, which becomes its owner. */\n private owner: number | undefined;\n\n /** The URL prefix of server function calls. */\n private rpcPrefix = '/_brumate';\n /** The names of the slots of each scope, so an error can name a value that cannot be sent. */\n readonly slotNames: Map<number, string[]> = new Map();\n\n /** Results of server functions that a form posted to this page, for `$action`. */\n actions: Map<unknown, unknown> = new Map();\n /** The request of the page, when it renders with one. */\n event: RequestEvent | undefined;\n /** Results of server function calls in this render, so the same call runs once. */\n readonly calls: Map<string, unknown> = new Map();\n\n /** The event of the page, for `getEvent()` in a component, which the compiler rewrites to this. */\n getEvent(): RequestEvent {\n const event = this.root.event;\n if (!event) {\n throw new Error('getEvent() works while a page renders with a request, such as in a route');\n }\n return event;\n }\n\n /** Runs code of the render with its event and its call results, such as a memo's compute. */\n run<T>(callback: () => T): T {\n return withEvent(this.root.event, callback, this.root.calls);\n }\n\n /** The result of a server function that a form posted to this page. */\n actionResult(fn: unknown): unknown {\n return this.root.actions.get(unwrap(fn));\n }\n\n constructor(root?: Context, rpc?: string, base = 0) {\n this.root = root ?? this;\n if (rpc) {\n this.rpcPrefix = rpc;\n }\n this.nextScope = base;\n this.nextBoundary = base;\n }\n\n /** A number above every scope and boundary ID so far, so a later render can start there. */\n next(): number {\n return Math.max(this.root.nextScope, this.root.nextBoundary);\n }\n\n /** Returns the URL prefix of server function calls. */\n rpc(): string {\n return this.root.rpcPrefix;\n }\n\n /**\n * Returns a new scope ID. `kind` is the scope's ID in the compiled\n * component, `parent` is the scope that contains it, and `module` is the\n * component ID of a component's root scope.\n */\n scope(kind: number, parent?: number, module?: string): number {\n const root = this.root;\n const id = root.nextScope++;\n const record = this.record(id);\n record.k = kind;\n if (parent !== undefined) {\n record.p = parent;\n }\n let up = parent;\n if (module !== undefined) {\n record.m = module;\n // A component's root scope links to the scope that rendered it.\n if (root.owner !== undefined) {\n record.o = root.owner;\n up = root.owner;\n root.owner = undefined;\n }\n }\n root.tree.set(id, { parent: up });\n return id;\n }\n\n /** The ID that `$id()` makes: the scope's ID and the position of the call. */\n id(scope: number, index: number): string {\n return `b${scope}-${index}`;\n }\n\n /** Sets the owner of the next component's root scope. */\n own(scope: number): void {\n this.root.owner = scope;\n }\n\n /** Provides a value of a context to the scopes inside `scope`. */\n provide<T>(context: ContextValue<T>, value: T, scope: number): void {\n const node = this.root.tree.get(scope)!;\n node.values ??= new Map();\n node.values.set(context.key, value);\n const record = this.record(scope);\n record.v ??= {};\n record.v[context.key] = value;\n }\n\n /**\n * Reads a context from the nearest scope that provides it, starting at\n * `scope`. With `slot`, records which slot holds it, so the client can\n * update it when the provided value changes.\n */\n consume<T>(context: ContextValue<T>, scope: number, slot?: number): T {\n if (slot !== undefined) {\n const record = this.record(scope);\n record.x ??= {};\n record.x[context.key] = slot;\n }\n for (let id: number | undefined = scope; id !== undefined;) {\n const node = this.root.tree.get(id);\n if (node?.values?.has(context.key)) {\n return node.values.get(context.key) as T;\n }\n id = node?.parent;\n }\n return context.defaultValue;\n }\n\n /** The ID that the next call to `scope()` returns. */\n peek(): number {\n return this.root.nextScope;\n }\n\n private record(scope: number): ScopeState {\n this.state[scope] ??= {};\n return this.state[scope];\n }\n\n slots(scope: number, values: unknown[], names?: string[]): void {\n this.record(scope).s = values;\n if (names) {\n this.root.slotNames.set(scope, names);\n }\n }\n\n /** Records the item of a list that can change on the client. */\n item(scope: number, value: unknown): void {\n this.record(scope).i = value;\n }\n\n /** Records the scope of a child component at an anchor of its parent. */\n link(scope: number, anchor: number, child: number): void {\n const record = this.record(scope);\n record.c ??= {};\n record.c[anchor] = child;\n }\n\n /** Returns the reference that a `ref` signal holds on the server. */\n element(scope: number, anchor: number): ElementReference {\n return new ElementReference(scope, anchor);\n }\n\n /** Marks a function as a client function, so it serializes as a reference. */\n fn<T>(value: T, ref: string, scope: number): T {\n if (typeof value === 'function') {\n functionReferences.set(value, new FunctionReference(ref, scope));\n }\n return value;\n }\n\n /** Returns a component's stylesheet the first time the page renders the component. */\n style(id: string, css: string): string {\n if (this.root.styles.has(id)) {\n return '';\n }\n this.root.styles.add(id);\n return styleElement(id, css);\n }\n\n /** Adds the markup of a `#head` block. */\n head(html: string): void {\n // After the first render, the head has been sent, so a `#loading` body sends its own.\n (this.root.sent ? this : this.root).heads.push(html);\n }\n\n /** Sets the title of the page. The last call wins. */\n title(value: unknown): void {\n (this.root.sent ? this : this.root).pageTitle =\n value === null || value === undefined ? '' : String(value);\n }\n\n /** True once the first render is done, and its head is about to be sent. */\n private sent = false;\n\n /** Marks the first render as done. Head markup after it streams with its `#loading` body. */\n send(): void {\n this.root.sent = true;\n }\n\n /**\n * The head markup and the title that a `#loading` body set, after the\n * head was sent. The title is undefined if the body set none.\n */\n lateHead(): { html: string; title: string | undefined } {\n return { html: this.heads.join(''), title: this.pageTitle };\n }\n\n /** The markup for the document's head: the title and the `#head` blocks. */\n headHTML(): string {\n const title =\n this.root.pageTitle === undefined ? '' : `<title>${escape(this.root.pageTitle)}</title>`;\n return title + this.root.heads.join('');\n }\n\n /** Adds the markup of a `#portal` block, which goes after the rest of the page. */\n portal(html: string): void {\n this.portals.push(html);\n }\n\n /** Returns the ID of a new `#loading` boundary. */\n boundary(): number {\n return this.root.nextBoundary++;\n }\n\n /** Renders a `#loading` body after the rest of the page, in its own context. */\n defer(id: number, renderBody: (ctx: Context) => Promise<string>): void {\n const child = new Context(this.root);\n const boundary: Boundary = {\n id,\n render: renderBody(child).then((html) => ({ html, ctx: child })),\n };\n // The page does not wait for it, so a failure must not be unhandled.\n boundary.render.catch(() => {});\n const root = this.root;\n if (root.onBoundary) {\n root.onBoundary(boundary);\n } else {\n root.boundaries.push(boundary);\n }\n }\n\n /** Receives every boundary, including those registered before this call. */\n watch(onBoundary: (boundary: Boundary) => void): void {\n this.onBoundary = onBoundary;\n for (const boundary of this.boundaries.splice(0)) {\n onBoundary(boundary);\n }\n }\n}\n\n/** Thrown when code reads a memo whose value is still loading. It carries the load. */\nexport class NotReady extends Error {\n readonly source: Promise<unknown>;\n\n constructor(source: Promise<unknown>) {\n super('The value is still loading');\n this.name = 'NotReady';\n this.source = source;\n }\n}\n\n/** A memo on the server. It computes on its first read, so nothing waits for a memo that nothing reads. */\nexport interface Memo<T = unknown> {\n compute: () => T;\n /** The render, whose event server functions that the compute calls read. */\n ctx?: Context;\n state: 'idle' | 'pending' | 'done' | 'failed';\n value?: unknown;\n error?: unknown;\n load?: Promise<unknown>;\n}\n\n/** Declares a memo. Its value is computed when it is first read. */\nexport function memo<T>(compute: () => T, ctx?: Context): Memo<T> {\n return { compute, ctx, state: 'idle' };\n}\n\n/**\n * Reads a memo. A value that is still loading throws `NotReady` with its\n * load, and a memo that read such a value stays unread, so it computes\n * again when it is read after the load settles.\n */\n// oxlint-disable-next-line typescript/no-explicit-any -- Memos hold any value.\nexport function read(node: Memo): any {\n if (node.state === 'done') {\n return node.value;\n }\n if (node.state === 'failed') {\n throw node.error;\n }\n if (node.state === 'pending') {\n throw new NotReady(node.load!);\n }\n let value: unknown;\n try {\n // Server functions that it calls read the event of the page before their first await.\n value = node.ctx ? node.ctx.run(node.compute) : node.compute();\n } catch (error) {\n if (!(error instanceof NotReady)) {\n node.state = 'failed';\n node.error = error;\n }\n throw error;\n }\n if (\n value !== null &&\n typeof value === 'object' &&\n (typeof (value as PromiseLike<unknown>).then === 'function' || isAsyncIterable(value))\n ) {\n node.state = 'pending';\n node.load = Promise.resolve(value)\n .then(firstValue)\n .then(\n (result) => {\n node.state = 'done';\n node.value = result;\n },\n (error: unknown) => {\n node.state = 'failed';\n node.error = error;\n },\n );\n throw new NotReady(node.load);\n }\n node.state = 'done';\n node.value = value;\n return value;\n}\n\n/**\n * The first value of an async iterable, such as a server function that\n * streams. A page renders once, so the server stops reading after it. Other\n * values are themselves.\n */\nasync function firstValue(value: unknown): Promise<unknown> {\n if (!isAsyncIterable(value)) {\n return value;\n }\n const iterator = value[Symbol.asyncIterator]();\n const first = await iterator.next();\n await iterator.return?.();\n return first.value;\n}\n\n/** Waits for the value of a memo, through every load it reads. */\nexport async function wait(node: Memo): Promise<unknown> {\n for (;;) {\n try {\n return read(node);\n } catch (error) {\n if (!(error instanceof NotReady)) {\n throw error;\n }\n // oxlint-disable-next-line no-await-in-loop -- Each load can reveal another one.\n await error.source.catch(() => {});\n }\n }\n}\n\nconst LAZY: unique symbol = Symbol.for('brumate.lazy');\n\n/** Markup that renders where it is inserted, so it can read the contexts there. */\nexport interface Lazy {\n [LAZY]: (ctx: Context, scope: number | undefined) => Promise<string>;\n}\n\n/** Makes markup that renders where it is inserted, such as the children of a layout. */\nexport function lazy(renderAt: (ctx: Context, scope: number | undefined) => Promise<string>): Lazy {\n return { [LAZY]: renderAt };\n}\n\nfunction isLazy(value: unknown): value is Lazy {\n return typeof value === 'object' && value !== null && LAZY in value;\n}\n\n/** Renders the attributes of a form or button that posts to a server function. */\nexport function action(\n ctx: Context,\n name: string,\n id: string,\n method?: string,\n result?: string,\n): string {\n return actionAttributes(ctx.rpc(), name, id, method, result);\n}\n\n/**\n * The result of a server function that a form posted to this page, for\n * `$action`, or undefined when the page was not rendered for a post.\n */\nexport function actionResult(ctx: Context, fn: unknown): unknown {\n return ctx.actionResult(fn);\n}\n\n/**\n * Renders a value inserted in markup. `ctx` and `scope` are where it is\n * inserted, for markup that renders there.\n */\nexport async function insert(value: unknown, ctx?: Context, scope?: number): Promise<string> {\n const resolved = await value;\n if (isLazy(resolved) && ctx) {\n return resolved[LAZY](ctx, scope);\n }\n if (Array.isArray(resolved)) {\n const parts = await Promise.all(resolved.map((item) => insert(item, ctx, scope)));\n return parts.join('');\n }\n return insertValue(resolved);\n}\n\n// oxlint-disable-next-line typescript/no-explicit-any -- Components take any props.\nexport type Component<P = any> = (props: P, ctx: Context) => Promise<string>;\n\n/**\n * Renders a child component. With `scope` and `anchor`, records the child's\n * scope so the parent can update its props on the client.\n */\nexport async function component<P>(\n Child: Component<P>,\n props: P,\n ctx: Context,\n scope?: number,\n anchor?: number,\n): Promise<string> {\n if (scope !== undefined && anchor !== undefined) {\n ctx.link(scope, anchor, ctx.peek());\n }\n if (scope !== undefined) {\n ctx.own(scope);\n }\n return Child(props, ctx);\n}\n\n/** Renders a dynamic tag, which can be an element name or a component. */\nexport async function dynamic(\n tag: string | Component,\n attributes: Record<string, unknown>,\n children: Raw | undefined,\n ctx: Context,\n scope?: number,\n): Promise<string> {\n if (typeof tag === 'function') {\n return component(tag, children ? { ...attributes, children } : attributes, ctx, scope);\n }\n const open = `<${tag}${spread(attributes)}>`;\n if (VOID_ELEMENTS.has(tag)) {\n return open;\n }\n return `${open}${children && isRaw(children) ? rawHTML(children) : ''}</${tag}>`;\n}\n\n/**\n * Serializes the page state as seroval cross-reference JSON records. The\n * first record holds the state, and each later record settles a promise in\n * it. `onRecord` receives each record as soon as it is ready. The promise\n * resolves when every promise in the state has settled.\n */\n/** True when `value` is `target`, or holds it in plain objects, arrays, maps or sets. */\nfunction holds(value: unknown, target: unknown, seen = new Set<unknown>()): boolean {\n if (value === target) {\n return true;\n }\n if (typeof value !== 'object' || value === null || seen.has(value)) {\n return false;\n }\n seen.add(value);\n const items =\n value instanceof Map\n ? [...value.keys(), ...value.values()]\n : value instanceof Set\n ? [...value]\n : Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype\n ? Object.values(value)\n : [];\n return items.some((item) => holds(item, target, seen));\n}\n\n/**\n * The error of a value in the state of a page that cannot be sent to the\n * browser, which names the value and its component.\n */\nfunction unsendable(error: unknown, ctx: Context): Error {\n const target = (error as { value?: unknown }).value;\n if (target === undefined) {\n return error instanceof Error ? error : new Error(String(error));\n }\n for (const [id, record] of Object.entries(ctx.state)) {\n const index = (record.s ?? []).findIndex((value) => holds(value, target));\n if (index === -1) {\n continue;\n }\n let owner: ScopeState | undefined = record;\n while (owner && owner.m === undefined && owner.p !== undefined) {\n owner = ctx.state[owner.p];\n }\n const name = ctx.slotNames.get(Number(id))?.[index] ?? `slot ${index}`;\n const kind = (target as object)?.constructor?.name ?? typeof target;\n return new Error(\n `The value of \"${name}\" in ${owner?.m ?? 'a component'} holds a ${kind}, which cannot be sent to the browser, and code that runs in the browser reads it. Use it in a server function, or create it in the browser, such as in $client.`,\n { cause: error },\n );\n }\n return error instanceof Error ? error : new Error(String(error));\n}\n\nexport function streamState(\n state: PageState,\n onRecord: (record: SerovalNode) => void,\n): Promise<void> {\n return new Promise((resolve, reject) => {\n toCrossJSONStream(state, {\n plugins,\n disabledFeatures,\n onParse: (record) => onRecord(record),\n onError: reject,\n onDone: resolve,\n });\n });\n}\n\n/**\n * Returns the script for one state record. `scopes` marks a record that\n * holds scopes, as opposed to one that settles a promise.\n */\n/**\n * Returns the script of a state record. `scopes` marks a record with scopes.\n * `next` is above every ID so far, and `route` names the route of the page.\n */\nexport function stateScript(\n record: SerovalNode,\n scopes = false,\n attributes: { next?: number; route?: string; root?: number } = {},\n): string {\n const json = JSON.stringify(record).replace(/</g, '\\\\u003c');\n let extra = scopes ? ' data-scopes' : '';\n if (attributes.next !== undefined) {\n extra += ` data-next=\"${attributes.next}\"`;\n }\n // Records of a render that starts above 0 name it, so their references stay apart from other renders.\n if (attributes.root) {\n extra += ` data-root=\"${attributes.root}\"`;\n }\n if (attributes.route !== undefined) {\n extra += ` data-route=\"${escapeAttribute(attributes.route)}\"`;\n }\n return `<script type=\"brumate/state\"${extra}>${json}</script>`;\n}\n\n// Moves the head markup of a `#loading` body into the head, and sets the title.\nconst HEAD = `function $bH(i,t){var e=document.querySelector('template[data-h=\"'+i+'\"]');e&&(document.head.append(e.content),e.remove());t!=null&&(document.title=t)}`;\n\n// Moves a `#loading` body from its <template> into the page, in place of the fallback.\nconst SWAP = `function $bS(i){var t=document.querySelector('template[data-l=\"'+i+'\"]'),w=document.createTreeWalker(document.body,128),s,n,d=0;while(n=w.nextNode())if(n.data==='l'+i){s=n;break}if(!s||!t)return;var p=s.parentNode;for(n=s.nextSibling;n;){if(n.nodeType===8){if(n.data==='/l'){if(!d)break;d--}else if(/^l\\\\d/.test(n.data))d++}var x=n.nextSibling;p.removeChild(n);n=x}p.insertBefore(t.content,s);p.removeChild(s);n&&p.removeChild(n);t.remove()}`;\n\nexport interface RenderResult {\n /** The markup. A `#loading` body that is not ready shows its fallback. */\n html: string;\n /** The script that holds the page state. */\n state: string;\n /**\n * Markup to write after the page, as it is ready: the bodies of\n * `#loading` blocks, and the state records that settle promises.\n */\n pending: AsyncIterable<string>;\n /** Headers that the page set while it rendered, such as cookies. */\n headers: Headers;\n /** The status that `setStatus` set while the page rendered, or 200. */\n status: number;\n /**\n * A number above every ID of this render, once its `#loading` bodies have\n * rendered. Another root on the same page passes it as `base`.\n */\n next: () => number;\n /** Markup for the document's head: the `$title` and the `#head` blocks. */\n head: string;\n}\n\n/** An async iterable that a producer pushes into. */\nfunction createQueue<T>(): {\n push: (item: T) => void;\n close: () => void;\n fail: (error: unknown) => void;\n iterable: AsyncIterable<T>;\n} {\n const items: T[] = [];\n let wake: (() => void) | undefined;\n let closed = false;\n let failure: { error: unknown } | undefined;\n const notify = (): void => {\n wake?.();\n wake = undefined;\n };\n return {\n push(item) {\n items.push(item);\n notify();\n },\n close() {\n closed = true;\n notify();\n },\n fail(error) {\n failure = { error };\n notify();\n },\n iterable: {\n async *[Symbol.asyncIterator]() {\n for (;;) {\n if (items.length > 0) {\n yield items.shift()!;\n } else if (failure) {\n throw failure.error;\n } else if (closed) {\n return;\n } else {\n // oxlint-disable-next-line no-await-in-loop -- Each wait is for the next item.\n await new Promise<void>((resolve) => {\n wake = resolve;\n });\n }\n }\n },\n },\n };\n}\n\nexport interface RenderOptions {\n /** The URL prefix of server function calls, for forms that post to one. Defaults to `/_brumate`. */\n rpc?: string;\n /**\n * The first scope and boundary ID. A page that the client loads in place\n * of another starts above the IDs of the page it keeps parts of.\n */\n base?: number;\n /** Names the route of the page, so the client knows which layouts it can keep. */\n route?: string;\n /** Results of server functions that a form posted to this page, by function, for `$action`. */\n actions?: Map<unknown, unknown>;\n /**\n * The request of the page. Components and the server functions that their\n * memos call read it with `getEvent()`. Headers and cookies that they set\n * are in the `headers` that `render` returns.\n */\n request?: Request;\n /** The event of the request, in place of `request`, such as one that middleware already set cookies on. */\n event?: RequestEvent;\n /**\n * A Content Security Policy nonce for the inline scripts that swap in\n * `#loading` bodies. State scripts need none, because they do not run.\n */\n nonce?: string;\n}\n\n/**\n * Renders the parts of a page. It returns as soon as the markup is rendered.\n * `#loading` bodies and promises in the state do not hold it up: they come\n * later, from `pending`. `renderToStream` puts the parts together. Use this\n * directly to send the response headers that server functions set before\n * the stream starts.\n */\nexport async function render<P>(\n Root: Component<P>,\n props: P,\n options: RenderOptions = {},\n): Promise<RenderResult> {\n const scriptTag =\n options.nonce === undefined ? '<script>' : `<script nonce=\"${escapeAttribute(options.nonce)}\">`;\n const ctx = new Context(undefined, options.rpc, options.base);\n if (options.actions) {\n ctx.actions = options.actions;\n }\n const event = options.event ?? (options.request ? new RequestEvent(options.request) : undefined);\n ctx.event = event;\n // The first part of each component runs with the event, and so do memos, which the compiler gives `$$ctx`.\n const rendered = await ctx.run(() => Root(props, ctx));\n ctx.send();\n const html = beforeBodyEnd(rendered, ctx.portals.join(''));\n const queue = createQueue<string>();\n // Records share references, so later records can point into earlier ones.\n const refs = new Map<unknown, number>();\n let open = 0;\n let swap = false;\n let headSwap = false;\n const finish = (): void => {\n open--;\n if (open === 0) {\n queue.close();\n }\n };\n const serialize = (\n state: PageState,\n onScopes: (script: string) => void,\n route?: string,\n onError: (error: unknown) => void = queue.fail,\n ): void => {\n open++;\n toCrossJSONStream(state, {\n plugins,\n disabledFeatures,\n refs,\n onParse(record, initial) {\n if (initial) {\n onScopes(stateScript(record, true, { next: ctx.next(), route, root: options.base }));\n } else {\n queue.push(stateScript(record, false, { root: options.base }));\n }\n },\n onError,\n onDone: finish,\n });\n };\n\n ctx.watch((boundary) => {\n open++;\n boundary.render.then(\n (result) => {\n serialize(result.ctx.state, (script) => {\n let call = `${swap ? '' : SWAP}$bS(${boundary.id})`;\n swap = true;\n const late = result.ctx.lateHead();\n let head = '';\n if (late.html || late.title !== undefined) {\n head = `<template data-h=\"${boundary.id}\">${late.html}</template>`;\n const title =\n late.title === undefined\n ? ''\n : `,${JSON.stringify(late.title).replace(/</g, '\\\\u003c')}`;\n call += `;${headSwap ? '' : HEAD}$bH(${boundary.id}${title})`;\n headSwap = true;\n }\n queue.push(\n `<template data-l=\"${boundary.id}\">${result.html}</template>${head}${result.ctx.portals.join('')}${script}${scriptTag}${call}</script>`,\n );\n });\n finish();\n },\n (error: unknown) => {\n // The fallback stays in the page.\n console.error(error);\n finish();\n },\n );\n });\n\n let state = '';\n // The state of the page is serialized before this returns, so a value that cannot be sent\n // fails the render here, with its name, instead of leaving the page without its state.\n let failure: unknown;\n serialize(\n ctx.state,\n (script) => {\n state = script;\n },\n options.route,\n (error) => {\n failure = error;\n },\n );\n if (failure !== undefined) {\n throw unsendable(failure, ctx);\n }\n return {\n html,\n state,\n pending: queue.iterable,\n headers: event?.headers ?? new Headers(),\n status: event?.status ?? 200,\n next: () => ctx.next(),\n head: ctx.headHTML(),\n };\n}\n\nexport interface DocumentOptions extends RenderOptions {\n /**\n * Markup before the component, for a component that does not render\n * `<html>`. A function receives the markup for the document's head.\n */\n start?: string | ((head: string) => string);\n /** Markup for the head, before the head of the components, such as the `<link>` of a CSS file. */\n head?: string;\n /**\n * Markup right after the page state, such as the client entry. Make\n * module scripts `async`, so they run before the stream ends.\n */\n scripts?: string;\n /** Markup after the first render, for a component that does not render `<html>`. */\n end?: string;\n}\n\nexport type StreamOptions = DocumentOptions;\n\nconst HTML = /<html[\\s>]/i;\n\n/** Inserts markup before `</body>`, or at the end if there is none. */\nfunction beforeBodyEnd(html: string, content: string): string {\n if (!content) {\n return html;\n }\n const index = html.toLowerCase().lastIndexOf('</body>');\n return index === -1 ? html + content : html.slice(0, index) + content + html.slice(index);\n}\n\n/**\n * Builds the first chunk of a page: the whole rendered document, with the\n * page state and the scripts. A component that renders `<html>` gets the\n * doctype, its head before `</head>`, and the state and scripts before\n * `</body>`. Markup that resolves later is written after it.\n */\nfunction firstRender(\n html: string,\n componentHead: string,\n state: string,\n options: DocumentOptions,\n): string {\n const head = (options.head ?? '') + componentHead;\n const tail = state + (options.scripts ?? '');\n const match = HTML.exec(html);\n if (!match) {\n const start = typeof options.start === 'function' ? options.start(head) : (options.start ?? '');\n return start + html + tail + (options.end ?? '');\n }\n // Markup before <html>, such as the stylesheet of the root component, belongs in the head.\n const headContent = html.slice(0, match.index) + head;\n let page = html.slice(match.index);\n const lower = page.toLowerCase();\n const headEnd = lower.indexOf('</head>');\n if (headEnd !== -1) {\n page = page.slice(0, headEnd) + headContent + page.slice(headEnd);\n } else if (headContent) {\n const bodyStart = lower.search(/<body[\\s>]/);\n const at = bodyStart === -1 ? page.indexOf('>') + 1 : bodyStart;\n page = `${page.slice(0, at)}<head>${headContent}</head>${page.slice(at)}`;\n }\n return `<!doctype html>${beforeBodyEnd(page, tail)}`;\n}\n\n/**\n * Renders a component as a stream. The first chunk is the whole first\n * render, sent as soon as it is ready. Each `#loading` body and each state\n * record that settles a promise follows it as it resolves. A component that\n * renders `<html>` gets the doctype and its head.\n */\nexport function renderToStream<P>(\n Root: Component<P>,\n props: P,\n options: DocumentOptions = {},\n): ReadableStream<string> {\n return new ReadableStream<string>({\n async start(controller) {\n try {\n await writeParts(await render(Root, props, options), options, controller);\n } catch (error) {\n controller.error(error);\n }\n },\n });\n}\n\n/** Streams the parts of a page from `render`: the first render whole, then what resolves later. */\nexport function streamParts(\n parts: RenderResult,\n options: DocumentOptions = {},\n): ReadableStream<string> {\n return new ReadableStream<string>({\n async start(controller) {\n try {\n await writeParts(parts, options, controller);\n } catch (error) {\n controller.error(error);\n }\n },\n });\n}\n\nasync function writeParts(\n parts: RenderResult,\n options: DocumentOptions,\n controller: ReadableStreamDefaultController<string>,\n): Promise<void> {\n controller.enqueue(firstRender(parts.html, parts.head, parts.state, options));\n for await (const chunk of parts.pending) {\n controller.enqueue(chunk);\n }\n controller.close();\n}\n\n/** True for a request that a `<form>` sent, without client code. */\nfunction isFormPost(request: Request): boolean {\n const type = request.headers.get('content-type') ?? '';\n return (\n type.startsWith('application/x-www-form-urlencoded') || type.startsWith('multipart/form-data')\n );\n}\n\n/**\n * Calls a server function with the data of a form that the browser sent, and\n * sends the browser back to the page with a redirect. A `redirect` in the\n * function sends it there instead. An error answers with a short text page,\n * because there is no page to report it in.\n */\nasync function handleForm(\n // oxlint-disable-next-line typescript/no-explicit-any -- Server functions take any arguments.\n fn: (...args: any[]) => unknown,\n request: Request,\n event: RequestEvent,\n): Promise<Response> {\n const { headers } = event;\n const back = request.headers.get('referer') ?? '/';\n try {\n const form = await request.formData();\n await withEvent(event, () => fn(form));\n headers.set('location', back);\n return new Response(null, { status: 303, headers });\n } catch (error) {\n if (error instanceof Redirect) {\n headers.set('location', error.location);\n return new Response(null, { status: error.status, headers });\n }\n const known = error instanceof ServerError;\n if (!known) {\n console.error(error);\n }\n headers.set('content-type', 'text/plain; charset=utf-8');\n const message = known ? error.message : 'The server function failed';\n return new Response(message, { status: known ? error.status : 500, headers });\n }\n}\n\n/**\n * The arguments of a call. They come as seroval JSON, or as multipart form\n * data when they hold files: the JSON in `args`, and each file in\n * `file<index>`, where an `Upload` stands in the JSON.\n */\nasync function readArgs(request: Request): Promise<unknown[]> {\n if (!request.headers.has('x-brumate-args')) {\n return fromJSON<unknown[]>((await request.json()) as SerovalJSON, {\n plugins,\n disabledFeatures,\n });\n }\n const form = await request.formData();\n const args = fromJSON<unknown[]>(JSON.parse(String(form.get('args'))) as SerovalJSON, {\n plugins,\n disabledFeatures,\n });\n return replaceDeep(args, (value) =>\n value instanceof Upload ? (form.get(`file${value.index}`) ?? undefined) : undefined,\n ) as unknown[];\n}\n\nexport interface RequestOptions {\n /**\n * Other origins that may call server functions and post forms to them,\n * such as `https://app.example.com`. The origin of the request is always\n * allowed.\n */\n origins?: string[];\n}\n\n/**\n * True when a request comes from a page of another site. Server function\n * calls and form posts send the cookies of the user, so another site must\n * not be able to make them.\n *\n * The browser sends `Origin` with every call and post. Without it, an older\n * browser's `Sec-Fetch-Site` decides. A request with neither does not come\n * from a page in a browser, so it is allowed.\n */\nexport function isCrossSite(request: Request, options: RequestOptions = {}): boolean {\n const origin = request.headers.get('origin');\n if (origin === null) {\n const site = request.headers.get('sec-fetch-site');\n return site === 'cross-site' || site === 'same-site';\n }\n if (origin === 'null') {\n return true;\n }\n if (options.origins?.includes(origin)) {\n return false;\n }\n let host: string;\n try {\n host = new URL(origin).host;\n } catch {\n return true;\n }\n // The server can see itself under another name than the page, such as\n // `localhost` behind a proxy, so the host headers count too.\n return ![\n new URL(request.url).host,\n request.headers.get('host'),\n request.headers.get('x-forwarded-host'),\n ].includes(host);\n}\n\n/**\n * Answers a server function call from `brumate/client`. Returns undefined\n * when the request is not a call, so other handlers can answer it. Server\n * functions read the request with `getEvent()`. A call from a page of\n * another site answers 403. See `isCrossSite`.\n */\nexport async function handleRequest(\n // oxlint-disable-next-line typescript/no-explicit-any -- Server functions take any arguments.\n functions: Record<string, (...args: any[]) => unknown>,\n request: Request,\n prefix = '/_brumate',\n options: RequestOptions = {},\n): Promise<Response | undefined> {\n const url = new URL(request.url);\n if (request.method !== 'POST' || !url.pathname.startsWith(`${prefix}/`)) {\n return undefined;\n }\n if (isCrossSite(request, options)) {\n return new Response('Calls from other sites are not allowed', { status: 403 });\n }\n const id = decodeURIComponent(url.pathname.slice(prefix.length + 1));\n if (!functions[id]) {\n return new Response(`Unknown server function \"${id}\"`, { status: 404 });\n }\n const event = new RequestEvent(request);\n const fn = functions[id];\n // The function runs with its event, so `getEvent()` before its first await returns it.\n const invoke = (args: unknown[]): unknown => withEvent(event, () => fn(...args));\n // A call with files sends its arguments as form data, with this header.\n const call = request.headers.has('x-brumate-args');\n // The loader sends a form of an `$action` with this header, and wants the result, not a page.\n if (isFormPost(request) && !call && !request.headers.has('x-brumate-result')) {\n return handleForm(fn, request, event);\n }\n if (isFormPost(request) && !call) {\n const form = await request.formData();\n return answerCall(functions, event, async () => invoke([form]));\n }\n // Arguments that fail to read, such as a regular expression, answer as an error of the call.\n return answerCall(functions, event, async () => invoke(await readArgs(request)));\n}\n\n/**\n * Answers a server function call with its result as a stream of seroval\n * chunks, so promises and async iterables in it stream as they settle. A\n * redirect is sent as a header, so the client can follow it. An error\n * answers with a message that the client throws.\n */\nasync function answerCall(\n // oxlint-disable-next-line typescript/no-explicit-any -- Server functions take any arguments.\n functions: Record<string, (...args: any[]) => unknown>,\n event: RequestEvent,\n run: () => Promise<unknown>,\n): Promise<Response> {\n const { headers } = event;\n try {\n const result = await run();\n // The client loads again the memos that call the server functions that `refresh` named.\n const refreshed = Object.keys(functions).filter((key) =>\n event.refreshed?.has(unwrap(functions[key])),\n );\n if (refreshed.length > 0) {\n headers.set('x-brumate-refresh', refreshed.join(','));\n }\n headers.set('content-type', STREAM_TYPE);\n return new Response(toChunkStream(result), { headers });\n } catch (error) {\n if (error instanceof Redirect) {\n headers.set('x-brumate-redirect', error.location);\n return new Response(null, { status: 204, headers });\n }\n const known = error instanceof ServerError;\n if (!known) {\n console.error(error);\n }\n headers.set('content-type', 'application/json');\n const message = known ? error.message : 'The server function failed';\n return new Response(JSON.stringify({ error: message }), {\n status: known ? error.status : 500,\n headers,\n });\n }\n}\n\ninterface ResolvedView {\n key: string;\n component: Component;\n slots: Record<string, ResolvedView>;\n /** `_loading.brm`: the view streams in, and this shows until then. */\n loading?: Component;\n}\n\n/** Imports every module of a matched route before it renders. */\nasync function resolveView(view: RouteView): Promise<ResolvedView> {\n const [module, loading, ...slots] = await Promise.all([\n view.load(),\n view.loading?.(),\n ...Object.values(view.slots).map(resolveView),\n ]);\n const names = Object.keys(view.slots);\n return {\n key: view.key,\n component: module.default,\n loading: loading?.default,\n slots: Object.fromEntries(names.map((name, index) => [name, slots[index]!])),\n };\n}\n\n/**\n * Renders a view where its layout inserts it. A view with a loading file\n * streams in after the rest of the page, as a `#loading` body does.\n */\nasync function renderView(\n view: ResolvedView,\n props: Record<string, unknown>,\n ctx: Context,\n scope: number | undefined,\n): Promise<string> {\n if (!view.loading) {\n return component(viewComponent(view, props), {}, ctx, scope);\n }\n const id = ctx.boundary();\n const fallback = await component(view.loading, props, ctx, scope);\n ctx.defer(id, (child) => component(viewComponent(view, props), {}, child, scope));\n return `<!--l${id}-->${fallback}<!--/l-->`;\n}\n\n/**\n * A component that renders a route, with its slots rendering where the\n * layout inserts them. `props` go to every view, such as `params`.\n */\nfunction viewComponent(view: ResolvedView, props: Record<string, unknown>): Component {\n return (_props, ctx) => {\n const own: Record<string, unknown> = { ...props };\n for (const [name, slot] of Object.entries(view.slots)) {\n // Comments mark the slot, its layout's scope, the scope of its route and the route's key,\n // so the client can replace only the routes that change.\n own[name] = lazy(async (at, scope) => {\n const root = at.peek();\n const html = await renderView(slot, props, at, scope);\n return `<!--R${scope ?? -1}:${name}:${root}:${encodeURIComponent(slot.key)}-->${html}<!--/R-->`;\n });\n }\n return view.component(own, ctx);\n };\n}\n\nexport interface RouteOptions extends DocumentOptions, RequestOptions {\n /**\n * Throws errors that are not a `ServerError` instead of rendering\n * `_error.brm`, so a dev server can show them, such as with `errorPage`\n * from `brumate/vite`. The Vite plugin sets it in development.\n */\n dev?: boolean;\n /** The server functions, by ID, for forms that post to a page. `virtual:brumate/routes` passes them. */\n // oxlint-disable-next-line typescript/no-explicit-any -- Server functions take any arguments.\n functions?: Record<string, (...args: any[]) => unknown>;\n}\n\n/**\n * Runs the server function that a form without scripts posted to a page, as\n * `?__action=<id>`. Returns its result for `$action`, or the response that\n * answers the post instead of the page: a redirect, or an error.\n */\nasync function runAction(\n request: Request,\n id: string,\n options: RouteOptions,\n event: RequestEvent,\n): Promise<{ actions: Map<unknown, unknown> } | { answer: Response }> {\n if (isCrossSite(request, options)) {\n return { answer: new Response('Calls from other sites are not allowed', { status: 403 }) };\n }\n const fn = options.functions?.[id];\n if (!fn) {\n return { answer: new Response(`Unknown server function \"${id}\"`, { status: 404 }) };\n }\n try {\n const form = await request.formData();\n const result = await withEvent(event, () => fn(form));\n return { actions: new Map([[fn, result]]) };\n } catch (error) {\n if (error instanceof Redirect) {\n return {\n answer: new Response(null, {\n status: error.status,\n headers: { location: new URL(error.location, request.url).href },\n }),\n };\n }\n const known = error instanceof ServerError;\n if (!known) {\n console.error(error);\n }\n return {\n answer: new Response(known ? error.message : 'The server function failed', {\n status: known ? error.status : 500,\n headers: { 'content-type': 'text/plain; charset=utf-8' },\n }),\n };\n }\n}\n\n/** Renders the page of a route tree, streamed, with the results of a form for `$action`. */\nasync function renderPage(\n view: ResolvedView,\n props: Record<string, unknown>,\n request: Request,\n options: RouteOptions,\n extra: { actions?: Map<unknown, unknown>; status?: number },\n): Promise<Response> {\n // A page that the client loads in place of another starts above its IDs.\n const base = Number(request.headers.get('x-brumate-base'));\n const parts = await render(\n viewComponent(view, props),\n {},\n {\n ...options,\n request,\n actions: extra.actions,\n route: view.key,\n base: Number.isSafeInteger(base) && base > 0 ? base : undefined,\n },\n );\n const headers = new Headers(parts.headers);\n headers.set('content-type', 'text/html; charset=utf-8');\n const body = streamParts(parts, options).pipeThrough(new TextEncoderStream());\n return new Response(body, { status: extra.status ?? parts.status, headers });\n}\n\n/**\n * Renders the first `_error.brm` that renders, from the innermost. Its\n * component gets `error`, with the message and the status.\n */\nasync function renderError(\n views: RouteView[],\n error: { message: string; status: number },\n params: Record<string, string>,\n request: Request,\n options: RouteOptions,\n): Promise<Response | undefined> {\n for (const view of views) {\n try {\n // oxlint-disable-next-line no-await-in-loop -- The next file renders only when this one throws.\n const resolved = await resolveView(view);\n // oxlint-disable-next-line no-await-in-loop -- The next file renders only when this one throws.\n return await renderPage(resolved, { params, error }, request, options, {\n status: error.status,\n });\n } catch (failure) {\n // An error file that throws hands the error to the one outside it.\n console.error(failure);\n }\n }\n return undefined;\n}\n\n/** Runs the middleware of the folders on the path, from the outside in, around the answer. */\nasync function runMiddleware(\n loaders: MiddlewareLoader[],\n request: Request,\n event: RequestEvent,\n answer: () => Promise<Response>,\n): Promise<Response> {\n const [first, ...rest] = loaders;\n if (!first) {\n return answer();\n }\n const { middleware } = await first();\n return withEvent(event, () =>\n middleware(request, () => runMiddleware(rest, request, event, answer)),\n );\n}\n\n/**\n * Answers a request with the route that matches its path, streamed:\n *\n * - The `_middleware.ts` of each folder on the path runs first, from the outside in.\n * - An endpoint at the path answers the methods that it exports.\n * - A form without scripts that posts to the page with `?__action=<id>`\n * runs that server function first, and the page renders with its result\n * for `$action`.\n * - A route that throws renders the nearest `_error.brm`, and a path that\n * no route matches renders the `_error.brm` of the root with status 404.\n *\n * Returns undefined when no route matches and the root has no error file or\n * middleware. A `redirect` while the page renders answers with a redirect.\n */\nexport async function handleRoute(\n tree: RouteNode,\n request: Request,\n options: RouteOptions = {},\n): Promise<Response | undefined> {\n // One event for the request: middleware, endpoints, a form's server function and the page\n // share it, so cookies that one sets reach the response and the others read them.\n const event = options.event ?? new RequestEvent(request);\n const answer = await routeAnswer(tree, request, { ...options, event });\n return answer && withHeaders(answer, event.headers);\n}\n\n/** A response with more headers, such as cookies that middleware set. */\nfunction withHeaders(answer: Response, headers: Headers): Response {\n // A rendered page has them already.\n const sent = new Set(answer.headers.getSetCookie());\n const cookies = headers.getSetCookie().filter((cookie) => !sent.has(cookie));\n if (cookies.length === 0) {\n return answer;\n }\n // A response can have headers that cannot change, such as one from `Response.redirect`.\n const result = new Response(answer.body, answer);\n for (const cookie of cookies) {\n result.headers.append('set-cookie', cookie);\n }\n return result;\n}\n\nasync function routeAnswer(\n tree: RouteNode,\n request: Request,\n options: RouteOptions,\n): Promise<Response | undefined> {\n const url = new URL(request.url);\n const match = matchRoute(tree, url.pathname);\n if (!match) {\n const missing = notFound(tree);\n if (missing.errors.length === 0 && missing.middleware.length === 0) {\n return undefined;\n }\n return runMiddleware(missing.middleware, request, options.event!, async () => {\n const page = await renderError(\n missing.errors,\n { message: 'Not found', status: 404 },\n {},\n request,\n options,\n );\n return page ?? new Response('Not found', { status: 404 });\n });\n }\n return runMiddleware(match.middleware, request, options.event!, () =>\n answerRoute(match, request, options),\n );\n}\n\n/** Answers a request that a route matches, after its middleware. */\nasync function answerRoute(\n match: RouteMatch,\n request: Request,\n options: RouteOptions,\n): Promise<Response> {\n const url = new URL(request.url);\n if (match.endpoint) {\n const endpoint = await match.endpoint();\n const handler =\n endpoint[request.method] ?? (request.method === 'HEAD' ? endpoint.GET : undefined);\n if (handler) {\n return withEvent(options.event, () => handler(request, match.params));\n }\n if (match.view.load === missingPage || request.method !== 'GET') {\n const allow = Object.keys(endpoint).filter((name) => /^[A-Z]+$/.test(name));\n return new Response('Method not allowed', {\n status: 405,\n headers: { allow: allow.join(', ') },\n });\n }\n }\n let actions: Map<unknown, unknown> | undefined;\n const posted = url.searchParams.get('__action');\n if (request.method === 'POST' && posted !== null) {\n const outcome = await runAction(request, posted, options, options.event!);\n if ('answer' in outcome) {\n return outcome.answer;\n }\n actions = outcome.actions;\n }\n try {\n const view = await resolveView(match.view);\n return await renderPage(view, { params: match.params }, request, options, { actions });\n } catch (error) {\n if (isRedirect(error)) {\n return new Response(null, {\n status: error.status,\n headers: { location: new URL(error.location, url).href },\n });\n }\n const known = error instanceof ServerError;\n if (!known && options.dev) {\n throw error;\n }\n if (!known) {\n console.error(error);\n }\n const page = await renderError(\n match.errors,\n {\n message: known ? error.message : 'Something went wrong',\n status: known ? error.status : 500,\n },\n match.params,\n request,\n options,\n );\n if (page) {\n return page;\n }\n throw error;\n }\n}\n"],"mappings":";;;;;;;;;;;AAUA,IAAa,eAAb,MAA0B;CACxB;;CAEA,UAA4B,IAAI,QAAQ;;CAExC;;CAEA;;CAEA;CAEA,YAAY,SAAkB;EAC5B,KAAK,UAAU;CACjB;;;;;;;CAQA,UAAU,QAAsB;EAC9B,KAAK,SAAS;CAChB;;;;;;CAOA,QAAQ,IAAyC;EAC/C,KAAK,8BAAc,IAAI,IAAI;EAC3B,KAAK,UAAU,IAAI,OAAO,EAAE,CAAC;CAC/B;;CAGA,aAAqC;EACnC,OAAO,WAAW,IAAI;CACxB;;CAGA,UAAU,MAAkC;EAC1C,OAAO,WAAW,IAAI,CAAC,CAAC;CAC1B;;;;;;;CAQA,UAAU,MAAc,OAAe,UAAyB,CAAC,GAAS;EACxE,UAAU,MAAM,MAAM,OAAO,OAAO;CACtC;;CAGA,aAAa,MAAc,UAAkD,CAAC,GAAS;EACrF,aAAa,MAAM,MAAM,OAAO;CAClC;AACF;;;;;;;AAQA,IAAI;;AAEJ,IAAI;;;;;;AAOJ,SAAgB,UACd,OACA,UACA,OACG;CACH,MAAM,QAAQ;CACd,MAAM,aAAa;CACnB,UAAU;CACV,eAAe;CACf,IAAI;EACF,OAAO,SAAS;CAClB,UAAU;EACR,UAAU;EACV,eAAe;CACjB;AACF;;;;;;;;;;;;;;;;;AAkBA,SAAgB,WAAyB;CACvC,IAAI,CAAC,SACH,MAAM,IAAI,MACR,oNACF;CAEF,OAAO;AACT;;;;;;;AASA,SAAgB,OAA8C,IAAO,IAAe;CAClF,MAAM,YAAY,GAAG,SAAoB;EACvC,MAAM,QAAQ;EACd,IAAI,CAAC,OACH,OAAO,GAAG,GAAG,IAAI;EAEnB,IAAI;EACJ,IAAI;GACF,MAAM,GAAG,GAAG,GAAG,KAAK,UAAU,OAAO,MAAM;IAAE;IAAS;GAAiB,CAAC,CAAC;EAC3E,QAAQ;GAEN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