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
|
@@ -1,27 +1,18 @@
|
|
|
1
|
-
import { a as
|
|
1
|
+
import { a as disabledFeatures, i as callPlugins, n as fromChunkStream } from "./stream-JaMHMdBD.js";
|
|
2
|
+
import { ct as skew, d as build } from "./client-C0UCNL3J.js";
|
|
2
3
|
import { toJSONAsync } from "seroval";
|
|
3
4
|
//#region src/runtime/rpc.ts
|
|
4
5
|
/**
|
|
5
|
-
* True for a file or a blob. One from another frame, or another DOM, is an
|
|
6
|
-
* instance of another `Blob` class, so its methods tell instead.
|
|
7
|
-
*/
|
|
8
|
-
function isBlob(value) {
|
|
9
|
-
if (value instanceof Blob) return true;
|
|
10
|
-
const blob = value;
|
|
11
|
-
return typeof blob === "object" && blob !== null && typeof blob.size === "number" && typeof blob.type === "string" && typeof blob.arrayBuffer === "function" && typeof blob.slice === "function";
|
|
12
|
-
}
|
|
13
|
-
/**
|
|
14
6
|
* Calls a server function. It is a separate module, so pages that never call
|
|
15
7
|
* one never load seroval's serializer.
|
|
16
8
|
*
|
|
17
|
-
* Files and blobs in the arguments, in
|
|
18
|
-
*
|
|
9
|
+
* Files and blobs in the arguments, anywhere in them, go as parts of
|
|
10
|
+
* multipart form data. `signal` aborts the call.
|
|
19
11
|
*/
|
|
20
12
|
async function call(prefix, id, args, signal) {
|
|
21
13
|
const files = [];
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
plugins,
|
|
14
|
+
const json = JSON.stringify(await toJSONAsync(args, {
|
|
15
|
+
plugins: callPlugins(files),
|
|
25
16
|
disabledFeatures
|
|
26
17
|
}));
|
|
27
18
|
let init;
|
|
@@ -55,8 +46,11 @@ async function submit(prefix, id, form) {
|
|
|
55
46
|
}
|
|
56
47
|
/** Posts to a server function, and reads its answer. */
|
|
57
48
|
async function post(prefix, id, init) {
|
|
49
|
+
const headers = new Headers(init.headers);
|
|
50
|
+
if (build !== void 0) headers.set("x-brumate-build", build);
|
|
58
51
|
return answer(id, await fetch(`${prefix}/${encodeURIComponent(id)}`, {
|
|
59
52
|
...init,
|
|
53
|
+
headers,
|
|
60
54
|
method: "POST"
|
|
61
55
|
}));
|
|
62
56
|
}
|
|
@@ -78,13 +72,16 @@ async function answer(id, response) {
|
|
|
78
72
|
return new Promise(() => {});
|
|
79
73
|
}
|
|
80
74
|
if (!response.ok) {
|
|
75
|
+
if (response.status === 409 && response.headers.get("x-brumate-build")) skew("call");
|
|
81
76
|
let message = `Server function "${id}" failed with status ${response.status}`;
|
|
82
77
|
try {
|
|
83
78
|
message = (await response.json()).error;
|
|
84
79
|
} catch {}
|
|
80
|
+
const retryAfter = Number(response.headers.get("retry-after"));
|
|
85
81
|
throw Object.assign(new Error(message), {
|
|
86
82
|
name: "ServerError",
|
|
87
|
-
status: response.status
|
|
83
|
+
status: response.status,
|
|
84
|
+
...retryAfter > 0 ? { retryAfter } : {}
|
|
88
85
|
});
|
|
89
86
|
}
|
|
90
87
|
return fromChunkStream(response.body);
|
|
@@ -119,10 +116,19 @@ function sendAction(form, submitter) {
|
|
|
119
116
|
const action = form.getAttribute("b-action");
|
|
120
117
|
return import("./runtime/client.js").then(({ asyncMemo, rpcPrefix, scopes, track }) => {
|
|
121
118
|
const scope = scopes.get(scopeId);
|
|
122
|
-
if (scope)
|
|
119
|
+
if (scope) {
|
|
120
|
+
const result = submit(rpcPrefix, action, data).catch((error) => {
|
|
121
|
+
if (error.status === 409 && build !== void 0) {
|
|
122
|
+
form.submit();
|
|
123
|
+
return new Promise(() => {});
|
|
124
|
+
}
|
|
125
|
+
throw error;
|
|
126
|
+
});
|
|
127
|
+
asyncMemo(scope, slot, track(result));
|
|
128
|
+
}
|
|
123
129
|
});
|
|
124
130
|
}
|
|
125
131
|
//#endregion
|
|
126
132
|
export { call, sendAction };
|
|
127
133
|
|
|
128
|
-
//# sourceMappingURL=rpc-
|
|
134
|
+
//# sourceMappingURL=rpc-B-Zkn6Ch.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rpc-B-Zkn6Ch.js","names":[],"sources":["../src/runtime/rpc.ts"],"sourcesContent":["import { toJSONAsync } from 'seroval';\nimport { build, skew } from './client.ts';\nimport type { Scope } from './client.ts';\nimport { callPlugins, disabledFeatures } from './serial.ts';\nimport { fromChunkStream } from './stream.ts';\n\n/**\n * Calls a server function. It is a separate module, so pages that never call\n * one never load seroval's serializer.\n *\n * Files and blobs in the arguments, anywhere in them, go as parts of\n * multipart form data. `signal` aborts the call.\n */\nexport async function call(\n prefix: string,\n id: string,\n args: unknown[],\n signal?: AbortSignal,\n): Promise<unknown> {\n // The plugin of uploads takes each file and blob in the arguments, wherever it is.\n const files: Blob[] = [];\n const json = JSON.stringify(\n await toJSONAsync(args, { plugins: callPlugins(files), disabledFeatures }),\n );\n let init: RequestInit;\n if (files.length > 0) {\n const form = new FormData();\n form.set('args', json);\n // A blob of another DOM is copied, because form data takes only its own.\n const blobs = await Promise.all(\n files.map((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 : (file as Blob)\n .arrayBuffer()\n .then((data) => new Blob([data], { 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 post(prefix, id, { ...init, signal });\n}\n\n/**\n * Sends a form to a server function, and returns its result. The form data\n * goes as it is, files included, as when the browser posts the form.\n */\nexport async function submit(prefix: string, id: string, form: FormData): Promise<unknown> {\n return post(prefix, id, { headers: { 'x-brumate-result': '1' }, body: form });\n}\n\n/** Posts to a server function, and reads its answer. */\nasync function post(prefix: string, id: string, init: RequestInit): Promise<unknown> {\n const headers = new Headers(init.headers);\n // The build of the page, so the server can tell a call from before a deploy.\n if (build !== undefined) {\n headers.set('x-brumate-build', build);\n }\n return answer(\n id,\n await fetch(`${prefix}/${encodeURIComponent(id)}`, { ...init, headers, method: 'POST' }),\n );\n}\n\n/** Reads the answer of a server function: its result, a redirect or an error. */\nasync function answer(id: string, response: Response): Promise<unknown> {\n // The server functions whose memos load again, from `refresh` on the server.\n const refreshed = response.headers.get('x-brumate-refresh');\n if (refreshed) {\n const ids = refreshed.split(',');\n void refreshMemos(ids);\n document.dispatchEvent(new CustomEvent('brumate:refresh', { detail: ids }));\n }\n const location = response.headers.get('x-brumate-redirect');\n if (location !== null) {\n // The loader navigates on the client when it can. Without client navigation, the page loads in full.\n const redirect = new CustomEvent('brumate:redirect', { detail: location, cancelable: true });\n if (document.dispatchEvent(redirect)) {\n window.location.assign(location);\n }\n // The page is leaving, so the call never settles.\n return new Promise(() => {});\n }\n if (!response.ok) {\n // The site changed, and this page is from before. The next page loads in full.\n if (response.status === 409 && response.headers.get('x-brumate-build')) {\n skew('call');\n }\n let message = `Server function \"${id}\" failed with status ${response.status}`;\n try {\n message = ((await response.json()) as { error: string }).error;\n } catch {\n // The body is not the error of a server function.\n }\n const retryAfter = Number(response.headers.get('retry-after'));\n throw Object.assign(new Error(message), {\n name: 'ServerError',\n status: response.status,\n // The seconds to wait, for a call that a rate limit refused.\n ...(retryAfter > 0 ? { retryAfter } : {}),\n });\n }\n // Promises and async iterables in the result settle as the rest of the answer arrives.\n return fromChunkStream(response.body!);\n}\n\n// The code below reads the core with `import()`, not a static import: a module that imports\n// the core statically would make the package build move the core into a chunk of its own, behind\n// a module that only re-exports it, which a page loads one after the other. The core is loaded\n// already when it runs, so the import costs no request. It names the exports it uses, so a build\n// keeps only them.\n\n/**\n * Loads again the memos that call these server functions, after a server\n * function named them with `refresh`. Each component on the page knows its\n * own memos, from its client module. It is here, and not in the core, because\n * only the answer of a server call starts it.\n */\nexport function refreshMemos(ids: string[]): Promise<void> {\n return import('./client.ts').then(({ descendants, loadModule, loadPart, scopes }) => {\n for (const root of scopes.values()) {\n if (!root.m) {\n continue;\n }\n void loadModule(root.m).then(async (module) => {\n const entries = ids.flatMap((id) => module.refresh?.[id] ?? []);\n if (entries.length === 0) {\n return;\n }\n const updates = await loadPart(module, 'update');\n for (const [kind, name] of entries) {\n for (const target of kind === root.k ? [root] : descendants(root, kind)) {\n if (scopes.has(target.id)) {\n (updates[name] as (scope: Scope) => void)(target);\n }\n }\n }\n });\n }\n });\n}\n\n/**\n * Sends a form to the server function of its `$action`, and writes the\n * result into the `$action` when it arrives. It is pending until then. See\n * `submitAction` in the core.\n */\nexport function sendAction(form: HTMLFormElement, submitter: HTMLElement | null): Promise<void> {\n const [scopeId, slot] = form.getAttribute('b-result')!.split(':').map(Number) as [number, number];\n const data = new FormData(form, submitter);\n const action = form.getAttribute('b-action')!;\n return import('./client.ts').then(({ asyncMemo, rpcPrefix, scopes, track }) => {\n const scope = scopes.get(scopeId);\n if (scope) {\n const result = submit(rpcPrefix, action, data).catch((error: unknown) => {\n // The site changed since the page loaded. The form posts again without scripts, and the\n // page that answers is of the new build.\n if ((error as { status?: number }).status === 409 && build !== undefined) {\n form.submit();\n return new Promise(() => {});\n }\n throw error;\n });\n asyncMemo(scope, slot, track(result));\n }\n });\n}\n"],"mappings":";;;;;;;;;;;AAaA,eAAsB,KACpB,QACA,IACA,MACA,QACkB;CAElB,MAAM,QAAgB,CAAC;CACvB,MAAM,OAAO,KAAK,UAChB,MAAM,YAAY,MAAM;EAAE,SAAS,YAAY,KAAK;EAAG;CAAiB,CAAC,CAC3E;CACA,IAAI;CACJ,IAAI,MAAM,SAAS,GAAG;EACpB,MAAM,OAAO,IAAI,SAAS;EAC1B,KAAK,IAAI,QAAQ,IAAI;EAErB,MAAM,QAAQ,MAAM,QAAQ,IAC1B,MAAM,KAAK,SAET,gBAAgB,OACZ,OACC,KACE,YAAY,CAAC,CACb,MAAM,SAAS,IAAI,KAAK,CAAC,IAAI,GAAG,EAAE,MAAO,KAAc,KAAK,CAAC,CAAC,CACvE,CACF;EACA,KAAK,MAAM,CAAC,OAAO,SAAS,MAAM,QAAQ,GACxC,KAAK,IAAI,OAAO,SAAS,MAAO,MAAM,MAAM,CAAmB,QAAQ,MAAM;EAE/E,OAAO;GAAE,SAAS,EAAE,kBAAkB,OAAO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AS,OAAO,WAAW,QAAQ,IAAI,CAAC,CAAC,OAAO,UAAmB;IAGvE,IAAK,MAA8B,WAAW,OAAO,UAAU,KAAA,GAAW;KACxE,KAAK,OAAO;KACZ,OAAO,IAAI,cAAc,CAAC,CAAC;IAC7B;IACA,MAAM;GACR,CAAC;GACD,UAAU,OAAO,MAAM,MAAM,MAAM,CAAC;EACtC;CACF,CAAC;AACH"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
//#region src/runtime/batch.d.ts
|
|
2
|
+
export interface BatchOptions<K> {
|
|
3
|
+
/**
|
|
4
|
+
* What makes two calls the same key. Defaults to the key itself, and to
|
|
5
|
+
* its JSON for an object.
|
|
6
|
+
*/
|
|
7
|
+
key?: (key: K) => unknown;
|
|
8
|
+
/** The most keys in one call. A larger batch becomes several calls. */
|
|
9
|
+
limit?: number;
|
|
10
|
+
/** How long a batch gathers calls, in milliseconds. Defaults to 0, until the next task. */
|
|
11
|
+
wait?: number;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Gives a function of one key, whose calls in the same moment become one
|
|
15
|
+
* call of `readMany` with every distinct key. Each call gets its value from
|
|
16
|
+
* `lookup`, with what `readMany` returned and its key.
|
|
17
|
+
*
|
|
18
|
+
* A failed read rejects only the calls that it read for, and a `lookup` that
|
|
19
|
+
* throws rejects only the calls of its key.
|
|
20
|
+
*/
|
|
21
|
+
export declare function batched<K, R, V>(readMany: (keys: K[]) => R | Promise<R>, lookup: (found: R, key: K) => V, options?: BatchOptions<K>): (key: K) => Promise<Awaited<V>>;
|
|
22
|
+
//#endregion
|
|
23
|
+
//# sourceMappingURL=batch.d.ts.map
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
//#region src/runtime/batch.ts
|
|
2
|
+
/** True while the server answers a request, from `request.ts`. A symbol of the registry, so the browser has none. */
|
|
3
|
+
const IN_REQUEST = Symbol.for("brumate.inRequest");
|
|
4
|
+
/** True on the server, or in a test while server code runs. */
|
|
5
|
+
function onServer() {
|
|
6
|
+
const inRequest = globalThis[IN_REQUEST];
|
|
7
|
+
return typeof document === "undefined" || inRequest?.() === true;
|
|
8
|
+
}
|
|
9
|
+
function identity(key) {
|
|
10
|
+
return key !== null && typeof key === "object" ? JSON.stringify(key) : key;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Gives a function of one key, whose calls in the same moment become one
|
|
14
|
+
* call of `readMany` with every distinct key. Each call gets its value from
|
|
15
|
+
* `lookup`, with what `readMany` returned and its key.
|
|
16
|
+
*
|
|
17
|
+
* A failed read rejects only the calls that it read for, and a `lookup` that
|
|
18
|
+
* throws rejects only the calls of its key.
|
|
19
|
+
*/
|
|
20
|
+
function batched(readMany, lookup, options = {}) {
|
|
21
|
+
const keyOf = options.key ?? identity;
|
|
22
|
+
const limit = Math.max(1, options.limit ?? Infinity);
|
|
23
|
+
let pending = /* @__PURE__ */ new Map();
|
|
24
|
+
let timer;
|
|
25
|
+
const read = async (entries) => {
|
|
26
|
+
let found;
|
|
27
|
+
try {
|
|
28
|
+
found = await readMany(entries.map((entry) => entry.key));
|
|
29
|
+
} catch (error) {
|
|
30
|
+
for (const entry of entries) for (const waiter of entry.waiters) waiter.reject(error);
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
for (const entry of entries) try {
|
|
34
|
+
const value = lookup(found, entry.key);
|
|
35
|
+
for (const waiter of entry.waiters) waiter.resolve(value);
|
|
36
|
+
} catch (error) {
|
|
37
|
+
for (const waiter of entry.waiters) waiter.reject(error);
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
const flush = () => {
|
|
41
|
+
timer = void 0;
|
|
42
|
+
const entries = [...pending.values()];
|
|
43
|
+
pending = /* @__PURE__ */ new Map();
|
|
44
|
+
for (let start = 0; start < entries.length; start += limit) read(entries.slice(start, start + limit));
|
|
45
|
+
};
|
|
46
|
+
return (key) => {
|
|
47
|
+
if (onServer()) return (async () => lookup(await readMany([key]), key))();
|
|
48
|
+
return new Promise((resolve, reject) => {
|
|
49
|
+
const id = keyOf(key);
|
|
50
|
+
let entry = pending.get(id);
|
|
51
|
+
if (!entry) {
|
|
52
|
+
entry = {
|
|
53
|
+
key,
|
|
54
|
+
waiters: []
|
|
55
|
+
};
|
|
56
|
+
pending.set(id, entry);
|
|
57
|
+
}
|
|
58
|
+
entry.waiters.push({
|
|
59
|
+
resolve,
|
|
60
|
+
reject
|
|
61
|
+
});
|
|
62
|
+
timer ??= setTimeout(flush, options.wait ?? 0);
|
|
63
|
+
});
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
//#endregion
|
|
67
|
+
export { batched };
|
|
68
|
+
|
|
69
|
+
//# sourceMappingURL=batch.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"batch.js","names":[],"sources":["../../src/runtime/batch.ts"],"sourcesContent":["// Reads of many keys at once. In the browser, the calls of one moment, such\n// as the rows of a list that renders, become one call of a server function\n// with every key. The server renders the rows of a list one after another,\n// so there each call reads its own key at once.\n\nexport interface BatchOptions<K> {\n /**\n * What makes two calls the same key. Defaults to the key itself, and to\n * its JSON for an object.\n */\n key?: (key: K) => unknown;\n /** The most keys in one call. A larger batch becomes several calls. */\n limit?: number;\n /** How long a batch gathers calls, in milliseconds. Defaults to 0, until the next task. */\n wait?: number;\n}\n\ninterface Waiter<V> {\n resolve: (value: V) => void;\n reject: (error: unknown) => void;\n}\n\n/** True while the server answers a request, from `request.ts`. A symbol of the registry, so the browser has none. */\nconst IN_REQUEST = Symbol.for('brumate.inRequest');\n\n/** True on the server, or in a test while server code runs. */\nfunction onServer(): boolean {\n const inRequest = (globalThis as Record<symbol, (() => boolean) | undefined>)[IN_REQUEST];\n return typeof document === 'undefined' || inRequest?.() === true;\n}\n\nfunction identity(key: unknown): unknown {\n return key !== null && typeof key === 'object' ? JSON.stringify(key) : key;\n}\n\n/**\n * Gives a function of one key, whose calls in the same moment become one\n * call of `readMany` with every distinct key. Each call gets its value from\n * `lookup`, with what `readMany` returned and its key.\n *\n * A failed read rejects only the calls that it read for, and a `lookup` that\n * throws rejects only the calls of its key.\n */\nexport function batched<K, R, V>(\n readMany: (keys: K[]) => R | Promise<R>,\n lookup: (found: R, key: K) => V,\n options: BatchOptions<K> = {},\n): (key: K) => Promise<Awaited<V>> {\n const keyOf = options.key ?? identity;\n const limit = Math.max(1, options.limit ?? Infinity);\n let pending = new Map<unknown, { key: K; waiters: Waiter<Awaited<V>>[] }>();\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const read = async (entries: { key: K; waiters: Waiter<Awaited<V>>[] }[]): Promise<void> => {\n let found: R;\n try {\n found = await readMany(entries.map((entry) => entry.key));\n } catch (error) {\n for (const entry of entries) {\n for (const waiter of entry.waiters) {\n waiter.reject(error);\n }\n }\n return;\n }\n for (const entry of entries) {\n try {\n // A promise that `lookup` returns settles each call by itself.\n const value = lookup(found, entry.key) as Awaited<V>;\n for (const waiter of entry.waiters) {\n waiter.resolve(value);\n }\n } catch (error) {\n for (const waiter of entry.waiters) {\n waiter.reject(error);\n }\n }\n }\n };\n\n const flush = (): void => {\n timer = undefined;\n const entries = [...pending.values()];\n pending = new Map();\n for (let start = 0; start < entries.length; start += limit) {\n void read(entries.slice(start, start + limit));\n }\n };\n\n return (key) => {\n if (onServer()) {\n // One read for the key, at once, so it reads the event of the request and shares the\n // result of equal calls in the render.\n return (async () => lookup(await readMany([key]), key))() as Promise<Awaited<V>>;\n }\n return new Promise<Awaited<V>>((resolve, reject) => {\n const id = keyOf(key);\n let entry = pending.get(id);\n if (!entry) {\n entry = { key, waiters: [] };\n pending.set(id, entry);\n }\n entry.waiters.push({ resolve, reject });\n timer ??= setTimeout(flush, options.wait ?? 0);\n });\n };\n}\n"],"mappings":";;AAuBA,MAAM,aAAa,OAAO,IAAI,mBAAmB;;AAGjD,SAAS,WAAoB;CAC3B,MAAM,YAAa,WAA2D;CAC9E,OAAO,OAAO,aAAa,eAAe,YAAY,MAAM;AAC9D;AAEA,SAAS,SAAS,KAAuB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AE;IAC3B,QAAQ,IAAI,IAAI,KAAK;GACvB;GACA,MAAM,QAAQ,KAAK;IAAE;IAAS;GAAO,CAAC;GACtC,UAAU,WAAW,OAAO,QAAQ,QAAQ,CAAC;EAC/C,CAAC;CACH;AACF"}
|
package/dist/runtime/client.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as attribute,
|
|
2
|
-
import { n as ElementReference, r as FunctionReference, t as produce } from "../produce-
|
|
3
|
-
import {
|
|
4
|
-
import { $ as
|
|
5
|
-
export { ClientModule, Component, CoreOptions, DEVTOOLS, DevtoolsHooks, ElementReference, FunctionReference, HiddenBody, Part, type Raw, Scope, action, addHead, addPortal, addStyle, affix, afterInsert, asyncMemo, attr, attribute, attrs, branch, cells, classAttribute, component, consumeContext, content, createContext, createScope, descendants, dispose, dynamic, effect, elementAt, escape, fill, forget, get, guess, handle, handlerProp, hooks, init, insert, leavePage, leaveRoutes, list, loadModule, loadPart, loader, makeId, memo, offscreen, pending, portalTo, produce, prop, provideValue, raw, rekey, remount, removeRoot, removeScope, reset, rpc, rpcPrefix, scopeOf, scopes, set, setItem, setOwner, setSlots, setVar, spread, submitAction, text, title, track, update, updateContext, vars, writeText };
|
|
1
|
+
import { a as attribute, g as spread, i as affix, l as escape, m as raw, p as mergeAttributes, s as classAttribute, t as Raw, y as vars } from "../html-y1q7-t7D.js";
|
|
2
|
+
import { n as ElementReference, r as FunctionReference, t as produce } from "../produce-D4K7qpaL.js";
|
|
3
|
+
import { c as routeContext, o as createContext, s as navigationContext } from "../context-btHuB01Z.js";
|
|
4
|
+
import { $ as provideValue, A as elementAt, B as insert, C as content, Ct as updateRoute, D as dispose, E as descendants, F as guess, G as loadPart, H as leaveRoutes, I as handle, J as memo, K as loader, L as handlerProp, M as fill, N as forget, O as dynamic, P as get, Q as prop, R as hooks, S as consumeContext, St as updateContext, T as deferInBrowser, U as list, V as leavePage, W as loadModule, X as pending, Y as offscreen, Z as portalTo, _ as branch, _t as text, a as DevtoolsHooks, at as rpc, b as children, bt as track, c as Scope, ct as scopes, d as addPortal, dt as setItem, et as rekey, f as addStyle, ft as setOwner, g as attrs, gt as submitAction, h as attr, ht as skew, i as DEVTOOLS, it as reset, j as fail, k as effect, l as action, lt as set, m as asyncMemo, mt as setVar, n as Component, nt as removeRoot, o as HiddenBody, ot as rpcPrefix, p as afterInsert, pt as setSlots, q as makeId, r as CoreOptions, rt as removeScope, s as Part, st as scopeOf, t as ClientModule, tt as remount, u as addHead, ut as setGlobal, v as build, vt as timed, w as createScope, wt as writeText, x as component, xt as update, y as cells, yt as title, z as init } from "../client-MD0ZmcFR.js";
|
|
5
|
+
export { ClientModule, Component, CoreOptions, DEVTOOLS, DevtoolsHooks, ElementReference, FunctionReference, HiddenBody, Part, type Raw, Scope, action, addHead, addPortal, addStyle, affix, afterInsert, asyncMemo, attr, attribute, attrs, branch, build, cells, children, classAttribute, component, consumeContext, content, createContext, createScope, deferInBrowser, descendants, dispose, dynamic, effect, elementAt, escape, fail, fill, forget, get, guess, handle, handlerProp, hooks, init, insert, leavePage, leaveRoutes, list, loadModule, loadPart, loader, makeId, memo, mergeAttributes, navigationContext, offscreen, pending, portalTo, produce, prop, provideValue, raw, rekey, remount, removeRoot, removeScope, reset, routeContext, rpc, rpcPrefix, scopeOf, scopes, set, setGlobal, setItem, setOwner, setSlots, setVar, skew, spread, submitAction, text, timed, title, track, update, updateContext, updateRoute, vars, writeText };
|