brumate 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{boot-DN1ZU8Hg.d.ts → boot-D-IdPy7B.d.ts} +24 -2
- package/dist/cli.js +2 -2
- package/dist/client-C0UCNL3J.js +1643 -0
- package/dist/client-C0UCNL3J.js.map +1 -0
- package/dist/{client-DwJInP_a.d.ts → client-MD0ZmcFR.d.ts} +101 -26
- package/dist/{client-routes-DakuM32C.js → client-routes-JTbGtukf.js} +28 -15
- package/dist/client-routes-JTbGtukf.js.map +1 -0
- package/dist/context-CTiSzQRc.js +27 -0
- package/dist/context-CTiSzQRc.js.map +1 -0
- package/dist/context-btHuB01Z.d.ts +42 -0
- package/dist/defer-D0bo1Gqx.js +52 -0
- package/dist/defer-D0bo1Gqx.js.map +1 -0
- package/dist/{devtools-BKjnHrnv.js → devtools-C50VH8gZ.js} +2 -2
- package/dist/devtools-C50VH8gZ.js.map +1 -0
- package/dist/{devtools-panel-AWOn0VK2.js → devtools-panel-AYjfwPhj.js} +4 -3
- package/dist/devtools-panel-AYjfwPhj.js.map +1 -0
- package/dist/events-BKWRqtMg.js +52 -0
- package/dist/events-BKWRqtMg.js.map +1 -0
- package/dist/{files-BBLPU9JR.js → files-Bnn1JqHx.js} +18 -3
- package/dist/files-Bnn1JqHx.js.map +1 -0
- package/dist/{html-DEeoepg3.js → html-bHZbkK-h.js} +26 -8
- package/dist/html-bHZbkK-h.js.map +1 -0
- package/dist/{html-Du8jY2Cc.d.ts → html-y1q7-t7D.d.ts} +12 -5
- package/dist/index.d.ts +79 -29
- package/dist/index.js +12 -4
- package/dist/index.js.map +1 -1
- package/dist/{inspect-CRZlO11T.js → inspect-BJtACnQp.js} +928 -91
- package/dist/inspect-BJtACnQp.js.map +1 -0
- package/dist/{loader-Dc9OwY5I.js → loader-B18i3_-T.js} +46 -11
- package/dist/loader-B18i3_-T.js.map +1 -0
- package/dist/{navigate-CzLjnoPH.js → navigate-BwuZveDF.js} +71 -12
- package/dist/navigate-BwuZveDF.js.map +1 -0
- package/dist/{produce-BRGHP7e0.js → produce-CWfJ4byV.js} +43 -2
- package/dist/produce-CWfJ4byV.js.map +1 -0
- package/dist/{produce-CtZ32UGG.d.ts → produce-D4K7qpaL.d.ts} +23 -11
- package/dist/routes-BZNt7DSZ.d.ts +38 -0
- package/dist/{rpc-9fSqL_YK.js → rpc-B-Zkn6Ch.js} +24 -18
- package/dist/rpc-B-Zkn6Ch.js.map +1 -0
- package/dist/runtime/batch.d.ts +23 -0
- package/dist/runtime/batch.js +69 -0
- package/dist/runtime/batch.js.map +1 -0
- package/dist/runtime/client.d.ts +5 -5
- package/dist/runtime/client.js +5 -1345
- package/dist/runtime/context.d.ts +2 -2
- package/dist/runtime/context.js +1 -1
- package/dist/runtime/devtools.d.ts +5 -4
- package/dist/runtime/devtools.js +1 -1
- package/dist/runtime/env.d.ts +44 -0
- package/dist/runtime/env.js +61 -0
- package/dist/runtime/env.js.map +1 -0
- package/dist/runtime/events.d.ts +27 -0
- package/dist/runtime/events.js +1 -0
- package/dist/runtime/hot.d.ts +1 -1
- package/dist/runtime/html.d.ts +2 -2
- package/dist/runtime/html.js +1 -1
- package/dist/runtime/loader.d.ts +2 -2
- package/dist/runtime/loader.js +2 -2
- package/dist/runtime/routes.d.ts +2 -21
- package/dist/runtime/routes.js +31 -1
- package/dist/runtime/routes.js.map +1 -1
- package/dist/runtime/server.d.ts +6 -5
- package/dist/runtime/server.js +5 -6
- package/dist/runtime/signals.d.ts +22 -1
- package/dist/runtime/signals.js +29 -1
- package/dist/runtime/signals.js.map +1 -1
- package/dist/runtime/static-loader.d.ts +2 -2
- package/dist/runtime/static-loader.js +1 -1
- package/dist/runtime/testing.d.ts +46 -5
- package/dist/runtime/testing.js +240 -33
- package/dist/runtime/testing.js.map +1 -1
- package/dist/secrets-BxagsJxJ.js +23 -0
- package/dist/secrets-BxagsJxJ.js.map +1 -0
- package/dist/{server-BxqjLUnV.d.ts → server-BA9SJ2Vm.d.ts} +544 -106
- package/dist/server-BqfM95r1.js +2762 -0
- package/dist/server-BqfM95r1.js.map +1 -0
- package/dist/skew-FRmAy9iy.js +49 -0
- package/dist/skew-FRmAy9iy.js.map +1 -0
- package/dist/standard-schema-BNY82yX3.d.ts +63 -0
- package/dist/{static-loader-BcFh4ebX.d.ts → static-loader-BzE9SRaj.d.ts} +2 -2
- package/dist/{static-loader-ClNkHZGn.js → static-loader-DOygOFj5.js} +52 -21
- package/dist/static-loader-DOygOFj5.js.map +1 -0
- package/dist/{stream-bgNCMcaA.js → stream-JaMHMdBD.js} +126 -61
- package/dist/stream-JaMHMdBD.js.map +1 -0
- package/dist/vite.d.ts +42 -1
- package/dist/vite.js +435 -55
- package/dist/vite.js.map +1 -1
- package/package.json +15 -2
- package/types.d.ts +9 -1
- package/dist/client-routes-DakuM32C.js.map +0 -1
- package/dist/context-BG8KCF3v.js +0 -15
- package/dist/context-BG8KCF3v.js.map +0 -1
- package/dist/context-aeo9esY9.d.ts +0 -16
- package/dist/devtools-BKjnHrnv.js.map +0 -1
- package/dist/devtools-panel-AWOn0VK2.js.map +0 -1
- package/dist/files-BBLPU9JR.js.map +0 -1
- package/dist/html-DEeoepg3.js.map +0 -1
- package/dist/inspect-CRZlO11T.js.map +0 -1
- package/dist/loader-Dc9OwY5I.js.map +0 -1
- package/dist/navigate-CzLjnoPH.js.map +0 -1
- package/dist/produce-BRGHP7e0.js.map +0 -1
- package/dist/rpc-9fSqL_YK.js.map +0 -1
- package/dist/runtime/client.js.map +0 -1
- package/dist/server-DZsgnPKS.js +0 -1615
- package/dist/server-DZsgnPKS.js.map +0 -1
- package/dist/shared-CWYOd0H3.js +0 -40
- package/dist/shared-CWYOd0H3.js.map +0 -1
- package/dist/static-loader-ClNkHZGn.js.map +0 -1
- package/dist/stream-bgNCMcaA.js.map +0 -1
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
//#region src/runtime/standard-schema.d.ts
|
|
2
|
+
/** The Standard Schema interface. */
|
|
3
|
+
interface StandardSchemaV1<Input = unknown, Output = Input> {
|
|
4
|
+
/** The Standard Schema properties. */
|
|
5
|
+
readonly "~standard": StandardSchemaV1.Props<Input, Output>;
|
|
6
|
+
}
|
|
7
|
+
declare namespace StandardSchemaV1 {
|
|
8
|
+
/** The Standard Schema properties interface. */
|
|
9
|
+
export interface Props<Input = unknown, Output = Input> {
|
|
10
|
+
/** The version number of the standard. */
|
|
11
|
+
readonly version: 1;
|
|
12
|
+
/** The vendor name of the schema library. */
|
|
13
|
+
readonly vendor: string;
|
|
14
|
+
/** Validates unknown input values. */
|
|
15
|
+
readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => Result<Output> | Promise<Result<Output>>;
|
|
16
|
+
/** Inferred types associated with the schema. */
|
|
17
|
+
readonly types?: Types<Input, Output> | undefined;
|
|
18
|
+
}
|
|
19
|
+
/** The result interface of the validate function. */
|
|
20
|
+
export type Result<Output> = SuccessResult<Output> | FailureResult;
|
|
21
|
+
/** The result interface if validation succeeds. */
|
|
22
|
+
export interface SuccessResult<Output> {
|
|
23
|
+
/** The typed output value. */
|
|
24
|
+
readonly value: Output;
|
|
25
|
+
/** A falsy value for `issues` indicates success. */
|
|
26
|
+
readonly issues?: undefined;
|
|
27
|
+
}
|
|
28
|
+
export interface Options {
|
|
29
|
+
/** Explicit support for additional vendor-specific parameters, if needed. */
|
|
30
|
+
readonly libraryOptions?: Record<string, unknown> | undefined;
|
|
31
|
+
}
|
|
32
|
+
/** The result interface if validation fails. */
|
|
33
|
+
export interface FailureResult {
|
|
34
|
+
/** The issues of failed validation. */
|
|
35
|
+
readonly issues: ReadonlyArray<Issue>;
|
|
36
|
+
}
|
|
37
|
+
/** The issue interface of the failure output. */
|
|
38
|
+
export interface Issue {
|
|
39
|
+
/** The error message of the issue. */
|
|
40
|
+
readonly message: string;
|
|
41
|
+
/** The path of the issue, if any. */
|
|
42
|
+
readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
|
|
43
|
+
}
|
|
44
|
+
/** The path segment interface of the issue. */
|
|
45
|
+
export interface PathSegment {
|
|
46
|
+
/** The key representing a path segment. */
|
|
47
|
+
readonly key: PropertyKey;
|
|
48
|
+
}
|
|
49
|
+
/** The Standard Schema types interface. */
|
|
50
|
+
export interface Types<Input = unknown, Output = Input> {
|
|
51
|
+
/** The input type of the schema. */
|
|
52
|
+
readonly input: Input;
|
|
53
|
+
/** The output type of the schema. */
|
|
54
|
+
readonly output: Output;
|
|
55
|
+
}
|
|
56
|
+
/** Infers the input type of a Standard Schema. */
|
|
57
|
+
export type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["input"];
|
|
58
|
+
/** Infers the output type of a Standard Schema. */
|
|
59
|
+
export type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"];
|
|
60
|
+
}
|
|
61
|
+
//#endregion
|
|
62
|
+
export { StandardSchemaV1 as t };
|
|
63
|
+
//# sourceMappingURL=standard-schema-BNY82yX3.d.ts.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as LoaderOptions } from "./boot-
|
|
1
|
+
import { t as LoaderOptions } from "./boot-D-IdPy7B.js";
|
|
2
2
|
//#region src/runtime/static-loader.d.ts
|
|
3
3
|
/**
|
|
4
4
|
* `start` for a site that loads every page with a full page load, as with
|
|
@@ -8,4 +8,4 @@ import { t as LoaderOptions } from "./boot-DN1ZU8Hg.js";
|
|
|
8
8
|
declare function startWithoutNavigation(options: LoaderOptions): () => void;
|
|
9
9
|
//#endregion
|
|
10
10
|
export { startWithoutNavigation as t };
|
|
11
|
-
//# sourceMappingURL=static-loader-
|
|
11
|
+
//# sourceMappingURL=static-loader-BzE9SRaj.d.ts.map
|
|
@@ -32,7 +32,8 @@ const idle = (fn) => (window.requestIdleCallback ?? setTimeout)(fn);
|
|
|
32
32
|
*/
|
|
33
33
|
function boot(options, navigate) {
|
|
34
34
|
let core;
|
|
35
|
-
|
|
35
|
+
/** The event types that the document listens to, and whether each listener is passive. */
|
|
36
|
+
const types = /* @__PURE__ */ new Map();
|
|
36
37
|
const removers = [];
|
|
37
38
|
const listen = (target, type, listener, flags) => {
|
|
38
39
|
target.addEventListener(type, listener, flags);
|
|
@@ -48,29 +49,56 @@ function boot(options, navigate) {
|
|
|
48
49
|
});
|
|
49
50
|
listen(document, "brumate:core", () => void loadCore());
|
|
50
51
|
const warm = (ref) => {
|
|
51
|
-
const [id, name] = ref.split("#");
|
|
52
|
-
options.load(id)?.then((module) => module.load?.(/^[
|
|
52
|
+
const [id, name] = ref.split("@")[0].split("#");
|
|
53
|
+
options.load(id)?.then((module) => module.load?.(/^[hct]\d/.test(name) ? name : "update")).catch(() => {});
|
|
53
54
|
};
|
|
54
55
|
const run = (element, ref, event) => {
|
|
55
56
|
warm(ref);
|
|
56
57
|
loadCore().then((client) => client.handle(element, ref, event));
|
|
57
58
|
};
|
|
58
59
|
const apply = (event, element, entry) => {
|
|
59
|
-
|
|
60
|
+
for (const modifier of entry.modifiers) if (modifier === "prevent" || modifier.startsWith("prevent(") && modifier.slice(8, -1).split(",").includes(event.key === " " ? "Space" : event.key)) event.preventDefault();
|
|
60
61
|
if (entry.modifiers.includes("once")) element.setAttribute("b-on", entries(element).map((item) => item.raw).filter((raw) => raw !== entry.raw).join(" "));
|
|
61
62
|
run(element, entry.ref, event);
|
|
62
63
|
return entry.modifiers.includes("stop");
|
|
63
64
|
};
|
|
65
|
+
/**
|
|
66
|
+
* Handlers run as if each element had its own listener: those with
|
|
67
|
+
* `capture` from the outside in, then the others from the target outwards.
|
|
68
|
+
* An event that does not bubble, such as `focus`, reaches only the others
|
|
69
|
+
* of its target. `stop` ends the event where it is.
|
|
70
|
+
*/
|
|
64
71
|
const onEvent = (event) => {
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
for (const
|
|
69
|
-
|
|
70
|
-
event.
|
|
71
|
-
|
|
72
|
+
const path = [];
|
|
73
|
+
for (let node = event.target; node && node !== document; node = node.parentNode) if (node.nodeType === 1 && node.hasAttribute("b-on")) path.push(node);
|
|
74
|
+
const phase = (elements, capture) => {
|
|
75
|
+
for (const element of elements) {
|
|
76
|
+
let stop = false;
|
|
77
|
+
for (const entry of entries(element)) if (entry.type === event.type && entry.modifiers.includes("capture") === capture && apply(event, element, entry)) stop = true;
|
|
78
|
+
if (stop) {
|
|
79
|
+
event.stopPropagation();
|
|
80
|
+
return true;
|
|
81
|
+
}
|
|
72
82
|
}
|
|
73
|
-
|
|
83
|
+
return false;
|
|
84
|
+
};
|
|
85
|
+
if (!phase([...path].reverse(), true)) phase(event.bubbles ? path : path.filter((element) => element === event.target), false);
|
|
86
|
+
};
|
|
87
|
+
/** True for an entry that prevents the default action, which a passive listener cannot do. */
|
|
88
|
+
const prevents = (entry) => entry.modifiers.some((modifier) => modifier.startsWith("prevent"));
|
|
89
|
+
/**
|
|
90
|
+
* Listens to an event type on the document. The listener is passive, so
|
|
91
|
+
* scrolling does not wait for it, until an entry of the type prevents.
|
|
92
|
+
*/
|
|
93
|
+
const delegate = (type, prevent) => {
|
|
94
|
+
const passive = types.get(type);
|
|
95
|
+
if (passive === false || passive === true && !prevent) return;
|
|
96
|
+
if (passive) document.removeEventListener(type, onEvent, true);
|
|
97
|
+
types.set(type, !prevent);
|
|
98
|
+
listen(document, type, onEvent, {
|
|
99
|
+
capture: true,
|
|
100
|
+
passive: !prevent
|
|
101
|
+
});
|
|
74
102
|
};
|
|
75
103
|
const started = /* @__PURE__ */ new WeakSet();
|
|
76
104
|
const select = (root, selector) => {
|
|
@@ -95,22 +123,24 @@ function boot(options, navigate) {
|
|
|
95
123
|
for (const element of select(root, "[data-prefetch=visible],[data-prefetch=idle]")) if (strategy(element) === "idle" || !visible) idle(() => preload(element));
|
|
96
124
|
else visible.observe(element);
|
|
97
125
|
for (const element of select(root, "[b-on]:not(template)")) {
|
|
98
|
-
for (const
|
|
99
|
-
types.add(type);
|
|
100
|
-
listen(document, type, onEvent, true);
|
|
101
|
-
}
|
|
126
|
+
for (const entry of entries(element)) delegate(entry.type, prevents(entry));
|
|
102
127
|
if (eager && strategy(element) === "hover") visible?.observe(element);
|
|
103
128
|
}
|
|
104
129
|
for (const template of select(root, "template[b-listen]")) {
|
|
105
130
|
const target = template.getAttribute("b-listen") === "window" ? window : document;
|
|
106
131
|
for (const entry of entries(template)) listen(target, entry.type, (event) => {
|
|
107
132
|
if (template.isConnected) apply(event, template, entry);
|
|
133
|
+
}, {
|
|
134
|
+
capture: entry.modifiers.includes("capture"),
|
|
135
|
+
passive: !prevents(entry)
|
|
108
136
|
});
|
|
109
137
|
}
|
|
110
|
-
for (const template of select(root, "template[b-client]")) {
|
|
111
|
-
const
|
|
112
|
-
const
|
|
113
|
-
const
|
|
138
|
+
for (const template of select(root, "template[b-client],template[b-defer]")) {
|
|
139
|
+
const client = template.getAttribute("b-client");
|
|
140
|
+
const [trigger, ref] = (client ?? template.getAttribute("b-defer")).split(client ? "=" : ":");
|
|
141
|
+
const go = () => client ? run(template, ref) : void import("./defer-D0bo1Gqx.js").then((module) => module.loadDeferred(template));
|
|
142
|
+
const near = template.getAttribute("b-near");
|
|
143
|
+
const next = near && (root.querySelector(`[b-b="${near}"]`) ?? document.querySelector(`[b-b="${near}"]`)) || template.nextElementSibling;
|
|
114
144
|
if (trigger === "idle") idle(go);
|
|
115
145
|
else if (trigger === "visible" && next && visible) {
|
|
116
146
|
const observer = new IntersectionObserver((records) => {
|
|
@@ -147,6 +177,7 @@ function boot(options, navigate) {
|
|
|
147
177
|
options,
|
|
148
178
|
listen,
|
|
149
179
|
core: () => core,
|
|
180
|
+
start: loadCore,
|
|
150
181
|
scan
|
|
151
182
|
});
|
|
152
183
|
else listen(document, "brumate:reload", () => location.reload());
|
|
@@ -182,4 +213,4 @@ function startWithoutNavigation(options) {
|
|
|
182
213
|
//#endregion
|
|
183
214
|
export { strategy as i, boot as n, importCore as r, startWithoutNavigation as t };
|
|
184
215
|
|
|
185
|
-
//# sourceMappingURL=static-loader-
|
|
216
|
+
//# sourceMappingURL=static-loader-DOygOFj5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"static-loader-DOygOFj5.js","names":[],"sources":["../src/runtime/boot.ts","../src/runtime/static-loader.ts"],"sourcesContent":["// The loader's code that every page runs. `loader.ts` adds client navigation,\n// and `static-loader.ts` starts it without, so a site that turns navigation\n// off does not have its code, or the parts of the core that only it uses, in\n// its bundle.\n\nimport type * as Client from './client.ts';\nimport type { ClientModule } from './client.ts';\n\nexport interface LoaderOptions {\n /**\n * Imports the client module of a component, by component ID. Undefined for\n * a component that has no client code.\n */\n load: (id: string) => Promise<ClientModule> | undefined;\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, forms that post to a server function, and redirects\n * from server functions to the same origin. Defaults to true.\n */\n navigate?: boolean | NavigateOptions;\n /**\n * After the page loads, while the browser is idle, loads the core and the\n * code of the handlers of elements in or near the viewport, so a first\n * event needs no request. Elements with `data-prefetch=\"none\"` are left\n * out, and nothing loads when the browser asks to save data or the\n * connection is 2G. Defaults to true.\n */\n preload?: boolean;\n /**\n * The ID of the build of the page, for skew protection. The Vite plugin\n * sets it. Calls send it, and a page of another build, or a call that\n * answers 409 after a deploy, makes the next navigation a full page load.\n */\n build?: string;\n /**\n * Receives every error of client code first: of a handler, an effect, a\n * `$client` callback or a memo that loads, such as for a reporting\n * service. `scope` is the ID of the scope that the code belongs to. The\n * error then renders the `#catch` body of the nearest `#try`, or the page\n * gets a `brumate:error` event on `window` and the error is logged.\n */\n onError?: (error: unknown, info: { scope?: number | string }) => void;\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`. A redirect from a server\n * function has the type `form`.\n */\n transition?: boolean;\n /**\n * After a navigation, moves the focus to the first `<h1>` of the routes\n * that changed, or to `<main>`, as a full page load starts it at the top.\n * Defaults to true.\n */\n focus?: boolean;\n}\n\ninterface Entry {\n raw: string;\n type: string;\n modifiers: string[];\n ref: string;\n}\n\n// Parsed `b-on` values, so repeated events do not parse them again.\nconst parsed = new Map<string, Entry[]>();\n\nexport function entries(element: Element): Entry[] {\n const value = element.getAttribute('b-on') ?? '';\n return (parsed.get(value) ??\n parsed\n .set(\n value,\n value\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 .get(value))!;\n}\n\n/** The `prefetch` strategy of an element, from its `data-prefetch`. */\nexport function strategy(element: Element): string {\n return element.getAttribute('data-prefetch') ?? 'hover';\n}\n\n/** The functions of the core that the loader calls. */\nexport type Core = (typeof Client)['loader'];\n\n/**\n * Imports the core. It reads one export by name, so a build keeps only it and\n * the helpers that compiled components call.\n */\nexport const importCore = (): Promise<Core> =>\n import('./client.ts').then((client) => client.loader);\n\n/** Runs a function when the browser is idle. */\nconst idle = (fn: () => void): unknown => (window.requestIdleCallback ?? setTimeout)(fn);\n\n/** What the loader gives the code that loads pages without a full page load. */\nexport interface Navigation {\n options: LoaderOptions;\n listen: (\n target: EventTarget,\n type: string,\n listener: (event: Event) => void,\n flags?: AddEventListenerOptions | boolean,\n ) => void;\n core: () => Promise<Core> | undefined;\n /** Starts the core, or returns the one that runs. */\n start: () => Promise<Core>;\n scan: (root: ParentNode) => void;\n}\n\n/**\n * Starts resuming the page. Listens to the events in `b-on` attributes\n * and loads `brumate/client` and the component's module on the first one.\n * `navigate` adds client navigation, and returns how to import the core.\n * Returns a function that removes the listeners and stops the core.\n */\nexport function boot(\n options: LoaderOptions,\n navigate?: (navigation: Navigation) => () => Promise<Core>,\n): () => void {\n let core: Promise<Core> | undefined;\n /** The event types that the document listens to, and whether each listener is passive. */\n const types = new Map<string, boolean>();\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 // Client navigation imports the core with the code that reads the pages it adds.\n let load = importCore;\n const loadCore = (): Promise<Core> =>\n (core ??= load().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 // Starts loading the module of a handler and its part, as one step when the module holds them.\n // The core reports an error of the load when it runs the handler.\n const warm = (ref: string): void => {\n // A handler that a spread passed on names its scope after `@`.\n const [id, name] = ref.split('@')[0]!.split('#') as [string, string];\n void options\n .load(id)\n ?.then((module) => module.load?.(/^[hct]\\d/.test(name) ? name : 'update'))\n .catch(() => {});\n };\n\n const run = (element: Element, ref: string, event?: Event): void => {\n // The module loads while the core does, not after it.\n warm(ref);\n void loadCore().then((client) => client.handle(element, ref, event));\n };\n\n const apply = (event: Event, element: Element, entry: Entry): boolean => {\n for (const modifier of entry.modifiers) {\n // `prevent(ArrowDown,Enter)` prevents only these keys, by `event.key`.\n if (\n modifier === 'prevent' ||\n (modifier.startsWith('prevent(') &&\n modifier\n .slice(8, -1)\n .split(',')\n .includes(\n (event as KeyboardEvent).key === ' ' ? 'Space' : (event as KeyboardEvent).key,\n ))\n ) {\n event.preventDefault();\n }\n }\n if (entry.modifiers.includes('once')) {\n element.setAttribute(\n 'b-on',\n entries(element)\n .map((item) => item.raw)\n .filter((raw) => raw !== entry.raw)\n .join(' '),\n );\n }\n run(element, entry.ref, event);\n return entry.modifiers.includes('stop');\n };\n\n /**\n * Handlers run as if each element had its own listener: those with\n * `capture` from the outside in, then the others from the target outwards.\n * An event that does not bubble, such as `focus`, reaches only the others\n * of its target. `stop` ends the event where it is.\n */\n const onEvent = (event: Event): void => {\n const path: Element[] = [];\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('b-on')) {\n path.push(node as Element);\n }\n }\n const phase = (elements: Element[], capture: boolean): boolean => {\n for (const element of elements) {\n let stop = false;\n for (const entry of entries(element)) {\n if (\n entry.type === event.type &&\n entry.modifiers.includes('capture') === capture &&\n apply(event, element, entry)\n ) {\n stop = true;\n }\n }\n if (stop) {\n event.stopPropagation();\n return true;\n }\n }\n return false;\n };\n if (!phase([...path].reverse(), true)) {\n phase(event.bubbles ? path : path.filter((element) => element === event.target), false);\n }\n };\n\n /** True for an entry that prevents the default action, which a passive listener cannot do. */\n const prevents = (entry: Entry): boolean =>\n entry.modifiers.some((modifier) => modifier.startsWith('prevent'));\n\n /**\n * Listens to an event type on the document. The listener is passive, so\n * scrolling does not wait for it, until an entry of the type prevents.\n */\n const delegate = (type: string, prevent: boolean): void => {\n const passive = types.get(type);\n if (passive === false || (passive === true && !prevent)) {\n return;\n }\n if (passive) {\n document.removeEventListener(type, onEvent, true);\n }\n types.set(type, !prevent);\n listen(document, type, onEvent, { capture: true, passive: !prevent });\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(\n (records) => {\n for (const record of records) {\n if (record.isIntersecting) {\n visible!.unobserve(record.target);\n preload(record.target);\n }\n }\n },\n // Near the viewport counts too, so code loads before an element scrolls in.\n { rootMargin: '25%' },\n );\n removers.push(() => visible?.disconnect());\n\n // True once the page is idle after `load`, when elements with the default strategy preload\n // as they come near the viewport. See `preload` in the options.\n let eager = false;\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 idle(() => preload(element));\n } else {\n visible.observe(element);\n }\n }\n for (const element of select(root, '[b-on]:not(template)')) {\n for (const entry of entries(element)) {\n delegate(entry.type, prevents(entry));\n }\n if (eager && strategy(element) === 'hover') {\n visible?.observe(element);\n }\n }\n for (const template of select(root, 'template[b-listen]')) {\n const target = template.getAttribute('b-listen') === 'window' ? window : document;\n for (const entry of entries(template)) {\n // Markup that is gone, such as a page that navigation replaced, no longer listens.\n listen(\n target,\n entry.type,\n (event) => {\n if (template.isConnected) {\n apply(event, template, entry);\n }\n },\n { capture: entry.modifiers.includes('capture'), passive: !prevents(entry) },\n );\n }\n }\n for (const template of select(root, 'template[b-client],template[b-defer]')) {\n const client = template.getAttribute('b-client');\n const [trigger, ref] = (client ?? template.getAttribute('b-defer')!).split(\n client ? '=' : ':',\n ) as [string, string];\n // A `#defer` block asks the server for its body, with a module that only it needs.\n const go = (): void =>\n client\n ? run(template, ref)\n : void import('./defer.ts').then((module) => module.loadDeferred(template));\n // The element that a `$client` callback reads through `ref`, or the one after the marker.\n const near = template.getAttribute('b-near');\n const next =\n (near &&\n (root.querySelector(`[b-b=\"${near}\"]`) ?? document.querySelector(`[b-b=\"${near}\"]`))) ||\n template.nextElementSibling;\n if (trigger === 'idle') {\n idle(go);\n } else if (trigger === 'visible' && next && visible) {\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 importCore();\n for (const entry of entries(element)) {\n warm(entry.ref);\n }\n };\n\n const hover = (event: Event): void => {\n const element = (event.target as Element).closest?.('[b-on]');\n if (element && strategy(element) === 'hover') {\n preload(element);\n }\n };\n listen(document, 'pointerover', hover, { passive: true });\n listen(document, 'focusin', hover);\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?.('b-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 (navigate) {\n load = navigate({ options, listen, core: () => core, start: loadCore, scan });\n } else {\n // A hot update whose markup changed loads the page again.\n listen(document, 'brumate:reload', () => location.reload());\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\n // After `load`, so the page's own requests go first, and only when the browser is idle.\n // `2g` matches `slow-2g` too.\n const connection = (navigator as { connection?: { saveData?: boolean; effectiveType?: string } })\n .connection;\n if (\n options.preload !== false &&\n !connection?.saveData &&\n !/2g/.test(connection?.effectiveType as string)\n ) {\n listen(window, 'load', () =>\n idle(() => {\n eager = true;\n scan(document);\n }),\n );\n }\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","// The loader without client navigation, for `navigate: false`. It is a module\n// of its own, so a bundle that starts it has no import of the navigation code,\n// and keeps none of the core's exports that only navigation reads.\n\nimport { boot } from './boot.ts';\nimport type { LoaderOptions } from './boot.ts';\n\nexport type { LoaderOptions } from './boot.ts';\n\n/**\n * `start` for a site that loads every page with a full page load, as with\n * `navigate: false`. A bundle that only calls it leaves out the code of\n * client navigation.\n */\nexport function startWithoutNavigation(options: LoaderOptions): () => void {\n return boot(options);\n}\n"],"mappings":";AAsEA,MAAM,yBAAS,IAAI,IAAqB;AAExC,SAAgB,QAAQ,SAA2B;CACjD,MAAM,QAAQ,QAAQ,aAAa,MAAM,K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OAAO,QAAQ,CAAC;CAC9C;AACF;;;;;;;;AC/aA,SAAgB,uBAAuB,SAAoC;CACzE,OAAO,KAAK,OAAO;AACrB"}
|
|
@@ -1,30 +1,22 @@
|
|
|
1
|
-
import { d as isRaw,
|
|
2
|
-
import {
|
|
1
|
+
import { d as isRaw, m as rawHTML } from "./html-bHZbkK-h.js";
|
|
2
|
+
import { n as ElementReference, o as stateValues } from "./produce-CWfJ4byV.js";
|
|
3
3
|
import { Feature, Stream, createPlugin, fromCrossJSON, toCrossJSONStream } from "seroval";
|
|
4
|
+
import { AbortSignalPlugin, CustomEventPlugin, DOMExceptionPlugin, EventPlugin, FormDataPlugin, HeadersPlugin, ImageDataPlugin, ReadableStreamPlugin, RequestPlugin, ResponsePlugin, URLPlugin, URLSearchParamsPlugin } from "seroval-plugins/web";
|
|
4
5
|
//#region src/runtime/calls.ts
|
|
5
|
-
/** Server functions that are passed to the client, with their references. */
|
|
6
|
-
const functionReferences = /* @__PURE__ */ new WeakMap();
|
|
7
6
|
/**
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
7
|
+
* Client functions that the server passes on, such as function props, with
|
|
8
|
+
* their references. Kept under a symbol of the registry, so two copies of the
|
|
9
|
+
* runtime, such as a component's and the render context's, share it.
|
|
11
10
|
*/
|
|
12
|
-
|
|
13
|
-
index;
|
|
14
|
-
constructor(index) {
|
|
15
|
-
this.index = index;
|
|
16
|
-
}
|
|
17
|
-
};
|
|
11
|
+
const functionReferences = globalThis[Symbol.for("brumate.functionReferences")] ??= /* @__PURE__ */ new WeakMap();
|
|
18
12
|
/**
|
|
19
|
-
*
|
|
20
|
-
*
|
|
13
|
+
* True for a file or a blob. One from another frame, or another DOM, is an
|
|
14
|
+
* instance of another `Blob` class, so its methods tell instead.
|
|
21
15
|
*/
|
|
22
|
-
function
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
if (value !== null && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, replaceDeep(item, replace)]));
|
|
27
|
-
return value;
|
|
16
|
+
function isBlob(value) {
|
|
17
|
+
if (typeof Blob !== "undefined" && value instanceof Blob) return true;
|
|
18
|
+
const blob = value;
|
|
19
|
+
return typeof blob === "object" && blob !== null && typeof blob.size === "number" && typeof blob.type === "string" && typeof blob.arrayBuffer === "function" && typeof blob.slice === "function";
|
|
28
20
|
}
|
|
29
21
|
//#endregion
|
|
30
22
|
//#region src/runtime/serial.ts
|
|
@@ -91,38 +83,104 @@ const ComponentPlugin = createPlugin({
|
|
|
91
83
|
serialize: (node, ctx) => `$b.c(${ctx.serialize(node.c)})`,
|
|
92
84
|
deserialize: (node, ctx) => stateValues.c(ctx.deserialize(node.c))
|
|
93
85
|
});
|
|
94
|
-
/**
|
|
95
|
-
|
|
86
|
+
/**
|
|
87
|
+
* Files and blobs, which go only in the arguments of a call, as parts of
|
|
88
|
+
* multipart form data named `file<index>`. The node holds the index. The
|
|
89
|
+
* call passes `sent`, which gets each blob, and the server passes the form
|
|
90
|
+
* that it `received`, whose files the indexes read. Without them, as in the
|
|
91
|
+
* page state and in the answer of a call, a blob throws.
|
|
92
|
+
*/
|
|
93
|
+
function uploadPlugin(sent, received) {
|
|
96
94
|
return createPlugin({
|
|
97
|
-
tag,
|
|
95
|
+
tag: "brumate/upload",
|
|
98
96
|
skipPlainObjects: true,
|
|
99
|
-
test:
|
|
100
|
-
parse: parsers((value) =>
|
|
101
|
-
|
|
102
|
-
|
|
97
|
+
test: isBlob,
|
|
98
|
+
parse: parsers((value) => {
|
|
99
|
+
if (!sent) throw new Error("A file or a blob can only be sent in the arguments of a server function");
|
|
100
|
+
return { i: sent.push(value) - 1 };
|
|
101
|
+
}),
|
|
102
|
+
serialize: () => {
|
|
103
|
+
throw new Error("A file or a blob can only be sent in the arguments of a server function");
|
|
104
|
+
},
|
|
105
|
+
deserialize: (node, ctx) => {
|
|
106
|
+
const file = received?.get(`file${ctx.deserialize(node.i)}`);
|
|
107
|
+
if (!(file instanceof Blob)) throw new TypeError("A file of the call is missing");
|
|
108
|
+
return file;
|
|
109
|
+
}
|
|
103
110
|
});
|
|
104
111
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
112
|
+
/**
|
|
113
|
+
* The plugin of `AbortSignal` from seroval-plugins, which sends whether the
|
|
114
|
+
* signal aborted and its reason. The one of seroval-plugins waits for a live
|
|
115
|
+
* signal to abort, so a call with one would not be sent, and a page or an
|
|
116
|
+
* answer with one would not end.
|
|
117
|
+
*/
|
|
118
|
+
const SignalPlugin = {
|
|
119
|
+
...AbortSignalPlugin,
|
|
120
|
+
parse: {
|
|
121
|
+
sync: AbortSignalPlugin.parse.sync,
|
|
122
|
+
stream: AbortSignalPlugin.parse.sync,
|
|
123
|
+
async: async (value, ctx) => value.aborted ? { reason: await ctx.parse(value.reason) } : {}
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
/**
|
|
127
|
+
* The plugin of `Request` from seroval-plugins, whose body streams in the
|
|
128
|
+
* stream mode. A request with a stream body needs `duplex: 'half'`, or its
|
|
129
|
+
* constructor throws, so the plugin adds it.
|
|
130
|
+
*/
|
|
131
|
+
const BodyRequestPlugin = {
|
|
132
|
+
...RequestPlugin,
|
|
133
|
+
serialize: (node, ctx) => `new Request(${ctx.serialize(node.url)},Object.assign(${ctx.serialize(node.options)},{duplex:"half"}))`,
|
|
134
|
+
deserialize: (node, ctx) => new Request(ctx.deserialize(node.url), {
|
|
135
|
+
...ctx.deserialize(node.options),
|
|
136
|
+
duplex: "half"
|
|
137
|
+
})
|
|
138
|
+
};
|
|
139
|
+
/** The plugins after the plugin of uploads, which a call makes for its files. */
|
|
140
|
+
const valuePlugins = [
|
|
108
141
|
ElementPlugin,
|
|
109
142
|
FunctionPlugin,
|
|
110
143
|
RawPlugin,
|
|
111
144
|
ComponentPlugin,
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
145
|
+
SignalPlugin,
|
|
146
|
+
CustomEventPlugin,
|
|
147
|
+
DOMExceptionPlugin,
|
|
148
|
+
EventPlugin,
|
|
149
|
+
FormDataPlugin,
|
|
150
|
+
HeadersPlugin,
|
|
151
|
+
ImageDataPlugin,
|
|
152
|
+
ReadableStreamPlugin,
|
|
153
|
+
BodyRequestPlugin,
|
|
154
|
+
ResponsePlugin,
|
|
122
155
|
URLPlugin,
|
|
123
|
-
|
|
156
|
+
URLSearchParamsPlugin
|
|
124
157
|
];
|
|
125
158
|
/**
|
|
159
|
+
* The plugins of a call with files: `sent` gets the files that the call
|
|
160
|
+
* sends, and `received` is the form that the server got them in.
|
|
161
|
+
*/
|
|
162
|
+
function callPlugins(sent, received) {
|
|
163
|
+
return [uploadPlugin(sent, received), ...valuePlugins];
|
|
164
|
+
}
|
|
165
|
+
/** The plugins of the page state, of answers and of calls without files. */
|
|
166
|
+
const plugins = callPlugins();
|
|
167
|
+
/**
|
|
168
|
+
* The plugins for the sync modes, which must throw for a value that only
|
|
169
|
+
* streams, so the page state streams instead, and a call with a stream in
|
|
170
|
+
* its arguments is not shared with another. The guard comes first, so it
|
|
171
|
+
* takes a `ReadableStream` before the plugin of `ReadableStream`, which the
|
|
172
|
+
* plugins of `Request` and `Response` bring in.
|
|
173
|
+
*/
|
|
174
|
+
const syncPlugins = [createPlugin({
|
|
175
|
+
tag: "brumate/stream-guard",
|
|
176
|
+
test: (value) => typeof ReadableStream !== "undefined" && value instanceof ReadableStream || typeof value === "object" && value !== null && Symbol.asyncIterator in value,
|
|
177
|
+
parse: { sync: () => {
|
|
178
|
+
throw new Error("A stream needs the async or stream mode");
|
|
179
|
+
} },
|
|
180
|
+
serialize: () => "",
|
|
181
|
+
deserialize: () => ({})
|
|
182
|
+
}), ...plugins];
|
|
183
|
+
/**
|
|
126
184
|
* Features that are off in both directions:
|
|
127
185
|
*
|
|
128
186
|
* - Errors keep their name and message only. A stack trace would show the
|
|
@@ -147,23 +205,30 @@ function chunk(text) {
|
|
|
147
205
|
return result;
|
|
148
206
|
}
|
|
149
207
|
/** Serializes a value as a stream of chunks. */
|
|
150
|
-
function toChunkStream(value) {
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
208
|
+
function toChunkStream(value, onCancel) {
|
|
209
|
+
let cancelled = false;
|
|
210
|
+
return new ReadableStream({
|
|
211
|
+
start(controller) {
|
|
212
|
+
toCrossJSONStream(value, {
|
|
213
|
+
refs: /* @__PURE__ */ new Map(),
|
|
214
|
+
plugins,
|
|
215
|
+
disabledFeatures,
|
|
216
|
+
onParse(node) {
|
|
217
|
+
if (!cancelled) controller.enqueue(chunk(JSON.stringify(node)));
|
|
218
|
+
},
|
|
219
|
+
onDone() {
|
|
220
|
+
if (!cancelled) controller.close();
|
|
221
|
+
},
|
|
222
|
+
onError(error) {
|
|
223
|
+
if (!cancelled) controller.error(error);
|
|
224
|
+
}
|
|
225
|
+
});
|
|
226
|
+
},
|
|
227
|
+
cancel(reason) {
|
|
228
|
+
cancelled = true;
|
|
229
|
+
onCancel?.(reason);
|
|
230
|
+
}
|
|
231
|
+
});
|
|
167
232
|
}
|
|
168
233
|
/** Reads chunks of a stream, buffering only the bytes of the chunk it waits for. */
|
|
169
234
|
var ChunkReader = class {
|
|
@@ -275,6 +340,6 @@ async function fromChunkStream(stream) {
|
|
|
275
340
|
return value;
|
|
276
341
|
}
|
|
277
342
|
//#endregion
|
|
278
|
-
export {
|
|
343
|
+
export { disabledFeatures as a, functionReferences as c, callPlugins as i, fromChunkStream as n, plugins as o, toChunkStream as r, syncPlugins as s, STREAM_TYPE as t };
|
|
279
344
|
|
|
280
|
-
//# sourceMappingURL=stream-
|
|
345
|
+
//# sourceMappingURL=stream-JaMHMdBD.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stream-JaMHMdBD.js","names":[],"sources":["../src/runtime/calls.ts","../src/runtime/serial.ts","../src/runtime/stream.ts"],"sourcesContent":["// Values that only server function calls and their serialization use. They are\n// not in `shared.ts`, which the core imports, so a page's core does not hold them.\n\nimport type { FunctionReference } from './shared.ts';\n\n/**\n * Client functions that the server passes on, such as function props, with\n * their references. Kept under a symbol of the registry, so two copies of the\n * runtime, such as a component's and the render context's, share it.\n */\nexport const functionReferences: WeakMap<object, FunctionReference> = ((\n globalThis as Record<symbol, WeakMap<object, FunctionReference> | undefined>\n)[Symbol.for('brumate.functionReferences')] ??= new WeakMap());\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 */\nexport function isBlob(value: unknown): value is Blob {\n if (typeof Blob !== 'undefined' && 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","// The seroval plugins of brumate's values. The server writes the page state\n// with them as code, and server function calls as JSON, which both sides\n// read with them. The core does not import this module: a state record\n// is code that makes its values with `stateValues`, so seroval loads in the\n// browser only with the first server function call.\n\nimport { Feature, createPlugin } from 'seroval';\nimport {\n AbortSignalPlugin,\n CustomEventPlugin,\n DOMExceptionPlugin,\n EventPlugin,\n FormDataPlugin,\n HeadersPlugin,\n ImageDataPlugin,\n ReadableStreamPlugin,\n RequestPlugin,\n ResponsePlugin,\n URLPlugin,\n URLSearchParamsPlugin,\n} from 'seroval-plugins/web';\nimport type {\n Plugin,\n SerovalNode,\n StreamParsePluginContext,\n SyncParsePluginContext,\n} from 'seroval';\nimport { isRaw, rawHTML } from './html.ts';\nimport type { Raw } from './html.ts';\nimport { functionReferences, isBlob } from './calls.ts';\nimport { ElementReference, stateValues } from './shared.ts';\nimport type { ComponentValue } from './shared.ts';\n\ntype ReferenceNode = { a: SerovalNode; b: SerovalNode };\n\n/**\n * Returns the parse functions of a plugin. `read` returns the values of the\n * node by key, and each mode parses them in that order, so the nodes match.\n */\nfunction parsers<T, K extends string>(\n read: (value: T) => Record<K, unknown>,\n): Plugin<T, Record<K, SerovalNode>>['parse'] {\n type N = Record<K, SerovalNode>;\n const parse = (value: T, ctx: SyncParsePluginContext | StreamParsePluginContext): N => {\n const node = read(value) as Record<string, unknown>;\n for (const key in node) {\n node[key] = ctx.parse(node[key]);\n }\n return node as N;\n };\n return {\n sync: parse,\n stream: parse,\n async: async (value, ctx) => {\n const node = read(value) as Record<string, unknown>;\n for (const key in node) {\n // oxlint-disable-next-line no-await-in-loop -- In order, as the other modes parse, so the IDs match.\n node[key] = await ctx.parse(node[key]);\n }\n return node as N;\n },\n };\n}\n\n// In the page state, each value is a call of `stateValues`, which the code of a record gets as `$b`.\n\n// No plugin here matches a plain object, so each one sets skipPlainObjects and seroval\n// does not run its test on object literals. Raw HTML is a class instance for this reason.\nconst ElementPlugin = createPlugin<ElementReference, ReferenceNode>({\n tag: 'brumate/element',\n skipPlainObjects: true,\n test: (value) => value instanceof ElementReference,\n parse: parsers((value) => ({ a: value.scope, b: value.anchor })),\n serialize: (node, ctx) => `$b.e(${ctx.serialize(node.a)},${ctx.serialize(node.b)})`,\n deserialize: (node, ctx) =>\n stateValues.e(ctx.deserialize<number>(node.a), ctx.deserialize<number>(node.b)),\n});\n\nconst FunctionPlugin = createPlugin<object, ReferenceNode>({\n tag: 'brumate/function',\n skipPlainObjects: true,\n test: (value) => typeof value === 'function' && functionReferences.has(value),\n parse: parsers((value) => {\n const reference = functionReferences.get(value)!;\n return { a: reference.ref, b: reference.scope };\n }),\n serialize: (node, ctx) => `$b.f(${ctx.serialize(node.a)},${ctx.serialize(node.b)})`,\n deserialize: (node, ctx) =>\n stateValues.f(ctx.deserialize<string>(node.a), ctx.deserialize<number>(node.b)),\n});\n\n/** HTML, such as the `children` of a component, so the client can insert it again. */\nconst RawPlugin = createPlugin<Raw, { h: SerovalNode }>({\n tag: 'brumate/raw',\n skipPlainObjects: true,\n test: isRaw,\n parse: parsers((value) => ({ h: rawHTML(value) })),\n serialize: (node, ctx) => `$b.r(${ctx.serialize(node.h)})`,\n deserialize: (node, ctx) => stateValues.r(ctx.deserialize<string>(node.h)),\n});\n\n/** A component in the page state, such as the value of a dynamic tag. See `stateValues.c`. */\nconst ComponentPlugin = createPlugin<ComponentValue, { c: SerovalNode }>({\n tag: 'brumate/component',\n skipPlainObjects: true,\n test: (value) =>\n typeof value === 'function' && typeof (value as Partial<ComponentValue>).brumateId === 'string',\n parse: parsers((value) => ({ c: value.brumateId })),\n serialize: (node, ctx) => `$b.c(${ctx.serialize(node.c)})`,\n deserialize: (node, ctx) => stateValues.c(ctx.deserialize<string>(node.c)),\n});\n\n/**\n * Files and blobs, which go only in the arguments of a call, as parts of\n * multipart form data named `file<index>`. The node holds the index. The\n * call passes `sent`, which gets each blob, and the server passes the form\n * that it `received`, whose files the indexes read. Without them, as in the\n * page state and in the answer of a call, a blob throws.\n */\nexport function uploadPlugin(sent?: Blob[], received?: FormData): Plugin<Blob, { i: SerovalNode }> {\n return createPlugin<Blob, { i: SerovalNode }>({\n tag: 'brumate/upload',\n skipPlainObjects: true,\n test: isBlob,\n parse: parsers((value) => {\n if (!sent) {\n throw new Error('A file or a blob can only be sent in the arguments of a server function');\n }\n return { i: sent.push(value) - 1 };\n }),\n serialize: () => {\n throw new Error('A file or a blob can only be sent in the arguments of a server function');\n },\n deserialize: (node, ctx) => {\n const file = received?.get(`file${ctx.deserialize<number>(node.i)}`);\n if (!(file instanceof Blob)) {\n throw new TypeError('A file of the call is missing');\n }\n return file;\n },\n });\n}\n\n/**\n * The plugin of `AbortSignal` from seroval-plugins, which sends whether the\n * signal aborted and its reason. The one of seroval-plugins waits for a live\n * signal to abort, so a call with one would not be sent, and a page or an\n * answer with one would not end.\n */\nconst SignalPlugin: typeof AbortSignalPlugin = {\n ...AbortSignalPlugin,\n parse: {\n sync: AbortSignalPlugin.parse.sync,\n stream: AbortSignalPlugin.parse.sync,\n async: async (value, ctx) => (value.aborted ? { reason: await ctx.parse(value.reason) } : {}),\n },\n};\n\n/**\n * The plugin of `Request` from seroval-plugins, whose body streams in the\n * stream mode. A request with a stream body needs `duplex: 'half'`, or its\n * constructor throws, so the plugin adds it.\n */\nconst BodyRequestPlugin: typeof RequestPlugin = {\n ...RequestPlugin,\n serialize: (node, ctx) =>\n `new Request(${ctx.serialize(node.url)},Object.assign(${ctx.serialize(node.options)},{duplex:\"half\"}))`,\n deserialize: (node, ctx) =>\n new Request(\n ctx.deserialize(node.url) as string,\n {\n ...(ctx.deserialize(node.options) as RequestInit),\n duplex: 'half',\n } as RequestInit,\n ),\n};\n\n/** The plugins after the plugin of uploads, which a call makes for its files. */\n// oxlint-disable-next-line typescript/no-explicit-any -- Plugin is invariant, so any is needed to hold every plugin.\nconst valuePlugins: Plugin<any, any>[] = [\n ElementPlugin,\n FunctionPlugin,\n RawPlugin,\n ComponentPlugin,\n // The web values of seroval-plugins. Requests and responses need the async or stream modes,\n // so a page state or a call result that holds one streams. The plugin of uploads takes files\n // and blobs, so those of seroval-plugins, which would put their bytes in the JSON, are left out.\n SignalPlugin,\n CustomEventPlugin,\n DOMExceptionPlugin,\n EventPlugin,\n FormDataPlugin,\n HeadersPlugin,\n ImageDataPlugin,\n ReadableStreamPlugin,\n BodyRequestPlugin,\n ResponsePlugin,\n URLPlugin,\n URLSearchParamsPlugin,\n];\n\n/**\n * The plugins of a call with files: `sent` gets the files that the call\n * sends, and `received` is the form that the server got them in.\n */\n// oxlint-disable-next-line typescript/no-explicit-any -- Plugin is invariant, so any is needed to hold every plugin.\nexport function callPlugins(sent?: Blob[], received?: FormData): Plugin<any, any>[] {\n return [uploadPlugin(sent, received), ...valuePlugins];\n}\n\n/** The plugins of the page state, of answers and of calls without files. */\n// oxlint-disable-next-line typescript/no-explicit-any -- Plugin is invariant, so any is needed to hold every plugin.\nexport const plugins: Plugin<any, any>[] = callPlugins();\n\n/**\n * Stops a sync mode at a value that only streams: an async iterable, such\n * as a `ReadableStream`. seroval writes one in a sync mode as a stream that\n * never gets its values, without an error.\n */\nconst StreamGuardPlugin = createPlugin<object, Record<string, never>>({\n tag: 'brumate/stream-guard',\n test: (value) =>\n (typeof ReadableStream !== 'undefined' && value instanceof ReadableStream) ||\n (typeof value === 'object' && value !== null && Symbol.asyncIterator in value),\n parse: {\n sync: () => {\n throw new Error('A stream needs the async or stream mode');\n },\n },\n serialize: () => '',\n deserialize: () => ({}),\n});\n\n/**\n * The plugins for the sync modes, which must throw for a value that only\n * streams, so the page state streams instead, and a call with a stream in\n * its arguments is not shared with another. The guard comes first, so it\n * takes a `ReadableStream` before the plugin of `ReadableStream`, which the\n * plugins of `Request` and `Response` bring in.\n */\n// oxlint-disable-next-line typescript/no-explicit-any -- Plugin is invariant, so any is needed to hold every plugin.\nexport const syncPlugins: Plugin<any, any>[] = [StreamGuardPlugin, ...plugins];\n\n/**\n * Features that are off in both directions:\n *\n * - Errors keep their name and message only. A stack trace would show the\n * server's files and code to the browser.\n * - Regular expressions are not sent. A pattern from a client could take\n * the server a long time to match, and reading one is refused as well.\n */\nexport const disabledFeatures: number = Feature.ErrorPrototypeStack | Feature.RegExp;\n","// The answer of a server function, as a stream of seroval chunks. Promises\n// and async iterables in the answer settle as their chunks arrive.\n//\n// Each chunk is a 12-byte header with the size of its data in bytes, as 8\n// hex digits, and the data: `;0x0000001f;{...}`. The reader knows how many\n// bytes to wait for, and can refuse a chunk that is too large.\n\nimport { Stream, fromCrossJSON, toCrossJSONStream } from 'seroval';\nimport type { SerovalNode } from 'seroval';\nimport { disabledFeatures, plugins } from './serial.ts';\n\nconst HEADER_SIZE = 12;\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\n/** The content type of a stream of chunks. */\nexport const STREAM_TYPE = 'application/x-brumate-stream';\n\n/** One chunk: its header and its data, in one array. */\nfunction chunk(text: string): Uint8Array {\n const data = encoder.encode(text);\n const result = new Uint8Array(HEADER_SIZE + data.length);\n encoder.encodeInto(`;0x${data.length.toString(16).padStart(8, '0')};`, result);\n result.set(data, HEADER_SIZE);\n return result;\n}\n\n/** Serializes a value as a stream of chunks. */\nexport function toChunkStream(\n value: unknown,\n onCancel?: (reason: unknown) => void,\n): ReadableStream<Uint8Array> {\n let cancelled = false;\n return new ReadableStream({\n start(controller) {\n toCrossJSONStream(value, {\n refs: new Map(),\n plugins,\n disabledFeatures,\n onParse(node) {\n if (!cancelled) {\n controller.enqueue(chunk(JSON.stringify(node)));\n }\n },\n onDone() {\n if (!cancelled) {\n controller.close();\n }\n },\n onError(error) {\n if (!cancelled) {\n controller.error(error);\n }\n },\n });\n },\n // The reader went away, such as a browser that aborted the call.\n cancel(reason) {\n cancelled = true;\n onCancel?.(reason);\n },\n });\n}\n\n/** Reads chunks of a stream, buffering only the bytes of the chunk it waits for. */\nclass ChunkReader {\n private readonly reader: ReadableStreamDefaultReader<Uint8Array>;\n private pieces: Uint8Array[] = [];\n private length = 0;\n private done = false;\n\n constructor(stream: ReadableStream<Uint8Array>) {\n this.reader = stream.getReader();\n }\n\n private async fill(size: number): Promise<void> {\n while (this.length < size && !this.done) {\n // oxlint-disable-next-line no-await-in-loop -- Pieces arrive in order.\n const piece = await this.reader.read();\n if (piece.done) {\n this.done = true;\n } else {\n this.pieces.push(piece.value);\n this.length += piece.value.length;\n }\n }\n }\n\n private take(size: number): Uint8Array {\n const result = new Uint8Array(size);\n let offset = 0;\n while (offset < size) {\n const piece = this.pieces[0]!;\n const count = Math.min(piece.length, size - offset);\n result.set(piece.subarray(0, count), offset);\n offset += count;\n if (count === piece.length) {\n this.pieces.shift();\n } else {\n this.pieces[0] = piece.subarray(count);\n }\n }\n this.length -= size;\n return result;\n }\n\n /** The data of the next chunk, or undefined at the end of the stream. */\n async next(): Promise<string | undefined> {\n await this.fill(HEADER_SIZE);\n if (this.length === 0) {\n return undefined;\n }\n const head = this.length < HEADER_SIZE ? '' : decoder.decode(this.take(HEADER_SIZE));\n const match = /^;0x([0-9a-f]{8});$/.exec(head);\n if (!match) {\n throw new Error('The answer of a server function is not a stream of chunks');\n }\n const size = Number.parseInt(match[1]!, 16);\n await this.fill(size);\n if (this.length < size) {\n throw new Error('The answer of a server function ended in the middle of a chunk');\n }\n return decoder.decode(this.take(size));\n }\n\n cancel(reason: unknown): void {\n this.done = true;\n void this.reader.cancel(reason).catch(() => {});\n }\n}\n\nconst ignore = (): void => {};\n\n/**\n * The refs of a stream. A promise in the answer can fail with nothing that\n * reads it, such as a field the caller ignores, so its failure is claimed\n * here. Code that awaits it still sees the failure.\n */\nclass Refs extends Map<number, unknown> {\n override set(id: number, value: unknown): this {\n if (value instanceof Promise) {\n value.catch(ignore);\n }\n return super.set(id, value);\n }\n}\n\n/**\n * Fails the promises and async iterables that still wait for a chunk, when\n * the stream ends early. Failing a settled one does nothing.\n */\nfunction failPending(refs: Refs, error: unknown): void {\n for (const value of refs.values()) {\n try {\n // The deserializer makes a Stream. A LiveStream comes only from user code, and its producer fails it.\n if (value instanceof Stream) {\n value.throw(error);\n } else if (value !== null && typeof value === 'object') {\n const resolver = value as { p?: unknown; f?: unknown };\n if (resolver.p instanceof Promise && typeof resolver.f === 'function') {\n resolver.p.catch(ignore);\n (resolver.f as (error: unknown) => void)(error);\n }\n }\n } catch {\n // A value that a plugin made, which has no such methods.\n }\n }\n}\n\n/**\n * Reads the first chunk of a stream as the value, and the rest in the\n * background, so the promises and async iterables in it settle as their\n * chunks arrive.\n */\nexport async function fromChunkStream(stream: ReadableStream<Uint8Array>): Promise<unknown> {\n const reader = new ChunkReader(stream);\n const refs = new Refs();\n const read = (data: string): unknown =>\n fromCrossJSON(JSON.parse(data) as SerovalNode, { refs, plugins, disabledFeatures });\n const first = await reader.next();\n if (first === undefined) {\n throw new Error('The answer of a server function is empty');\n }\n const value = read(first);\n void (async () => {\n try {\n for (;;) {\n // oxlint-disable-next-line no-await-in-loop -- Chunks arrive in order.\n const data = await reader.next();\n if (data === undefined) {\n break;\n }\n read(data);\n }\n failPending(refs, new Error('The answer of a server function ended early'));\n } catch (error) {\n reader.cancel(error);\n failPending(refs, error);\n }\n })();\n return value;\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAa,qBAA0D,WAErE,OAAO,IAAI,4BAA4B,uBAAO,IAAI,QAAQ;;;;;AAM5D,SAAgB,OAAO,OAA+B;CACpD,IAAI,OAAO,SAAS,eAAe,iBAAiB,MAClD,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;;;;;;;ACQA,SAAS,QACP,MAC4C;CAE5C,MAAM,SAAS,OAAU,QAA8D;EACrF,MAAM,OAAO,KAAK,KAAK;EACvB,KAAK,MAAM,OAAO,MAChB,KAAK,OAAO,IAAI,MAAM,KAAK,IAAI;EAEjC,OAAO;CACT;CACA,OAAO;EACL,MAAM;EACN,QAAQ;EACR,OAAO,OAAO,OAAO,QAAQ;GAC3B,MAAM,OAAO,KAAK,KAAK;GACvB,KAAK,MAAM,OAAO,MAEhB,KAAK,OAAO,MAAM,IAAI,MAAM,KAAK,IAAI;GAEvC,OAAO;EACT;CACF;AACF;AAMA,MAAM,gBAAgB,aAA8C;CAClE,KAAK;CACL,kBAAkB;CAClB,OAAO,UAAU,iBAAiB;CAClC,OAAO,SAAS,WAAW;EAAE,GAAG,MAAM;EAAO,GAAG,MAAM;CAAO,EAAE;CAC/D,YAAY,MAAM,QAAQ,QAAQ,IAAI,UAAU,KAAK,CAAC,EAAE,GAAG,IAAI,UAAU,KAAK,CAAC,EAAE;CACjF,cAAc,MAAM,QAClB,YAAY,EAAE,IAAI,YAAoB,K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MA,SAAS,YAAY,MAAY,OAAsB;CACrD,KAAK,MAAM,SAAS,KAAK,OAAO,GAC9B,IAAI;EAEF,IAAI,iBAAiB,QACnB,MAAM,MAAM,KAAK;OACZ,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;GACtD,MAAM,WAAW;GACjB,IAAI,SAAS,aAAa,WAAW,OAAO,SAAS,MAAM,YAAY;IACrE,SAAS,EAAE,MAAM,MAAM;IACvB,SAAU,EAA+B,KAAK;GAChD;EACF;CACF,QAAQ,CAER;AAEJ;;;;;;AAOA,eAAsB,gBAAgB,QAAsD;CAC1F,MAAM,SAAS,IAAI,YAAY,MAAM;CACrC,MAAM,OAAO,IAAI,KAAK;CACtB,MAAM,QAAQ,SACZ,cAAc,KAAK,MAAM,IAAI,GAAkB;EAAE;EAAM;EAAS;CAAiB,CAAC;CACpF,MAAM,QAAQ,MAAM,OAAO,KAAK;CAChC,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MAAM,0CAA0C;CAE5D,MAAM,QAAQ,KAAK,KAAK;CACxB,CAAM,YAAY;EAChB,IAAI;GACF,SAAS;IAEP,MAAM,OAAO,MAAM,OAAO,KAAK;IAC/B,IAAI,SAAS,KAAA,GACX;IAEF,KAAK,IAAI;GACX;GACA,YAAY,sBAAM,IAAI,MAAM,6CAA6C,CAAC;EAC5E,SAAS,OAAO;GACd,OAAO,OAAO,KAAK;GACnB,YAAY,MAAM,KAAK;EACzB;CACF,EAAA,CAAG;CACH,OAAO;AACT"}
|
package/dist/vite.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as NavigateOptions } from "./boot-
|
|
1
|
+
import { n as NavigateOptions } from "./boot-D-IdPy7B.js";
|
|
2
2
|
import { Plugin, ViteDevServer } from "vite";
|
|
3
3
|
//#region src/report.d.ts
|
|
4
4
|
/** Sizes in bytes, after gzip. */
|
|
@@ -7,6 +7,10 @@ interface Budget {
|
|
|
7
7
|
loader?: number;
|
|
8
8
|
/** The most that a route can load after its first event, with the core. */
|
|
9
9
|
route?: number;
|
|
10
|
+
/** What the first run of one handler loads: the component's entry, its part and the updates it runs, with what they import. */
|
|
11
|
+
event?: number;
|
|
12
|
+
/** The client code of one component. */
|
|
13
|
+
component?: number;
|
|
10
14
|
}
|
|
11
15
|
interface BuildReport {
|
|
12
16
|
/** The entry and its imports, which every page loads. */
|
|
@@ -24,6 +28,12 @@ interface BuildReport {
|
|
|
24
28
|
bytes: number;
|
|
25
29
|
components: number;
|
|
26
30
|
}[];
|
|
31
|
+
/** Each handler, with what its first run loads besides the loader and the core, largest first. */
|
|
32
|
+
events: {
|
|
33
|
+
file: string;
|
|
34
|
+
label: string;
|
|
35
|
+
bytes: number;
|
|
36
|
+
}[];
|
|
27
37
|
/** The sizes that go over the budget, as sentences. */
|
|
28
38
|
overBudget: string[];
|
|
29
39
|
}
|
|
@@ -90,6 +100,20 @@ export interface BrumateOptions {
|
|
|
90
100
|
exclude?: (directory: string) => boolean;
|
|
91
101
|
/** The directory of route files, relative to the root. Defaults to `src/routes`. */
|
|
92
102
|
routes?: string;
|
|
103
|
+
/**
|
|
104
|
+
* The entry middleware, relative to the root. Its default export runs for
|
|
105
|
+
* every request: pages, endpoints, server function calls, form posts and
|
|
106
|
+
* `#defer` bodies. Defaults to `src/middleware.ts` when the file exists.
|
|
107
|
+
* `false` runs none.
|
|
108
|
+
*/
|
|
109
|
+
middleware?: string | false;
|
|
110
|
+
/**
|
|
111
|
+
* The file of environment variables, relative to the root, which calls
|
|
112
|
+
* `defineEnv` from `brumate/env`. The server checks them when it starts,
|
|
113
|
+
* and the browser gets the file without the server variables. Defaults
|
|
114
|
+
* to `src/env.ts` when the file exists. `false` uses none.
|
|
115
|
+
*/
|
|
116
|
+
env?: string | false;
|
|
93
117
|
/**
|
|
94
118
|
* The declaration file that gives `href` of `brumate/routes` the paths of
|
|
95
119
|
* the routes, relative to the root. The plugin writes it when the routes
|
|
@@ -122,6 +146,23 @@ export interface BrumateOptions {
|
|
|
122
146
|
* the pages that its links lead to.
|
|
123
147
|
*/
|
|
124
148
|
prerender?: boolean | PrerenderOptions;
|
|
149
|
+
/**
|
|
150
|
+
* Skew protection: a page that was open before a deploy keeps working.
|
|
151
|
+
* Each build has an ID, which the page carries and sends with its calls.
|
|
152
|
+
* A call to a function that is gone, or a page of another build, makes
|
|
153
|
+
* the browser load the page in full. The client build writes its ID to
|
|
154
|
+
* `.brumate/build.json`, and the server build reads it, so build the
|
|
155
|
+
* client first. `BRUMATE_BUILD` in the environment names the ID for both.
|
|
156
|
+
*
|
|
157
|
+
* `keep` is how many earlier builds keep their files in the client
|
|
158
|
+
* output, so a page that is open still finds the code of its handlers
|
|
159
|
+
* after a deploy. The build then does not empty the output directory, and
|
|
160
|
+
* removes the files of older builds itself. Defaults to 0, which empties
|
|
161
|
+
* it as Vite does.
|
|
162
|
+
*/
|
|
163
|
+
skew?: {
|
|
164
|
+
keep?: number;
|
|
165
|
+
};
|
|
125
166
|
/**
|
|
126
167
|
* Prints what the client build ships: what every page loads before its
|
|
127
168
|
* first event, the core, the most that each route can load, and each
|