@rsc-kit/core 0.39.0 → 0.40.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/action.d.ts +2 -0
- package/dist/action.js +19 -1
- package/dist/action.js.map +1 -1
- package/dist/hostCalls.js +10 -4
- package/dist/hostCalls.js.map +1 -1
- package/dist/js/Form.d.ts +29 -0
- package/dist/js/Form.js +161 -22
- package/dist/js/Form.js.map +1 -1
- package/dist/js/checkField.d.ts +15 -0
- package/dist/js/checkField.js +24 -0
- package/dist/js/checkField.js.map +1 -0
- package/dist/js/queryClient.d.ts +9 -0
- package/dist/js/queryClient.js +19 -0
- package/dist/js/queryClient.js.map +1 -1
- package/dist/precognition.d.ts +51 -0
- package/dist/precognition.js +113 -0
- package/dist/precognition.js.map +1 -0
- package/dist/request.d.ts +15 -0
- package/dist/request.js +37 -0
- package/dist/request.js.map +1 -1
- package/dist/vite.d.ts +8 -0
- package/dist/vite.js +56 -3
- package/dist/vite.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The FormData entry that marks an action call as a check of its fields
|
|
3
|
+
* rather than a run, holding the fields as a JSON array - every field when it
|
|
4
|
+
* is empty. Shared by `<Form>`, which sets it, and the action endpoint, which
|
|
5
|
+
* takes it out before the action sees the form. See precognition.ts.
|
|
6
|
+
*/
|
|
7
|
+
export declare const CHECK_FIELD = "$rsc:validate";
|
|
8
|
+
/**
|
|
9
|
+
* Laravel's matching for Precognition-Validate-Only: a field named exactly,
|
|
10
|
+
* or by a pattern whose `*` stands for one segment - `items.*.name`. No
|
|
11
|
+
* patterns is every field.
|
|
12
|
+
*/
|
|
13
|
+
export declare function fieldMatches(field: string, patterns: readonly string[]): boolean;
|
|
14
|
+
/** The errors about the fields named, and none of the others. */
|
|
15
|
+
export declare function errorsFor(errors: Record<string, string[]>, patterns: readonly string[]): Record<string, string[]>;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The FormData entry that marks an action call as a check of its fields
|
|
3
|
+
* rather than a run, holding the fields as a JSON array - every field when it
|
|
4
|
+
* is empty. Shared by `<Form>`, which sets it, and the action endpoint, which
|
|
5
|
+
* takes it out before the action sees the form. See precognition.ts.
|
|
6
|
+
*/
|
|
7
|
+
export const CHECK_FIELD = "$rsc:validate";
|
|
8
|
+
/**
|
|
9
|
+
* Laravel's matching for Precognition-Validate-Only: a field named exactly,
|
|
10
|
+
* or by a pattern whose `*` stands for one segment - `items.*.name`. No
|
|
11
|
+
* patterns is every field.
|
|
12
|
+
*/
|
|
13
|
+
export function fieldMatches(field, patterns) {
|
|
14
|
+
if (patterns.length === 0)
|
|
15
|
+
return true;
|
|
16
|
+
return patterns.some((pattern) => pattern.includes("*")
|
|
17
|
+
? new RegExp("^" + pattern.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join("[^.]+") + "$").test(field)
|
|
18
|
+
: pattern === field);
|
|
19
|
+
}
|
|
20
|
+
/** The errors about the fields named, and none of the others. */
|
|
21
|
+
export function errorsFor(errors, patterns) {
|
|
22
|
+
return Object.fromEntries(Object.entries(errors).filter(([field]) => fieldMatches(field, patterns)));
|
|
23
|
+
}
|
|
24
|
+
//# sourceMappingURL=checkField.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"checkField.js","sourceRoot":"","sources":["../../src/js/checkField.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,eAAe,CAAC;AAE3C;;;;GAIG;AACH,MAAM,UAAU,YAAY,CAAC,KAAa,EAAE,QAA2B;IACrE,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IAEvC,OAAO,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAC/B,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC;QACnB,CAAC,CAAC,IAAI,MAAM,CACR,GAAG,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,oBAAoB,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,GAAG,CACvG,CAAC,IAAI,CAAC,KAAK,CAAC;QACf,CAAC,CAAC,OAAO,KAAK,KAAK,CACtB,CAAC;AACJ,CAAC;AAED,iEAAiE;AACjE,MAAM,UAAU,SAAS,CACvB,MAAgC,EAChC,QAA2B;IAE3B,OAAO,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,EAAE,CAAC,YAAY,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;AACvG,CAAC","sourcesContent":["/**\n * The FormData entry that marks an action call as a check of its fields\n * rather than a run, holding the fields as a JSON array - every field when it\n * is empty. Shared by `<Form>`, which sets it, and the action endpoint, which\n * takes it out before the action sees the form. See precognition.ts.\n */\nexport const CHECK_FIELD = \"$rsc:validate\";\n\n/**\n * Laravel's matching for Precognition-Validate-Only: a field named exactly,\n * or by a pattern whose `*` stands for one segment - `items.*.name`. No\n * patterns is every field.\n */\nexport function fieldMatches(field: string, patterns: readonly string[]): boolean {\n if (patterns.length === 0) return true;\n\n return patterns.some((pattern) =>\n pattern.includes(\"*\")\n ? new RegExp(\n \"^\" + pattern.split(\"*\").map((part) => part.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\")).join(\"[^.]+\") + \"$\",\n ).test(field)\n : pattern === field,\n );\n}\n\n/** The errors about the fields named, and none of the others. */\nexport function errorsFor(\n errors: Record<string, string[]>,\n patterns: readonly string[],\n): Record<string, string[]> {\n return Object.fromEntries(Object.entries(errors).filter(([field]) => fieldMatches(field, patterns)));\n}\n"]}
|
package/dist/js/queryClient.d.ts
CHANGED
|
@@ -25,3 +25,12 @@ export declare function setQueryCodec(codec: {
|
|
|
25
25
|
encode: (args: unknown[]) => Promise<string | FormData>;
|
|
26
26
|
asAction: (id: string, args: unknown[]) => Promise<unknown>;
|
|
27
27
|
}): void;
|
|
28
|
+
/**
|
|
29
|
+
* Whether `fn` is a server reference, asked of Flight before anything calls
|
|
30
|
+
* it: one it can send back to the server encodes, and a function of the
|
|
31
|
+
* browser's own is refused. React keeps its registry of references private,
|
|
32
|
+
* and calling to find out would run a plain function.
|
|
33
|
+
*
|
|
34
|
+
* False wherever there is no encoder - a page with no runtime, a test.
|
|
35
|
+
*/
|
|
36
|
+
export declare function isServerReference(fn: object): Promise<boolean>;
|
package/dist/js/queryClient.js
CHANGED
|
@@ -182,4 +182,23 @@ export function setQueryCodec(codec) {
|
|
|
182
182
|
encode = codec.encode;
|
|
183
183
|
asAction = codec.asAction;
|
|
184
184
|
}
|
|
185
|
+
const references = new WeakMap();
|
|
186
|
+
/**
|
|
187
|
+
* Whether `fn` is a server reference, asked of Flight before anything calls
|
|
188
|
+
* it: one it can send back to the server encodes, and a function of the
|
|
189
|
+
* browser's own is refused. React keeps its registry of references private,
|
|
190
|
+
* and calling to find out would run a plain function.
|
|
191
|
+
*
|
|
192
|
+
* False wherever there is no encoder - a page with no runtime, a test.
|
|
193
|
+
*/
|
|
194
|
+
export function isServerReference(fn) {
|
|
195
|
+
let known = references.get(fn);
|
|
196
|
+
if (!known) {
|
|
197
|
+
known = Promise.resolve()
|
|
198
|
+
.then(() => encode([fn]))
|
|
199
|
+
.then(() => true, () => false);
|
|
200
|
+
references.set(fn, known);
|
|
201
|
+
}
|
|
202
|
+
return known;
|
|
203
|
+
}
|
|
185
204
|
//# sourceMappingURL=queryClient.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"queryClient.js","sourceRoot":"","sources":["../../src/js/queryClient.ts"],"names":[],"mappings":"AAAA,uDAAuD;AACvD,EAAE;AACF,s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A;AACjC,CAAC;AAED;;;;;;;;GAQG;AACH,IAAI,WAAW,GAAiD,GAAG,EAAE;IACnE,MAAM,IAAI,KAAK,CAAC,8DAA8D,CAAC,CAAA;AACjF,CAAC,CAAA;AAED,IAAI,MAAM,GAAoD,GAAG,EAAE;IACjE,MAAM,IAAI,KAAK,CAAC,8DAA8D,CAAC,CAAA;AACjF,CAAC,CAAA;AAED,IAAI,QAAQ,GAAsD,GAAG,EAAE;IACrE,MAAM,IAAI,KAAK,CAAC,gEAAgE,CAAC,CAAA;AACnF,CAAC,CAAA;AAED,MAAM,UAAU,aAAa,CAAC,KAI7B;IACC,WAAW,GAAG,KAAK,CAAC,WAAW,CAAA;IAC/B,MAAM,GAAG,KAAK,CAAC,MAAM,CAAA;IACrB,QAAQ,GAAG,KAAK,CAAC,QAAQ,CAAA;AAC3B,CAAC","sourcesContent":["// The browser half of `query()`: send a read as a GET.\n//\n// That is the whole of it. There is no cache here, no batching and no\n// deduplication, because TanStack Query and SWR already do those and do them\n// better — this owns the transport and they own everything above it.\n//\n// The awkward fact it is built around: a server function's id is not readable\n// from the client. React keeps it in a module-private WeakMap and exposes no\n// getter, so there is no `ref.$$id` to build a url from. What the client *can*\n// do is call the reference and be handed the id by React itself — the stub's\n// whole body is `callServer(id, args)`, and this package already owns\n// `callServer`.\n//\n// So a read opens a one-shot slot and calls the reference; the transport claims\n// the slot and sends a GET instead of posting. The slot is also what says this\n// is a read at all: calling `getListings(kind)` directly is still a POST, and\n// `fetchQuery(getListings, [kind])` is the same call as a GET. Nothing has to\n// know a list of query ids, on either side of the build.\n\n/** Where reads are answered. Must match HEADER.queryPath on the server. */\nconst QUERY_PATH = '/_rsc/query'\n\n/**\n * Sent on every read, and required by the endpoint.\n *\n * Not decoration. A GET with no unusual header is a *simple* request, so any\n * page anywhere can trigger one with `<img src=\"…/_rsc/query?…\">` and it goes\n * out with the visitor's cookies — CORS stops the attacker reading the answer,\n * but the read still runs. This header is not CORS-safelisted, so the browser\n * preflights it, and nothing here answers a preflight.\n *\n * That restores exactly the protection a POST had: a `POST` carrying\n * `X-RSC-Action` is non-simple for the same reason.\n */\nconst QUERY_HEADER = 'X-RSC-Query'\n\n/**\n * How long a url may get before the read goes as a POST instead.\n *\n * Conservative. Proxies and CDNs start refusing somewhere between 8k and 16k,\n * and the failure is a 414 from a machine that is not ours.\n */\nconst MAX_URL = 6_000\n\ntype Reader = (...args: unknown[]) => Promise<unknown>\n\n/**\n * The slot a read opens before calling the reference.\n *\n * One-shot and synchronous: React's stub calls `callServer` in its own body\n * with nothing awaited in between, so exactly one transport call can claim it.\n */\nlet slot: { claimed: boolean; promise: Promise<unknown> | null } | null = null\n\n/**\n * Claim the open slot, if a read opened one.\n *\n * Called from the app's `callServer` before it posts. Returns null when this is\n * an ordinary action, which is every call that did not come through\n * `fetchQuery`.\n */\nexport function claimRead(id: string, args: unknown[]): Promise<unknown> | null {\n if (!slot || slot.claimed) return null\n\n slot.claimed = true\n slot.promise = send(id, args)\n\n return slot.promise\n}\n\n/**\n * Read a query, over GET.\n *\n * Hand this to a cache library and let it decide everything else:\n *\n * queryFn: () => fetchQuery(getListings, [kind])\n * useSWR(['listings', kind], () => fetchQuery(getListings, [kind]))\n *\n * Every call goes to the server, which is what a fetcher needs — staleness,\n * revalidation, retries, polling and deduplication all belong to the library\n * holding the answer, not to the thing that fetches it.\n */\nexport function fetchQuery<Data>(reference: () => Promise<Data>, args?: []): Promise<Data>\n// The query's own parameters, so a wrong key fails the typecheck rather than\n// the read. NoInfer keeps the tuple from being inferred from the call site,\n// where a wrong key would simply widen it.\nexport function fetchQuery<Args extends unknown[], Data>(\n reference: (...args: Args) => Promise<Data>,\n args: NoInfer<Args>,\n): Promise<Data>\nexport function fetchQuery<Data>(\n reference: (...args: never[]) => Promise<Data>,\n args: unknown[] = [],\n): Promise<Data> {\n if (typeof window === 'undefined') {\n // React's SSR runtime refuses a server-function call during the initial\n // render, and reaching a query's id means calling its reference — so this\n // cannot work here. Raised with the fix in it rather than left to surface\n // as React's more general message about fetch waterfalls.\n //\n // A cache library runs its fetcher in an effect, so the server render never\n // reaches this; a server component that wants the data during render should\n // await the query directly, which needs none of this.\n throw new Error(\n 'A query was read during server rendering. Read it in a server component with await, or through a cache library, whose fetcher runs after hydration.',\n )\n }\n\n const opened = { claimed: false, promise: null as Promise<unknown> | null }\n\n slot = opened\n\n try {\n // React's stub reaches callServer synchronously, so the slot is claimed by\n // the time this returns. The stub's own promise is discarded: the one the\n // transport made is the one that settles with the answer.\n ;(reference as unknown as Reader)(...(args as unknown[]))\n } finally {\n // Cleared here and nowhere else, so a reference that throws on the way in\n // does not leave the slot open for the next read to claim by accident.\n // Nothing is returned from this block: a `return` in `finally` discards\n // whatever the `try` was throwing, which would turn a reference that threw\n // synchronously into the misleading bound-reference error below.\n slot = null\n }\n\n if (!opened.claimed || !opened.promise) {\n // The only way here is a reference whose call path is asynchronous, which\n // today means one that was `.bind()`-ed. Loud, because the quiet version is\n // a read that silently went out as a POST.\n throw new Error(\n 'A query was called through a bound reference. Pass the exported query itself, unbound.',\n )\n }\n\n return opened.promise as Promise<Data>\n}\n\nasync function send(id: string, args: unknown[]): Promise<unknown> {\n const encoded = await encode(args)\n\n // encodeReply answers with FormData the moment an argument holds a File, and\n // a url cannot carry one. Rather than refuse a call that would have worked as\n // an action, the read falls back to a POST: it stops being cacheable, which\n // is the only thing it loses.\n if (typeof encoded !== 'string') return await post(id, args, 'an argument contained a File')\n\n const url = `${QUERY_PATH}?id=${encodeURIComponent(id)}&args=${encodeURIComponent(encoded)}`\n\n if (url.length > MAX_URL) return await post(id, args, 'the arguments are too large for a url')\n\n const res = await fetch(url, {\n headers: {\n [QUERY_HEADER]: '1',\n Accept: 'text/x-component',\n // Where the read came from. Same reason an action sends it: a host that\n // guards by route needs to know which page is asking.\n 'X-RSC-Referer': window.location.pathname + window.location.search,\n },\n })\n\n if (!res.ok || !res.body) {\n throw await failureFrom(res)\n }\n\n return await deserialize(res.body)\n}\n\n/**\n * What a refused read rejects with.\n *\n * A cache library reports failure by rejection, so this has to be an Error —\n * and one carrying the message the server meant, rather than a status code. A\n * validation refusal keeps its fields on `errors`, where a form can read them.\n */\nasync function failureFrom(res: Response): Promise<Error> {\n const body = await res.text().catch(() => '')\n\n try {\n const parsed = JSON.parse(body) as { message?: string; errors?: Record<string, string[]>; refusal?: unknown }\n const error = new Error(parsed.message || `Query failed: ${res.status}`) as Error & {\n errors?: unknown\n refusal?: unknown\n status?: number\n }\n\n if (parsed.errors) error.errors = parsed.errors\n // The data a refusal declared with .refusal(schema), checked on the server.\n if (parsed.refusal !== undefined) error.refusal = parsed.refusal\n error.status = res.status\n\n return error\n } catch {\n return new Error(body || `Query failed: ${res.status}`)\n }\n}\n\n/**\n * The same read, as an action.\n *\n * Reached only when the arguments cannot ride in a url. Warned about in\n * development rather than silently tolerated, because the read still works and\n * the thing that changed — it is no longer a GET, so nothing can cache it — is\n * otherwise invisible.\n */\nasync function post(id: string, args: unknown[], why: string): Promise<unknown> {\n if (import.meta.env?.DEV) {\n console.warn(`[rsc-kit] A query was sent as a POST because ${why}. It will not be cached.`)\n }\n\n return await asAction(id, args)\n}\n\n/**\n * The Flight codec and the action transport, installed by the app bootstrap.\n *\n * Injected rather than imported, and not for testing: this module is reached\n * from client components, so importing the browser runtime here would pull a\n * second copy of it into that graph — two client-reference registries, where\n * components resolve to undefined with nothing logged. The bootstrap already\n * holds the one true copy.\n */\nlet deserialize: (stream: ReadableStream) => Promise<unknown> = () => {\n throw new Error('No Flight decoder installed. createViteRscApp() sets one up.')\n}\n\nlet encode: (args: unknown[]) => Promise<string | FormData> = () => {\n throw new Error('No Flight encoder installed. createViteRscApp() sets one up.')\n}\n\nlet asAction: (id: string, args: unknown[]) => Promise<unknown> = () => {\n throw new Error('No action transport installed. createViteRscApp() sets one up.')\n}\n\nexport function setQueryCodec(codec: {\n deserialize: (stream: ReadableStream) => Promise<unknown>\n encode: (args: unknown[]) => Promise<string | FormData>\n asAction: (id: string, args: unknown[]) => Promise<unknown>\n}): void {\n deserialize = codec.deserialize\n encode = codec.encode\n asAction = codec.asAction\n}\n"]}
|
|
1
|
+
{"version":3,"file":"queryClient.js","sourceRoot":"","sources":["../../src/js/queryClient.ts"],"names":[],"mappings":"AAAA,uDAAuD;AACvD,EAAE;AACF,sEAAsE;AACtE,6EAA6E;AAC7E,qEAAqE;AACrE,EAAE;AACF,8EAA8E;AAC9E,6EAA6E;AAC7E,+EAA+E;AAC/E,6EAA6E;AAC7E,sEAAsE;AACtE,gBAAgB;AAChB,EAAE;AACF,gFAAgF;AAChF,+EAA+E;AAC/E,8EAA8E;AAC9E,8EAA8E;AAC9E,yDAAyD;AAEzD,2EAA2E;AAC3E,MAAM,UAAU,GAAG,aAAa,CAAA;AAEhC;;;;;;;;;;;GAWG;AACH,MAAM,YAAY,GAAG,aAAa,CAAA;AAElC;;;;;GAKG;AACH,MAAM,OAAO,GAAG,KAAK,CAAA;AAIrB;;;;;GAKG;AACH,IAAI,IAAI,GAAkE,IAAI,CAAA;AAE9E;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,EAAU,EAAE,IAAe;IACnD,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,OAAO;QAAE,OAAO,IAAI,CAAA;IAEtC,IAAI,CAAC,OAAO,GAAG,IAAI,CAAA;IACnB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,CAAA;IAE7B,OAAO,IAAI,CAAC,OAAO,CAAA;AACrB,CAAC;AAsBD,MAAM,UAAU,UAAU,CACxB,SAA8C,EAC9C,IAAI,GAAc,EAAE;IAEpB,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;QAClC,wEAAwE;QACxE,0EAA0E;QAC1E,0EAA0E;QAC1E,0DAA0D;QAC1D,EAAE;QACF,4EAA4E;QAC5E,4EAA4E;QAC5E,sDAAsD;QACtD,MAAM,IAAI,KAAK,CACb,qJAAqJ,CACtJ,CAAA;IACH,CAAC;IAED,MAA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ent":["// The browser half of `query()`: send a read as a GET.\n//\n// That is the whole of it. There is no cache here, no batching and no\n// deduplication, because TanStack Query and SWR already do those and do them\n// better — this owns the transport and they own everything above it.\n//\n// The awkward fact it is built around: a server function's id is not readable\n// from the client. React keeps it in a module-private WeakMap and exposes no\n// getter, so there is no `ref.$$id` to build a url from. What the client *can*\n// do is call the reference and be handed the id by React itself — the stub's\n// whole body is `callServer(id, args)`, and this package already owns\n// `callServer`.\n//\n// So a read opens a one-shot slot and calls the reference; the transport claims\n// the slot and sends a GET instead of posting. The slot is also what says this\n// is a read at all: calling `getListings(kind)` directly is still a POST, and\n// `fetchQuery(getListings, [kind])` is the same call as a GET. Nothing has to\n// know a list of query ids, on either side of the build.\n\n/** Where reads are answered. Must match HEADER.queryPath on the server. */\nconst QUERY_PATH = '/_rsc/query'\n\n/**\n * Sent on every read, and required by the endpoint.\n *\n * Not decoration. A GET with no unusual header is a *simple* request, so any\n * page anywhere can trigger one with `<img src=\"…/_rsc/query?…\">` and it goes\n * out with the visitor's cookies — CORS stops the attacker reading the answer,\n * but the read still runs. This header is not CORS-safelisted, so the browser\n * preflights it, and nothing here answers a preflight.\n *\n * That restores exactly the protection a POST had: a `POST` carrying\n * `X-RSC-Action` is non-simple for the same reason.\n */\nconst QUERY_HEADER = 'X-RSC-Query'\n\n/**\n * How long a url may get before the read goes as a POST instead.\n *\n * Conservative. Proxies and CDNs start refusing somewhere between 8k and 16k,\n * and the failure is a 414 from a machine that is not ours.\n */\nconst MAX_URL = 6_000\n\ntype Reader = (...args: unknown[]) => Promise<unknown>\n\n/**\n * The slot a read opens before calling the reference.\n *\n * One-shot and synchronous: React's stub calls `callServer` in its own body\n * with nothing awaited in between, so exactly one transport call can claim it.\n */\nlet slot: { claimed: boolean; promise: Promise<unknown> | null } | null = null\n\n/**\n * Claim the open slot, if a read opened one.\n *\n * Called from the app's `callServer` before it posts. Returns null when this is\n * an ordinary action, which is every call that did not come through\n * `fetchQuery`.\n */\nexport function claimRead(id: string, args: unknown[]): Promise<unknown> | null {\n if (!slot || slot.claimed) return null\n\n slot.claimed = true\n slot.promise = send(id, args)\n\n return slot.promise\n}\n\n/**\n * Read a query, over GET.\n *\n * Hand this to a cache library and let it decide everything else:\n *\n * queryFn: () => fetchQuery(getListings, [kind])\n * useSWR(['listings', kind], () => fetchQuery(getListings, [kind]))\n *\n * Every call goes to the server, which is what a fetcher needs — staleness,\n * revalidation, retries, polling and deduplication all belong to the library\n * holding the answer, not to the thing that fetches it.\n */\nexport function fetchQuery<Data>(reference: () => Promise<Data>, args?: []): Promise<Data>\n// The query's own parameters, so a wrong key fails the typecheck rather than\n// the read. NoInfer keeps the tuple from being inferred from the call site,\n// where a wrong key would simply widen it.\nexport function fetchQuery<Args extends unknown[], Data>(\n reference: (...args: Args) => Promise<Data>,\n args: NoInfer<Args>,\n): Promise<Data>\nexport function fetchQuery<Data>(\n reference: (...args: never[]) => Promise<Data>,\n args: unknown[] = [],\n): Promise<Data> {\n if (typeof window === 'undefined') {\n // React's SSR runtime refuses a server-function call during the initial\n // render, and reaching a query's id means calling its reference — so this\n // cannot work here. Raised with the fix in it rather than left to surface\n // as React's more general message about fetch waterfalls.\n //\n // A cache library runs its fetcher in an effect, so the server render never\n // reaches this; a server component that wants the data during render should\n // await the query directly, which needs none of this.\n throw new Error(\n 'A query was read during server rendering. Read it in a server component with await, or through a cache library, whose fetcher runs after hydration.',\n )\n }\n\n const opened = { claimed: false, promise: null as Promise<unknown> | null }\n\n slot = opened\n\n try {\n // React's stub reaches callServer synchronously, so the slot is claimed by\n // the time this returns. The stub's own promise is discarded: the one the\n // transport made is the one that settles with the answer.\n ;(reference as unknown as Reader)(...(args as unknown[]))\n } finally {\n // Cleared here and nowhere else, so a reference that throws on the way in\n // does not leave the slot open for the next read to claim by accident.\n // Nothing is returned from this block: a `return` in `finally` discards\n // whatever the `try` was throwing, which would turn a reference that threw\n // synchronously into the misleading bound-reference error below.\n slot = null\n }\n\n if (!opened.claimed || !opened.promise) {\n // The only way here is a reference whose call path is asynchronous, which\n // today means one that was `.bind()`-ed. Loud, because the quiet version is\n // a read that silently went out as a POST.\n throw new Error(\n 'A query was called through a bound reference. Pass the exported query itself, unbound.',\n )\n }\n\n return opened.promise as Promise<Data>\n}\n\nasync function send(id: string, args: unknown[]): Promise<unknown> {\n const encoded = await encode(args)\n\n // encodeReply answers with FormData the moment an argument holds a File, and\n // a url cannot carry one. Rather than refuse a call that would have worked as\n // an action, the read falls back to a POST: it stops being cacheable, which\n // is the only thing it loses.\n if (typeof encoded !== 'string') return await post(id, args, 'an argument contained a File')\n\n const url = `${QUERY_PATH}?id=${encodeURIComponent(id)}&args=${encodeURIComponent(encoded)}`\n\n if (url.length > MAX_URL) return await post(id, args, 'the arguments are too large for a url')\n\n const res = await fetch(url, {\n headers: {\n [QUERY_HEADER]: '1',\n Accept: 'text/x-component',\n // Where the read came from. Same reason an action sends it: a host that\n // guards by route needs to know which page is asking.\n 'X-RSC-Referer': window.location.pathname + window.location.search,\n },\n })\n\n if (!res.ok || !res.body) {\n throw await failureFrom(res)\n }\n\n return await deserialize(res.body)\n}\n\n/**\n * What a refused read rejects with.\n *\n * A cache library reports failure by rejection, so this has to be an Error —\n * and one carrying the message the server meant, rather than a status code. A\n * validation refusal keeps its fields on `errors`, where a form can read them.\n */\nasync function failureFrom(res: Response): Promise<Error> {\n const body = await res.text().catch(() => '')\n\n try {\n const parsed = JSON.parse(body) as { message?: string; errors?: Record<string, string[]>; refusal?: unknown }\n const error = new Error(parsed.message || `Query failed: ${res.status}`) as Error & {\n errors?: unknown\n refusal?: unknown\n status?: number\n }\n\n if (parsed.errors) error.errors = parsed.errors\n // The data a refusal declared with .refusal(schema), checked on the server.\n if (parsed.refusal !== undefined) error.refusal = parsed.refusal\n error.status = res.status\n\n return error\n } catch {\n return new Error(body || `Query failed: ${res.status}`)\n }\n}\n\n/**\n * The same read, as an action.\n *\n * Reached only when the arguments cannot ride in a url. Warned about in\n * development rather than silently tolerated, because the read still works and\n * the thing that changed — it is no longer a GET, so nothing can cache it — is\n * otherwise invisible.\n */\nasync function post(id: string, args: unknown[], why: string): Promise<unknown> {\n if (import.meta.env?.DEV) {\n console.warn(`[rsc-kit] A query was sent as a POST because ${why}. It will not be cached.`)\n }\n\n return await asAction(id, args)\n}\n\n/**\n * The Flight codec and the action transport, installed by the app bootstrap.\n *\n * Injected rather than imported, and not for testing: this module is reached\n * from client components, so importing the browser runtime here would pull a\n * second copy of it into that graph — two client-reference registries, where\n * components resolve to undefined with nothing logged. The bootstrap already\n * holds the one true copy.\n */\nlet deserialize: (stream: ReadableStream) => Promise<unknown> = () => {\n throw new Error('No Flight decoder installed. createViteRscApp() sets one up.')\n}\n\nlet encode: (args: unknown[]) => Promise<string | FormData> = () => {\n throw new Error('No Flight encoder installed. createViteRscApp() sets one up.')\n}\n\nlet asAction: (id: string, args: unknown[]) => Promise<unknown> = () => {\n throw new Error('No action transport installed. createViteRscApp() sets one up.')\n}\n\nexport function setQueryCodec(codec: {\n deserialize: (stream: ReadableStream) => Promise<unknown>\n encode: (args: unknown[]) => Promise<string | FormData>\n asAction: (id: string, args: unknown[]) => Promise<unknown>\n}): void {\n deserialize = codec.deserialize\n encode = codec.encode\n asAction = codec.asAction\n}\n\nconst references = new WeakMap<object, Promise<boolean>>()\n\n/**\n * Whether `fn` is a server reference, asked of Flight before anything calls\n * it: one it can send back to the server encodes, and a function of the\n * browser's own is refused. React keeps its registry of references private,\n * and calling to find out would run a plain function.\n *\n * False wherever there is no encoder - a page with no runtime, a test.\n */\nexport function isServerReference(fn: object): Promise<boolean> {\n let known = references.get(fn)\n\n if (!known) {\n known = Promise.resolve()\n .then(() => encode([fn]))\n .then(\n () => true,\n () => false,\n )\n references.set(fn, known)\n }\n\n return known\n}\n"]}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Checking a form's fields against the server before it is submitted.
|
|
3
|
+
*
|
|
4
|
+
* Laravel calls this Precognition: the request runs the route's middleware
|
|
5
|
+
* and its form request - authorization, then the rules for the fields named -
|
|
6
|
+
* and stops before the controller. Here it is the same idea for any backend.
|
|
7
|
+
* `<Form>` asks on blur and when its `validate()` is called, and the action's
|
|
8
|
+
* guards and validation run while its body never does.
|
|
9
|
+
*
|
|
10
|
+
* Two kinds of action can be asked:
|
|
11
|
+
*
|
|
12
|
+
* - A generated stub for a backend function the backend lists in
|
|
13
|
+
* `validates` (rsc-host.json). The stub's one host call goes out with
|
|
14
|
+
* `validate: [fields]` - empty for every field - and the backend answers
|
|
15
|
+
* as it would the call: a 422 with `validationErrors`, or a null result
|
|
16
|
+
* when the fields pass.
|
|
17
|
+
* A function the backend does not list is never sent one: a backend that
|
|
18
|
+
* has never heard of `validate` would run the call.
|
|
19
|
+
* - An action built by createActionClient with an input schema. Its schema
|
|
20
|
+
* and middleware run, and the handler is skipped.
|
|
21
|
+
*
|
|
22
|
+
* Anything else answers `unsupported`, and the form stops asking.
|
|
23
|
+
*/
|
|
24
|
+
import { CHECK_FIELD } from './js/checkField.js';
|
|
25
|
+
export { CHECK_FIELD };
|
|
26
|
+
/** What a check answers with: the fields' errors, or nothing to say. */
|
|
27
|
+
export interface Checked {
|
|
28
|
+
/** Errors for the fields that were asked about, and only those. Absent when they pass. */
|
|
29
|
+
errors?: Record<string, string[]>;
|
|
30
|
+
/** The action cannot be checked without running it. */
|
|
31
|
+
unsupported?: true;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The fields a call asks to check, when it is a check - an empty list is
|
|
35
|
+
* every field. The mark is taken out of the form, so what the action sees is
|
|
36
|
+
* the form as it was sent.
|
|
37
|
+
*
|
|
38
|
+
* A mark that cannot be read is still a mark: 'malformed', answered with
|
|
39
|
+
* nothing and never run, because whatever sent it meant a check.
|
|
40
|
+
*/
|
|
41
|
+
export declare function checkOf(args: unknown[]): string[] | 'malformed' | null;
|
|
42
|
+
/**
|
|
43
|
+
* Run `action` as a check of `fields`.
|
|
44
|
+
*
|
|
45
|
+
* Errors are kept to the fields asked about, whatever the backend sent: a
|
|
46
|
+
* schema has no notion of one field, and a backend may answer for the whole
|
|
47
|
+
* form. Anything that is not about the fields - a refusal, a redirect, a
|
|
48
|
+
* guard turning the visitor away - is no verdict on them, and is left for the
|
|
49
|
+
* submit to say.
|
|
50
|
+
*/
|
|
51
|
+
export declare function checkOnly(action: unknown, args: unknown[], fields: string[] | 'malformed'): Promise<Checked>;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Checking a form's fields against the server before it is submitted.
|
|
3
|
+
*
|
|
4
|
+
* Laravel calls this Precognition: the request runs the route's middleware
|
|
5
|
+
* and its form request - authorization, then the rules for the fields named -
|
|
6
|
+
* and stops before the controller. Here it is the same idea for any backend.
|
|
7
|
+
* `<Form>` asks on blur and when its `validate()` is called, and the action's
|
|
8
|
+
* guards and validation run while its body never does.
|
|
9
|
+
*
|
|
10
|
+
* Two kinds of action can be asked:
|
|
11
|
+
*
|
|
12
|
+
* - A generated stub for a backend function the backend lists in
|
|
13
|
+
* `validates` (rsc-host.json). The stub's one host call goes out with
|
|
14
|
+
* `validate: [fields]` - empty for every field - and the backend answers
|
|
15
|
+
* as it would the call: a 422 with `validationErrors`, or a null result
|
|
16
|
+
* when the fields pass.
|
|
17
|
+
* A function the backend does not list is never sent one: a backend that
|
|
18
|
+
* has never heard of `validate` would run the call.
|
|
19
|
+
* - An action built by createActionClient with an input schema. Its schema
|
|
20
|
+
* and middleware run, and the handler is skipped.
|
|
21
|
+
*
|
|
22
|
+
* Anything else answers `unsupported`, and the form stops asking.
|
|
23
|
+
*/
|
|
24
|
+
import { checksEarly, isActionRefusal, isActionValidationError, turnedAwayStatus } from './action.js';
|
|
25
|
+
import { isRedirectSignal } from './redirectDigest.js';
|
|
26
|
+
import { CHECK_FIELD, errorsFor } from './js/checkField.js';
|
|
27
|
+
import { beginCheck, endCheck } from './request.js';
|
|
28
|
+
export { CHECK_FIELD };
|
|
29
|
+
/**
|
|
30
|
+
* The fields a call asks to check, when it is a check - an empty list is
|
|
31
|
+
* every field. The mark is taken out of the form, so what the action sees is
|
|
32
|
+
* the form as it was sent.
|
|
33
|
+
*
|
|
34
|
+
* A mark that cannot be read is still a mark: 'malformed', answered with
|
|
35
|
+
* nothing and never run, because whatever sent it meant a check.
|
|
36
|
+
*/
|
|
37
|
+
export function checkOf(args) {
|
|
38
|
+
const form = args[args.length - 1];
|
|
39
|
+
let raw;
|
|
40
|
+
if (form instanceof FormData) {
|
|
41
|
+
if (!form.has(CHECK_FIELD))
|
|
42
|
+
return null;
|
|
43
|
+
raw = form.get(CHECK_FIELD);
|
|
44
|
+
form.delete(CHECK_FIELD);
|
|
45
|
+
}
|
|
46
|
+
else if (typeof form === 'object' && form !== null && Object.hasOwn(form, CHECK_FIELD)) {
|
|
47
|
+
// A FormData the encoder did not recognise as one arrives as its fields,
|
|
48
|
+
// an object - and the mark with them. Missed here, the check is a submit.
|
|
49
|
+
raw = form[CHECK_FIELD];
|
|
50
|
+
delete form[CHECK_FIELD];
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
try {
|
|
56
|
+
const fields = JSON.parse(String(raw));
|
|
57
|
+
if (Array.isArray(fields) && fields.every((field) => typeof field === 'string'))
|
|
58
|
+
return fields;
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
// Malformed, below.
|
|
62
|
+
}
|
|
63
|
+
return 'malformed';
|
|
64
|
+
}
|
|
65
|
+
function only(errors, fields) {
|
|
66
|
+
const kept = errorsFor(errors, fields);
|
|
67
|
+
return Object.keys(kept).length > 0 ? kept : undefined;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Run `action` as a check of `fields`.
|
|
71
|
+
*
|
|
72
|
+
* Errors are kept to the fields asked about, whatever the backend sent: a
|
|
73
|
+
* schema has no notion of one field, and a backend may answer for the whole
|
|
74
|
+
* form. Anything that is not about the fields - a refusal, a redirect, a
|
|
75
|
+
* guard turning the visitor away - is no verdict on them, and is left for the
|
|
76
|
+
* submit to say.
|
|
77
|
+
*/
|
|
78
|
+
export async function checkOnly(action, args, fields) {
|
|
79
|
+
const forms = globalThis[Symbol.for('rsc-kit.host-forms')];
|
|
80
|
+
const target = forms?.actions?.get(action);
|
|
81
|
+
const checks = target !== undefined ? forms?.validates?.has(target) === true : checksEarly(action);
|
|
82
|
+
if (!checks || typeof action !== 'function')
|
|
83
|
+
return { unsupported: true };
|
|
84
|
+
if (fields === 'malformed')
|
|
85
|
+
return {};
|
|
86
|
+
if (!beginCheck(fields, target ?? null))
|
|
87
|
+
return { unsupported: true };
|
|
88
|
+
try {
|
|
89
|
+
const result = (await action(...args));
|
|
90
|
+
// A client-built action returns its refusal rather than throwing it.
|
|
91
|
+
const errors = result?.validationErrors ? only(result.validationErrors, fields) : undefined;
|
|
92
|
+
return errors ? { errors } : {};
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
if (isActionValidationError(error)) {
|
|
96
|
+
const errors = only(error.errors, fields);
|
|
97
|
+
return errors ? { errors } : {};
|
|
98
|
+
}
|
|
99
|
+
// Not the visitor's to see on a blur, and not silent either: the submit
|
|
100
|
+
// that follows will most likely fail the same way, and this is earlier.
|
|
101
|
+
if (!isAnswer(error))
|
|
102
|
+
console.error('[rsc-kit] Checking an action\'s fields failed:', error);
|
|
103
|
+
return {};
|
|
104
|
+
}
|
|
105
|
+
finally {
|
|
106
|
+
endCheck();
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/** A refusal, a redirect or a turn-away: the backend answering, not failing. */
|
|
110
|
+
function isAnswer(error) {
|
|
111
|
+
return isActionRefusal(error) || isRedirectSignal(error) || turnedAwayStatus(error) !== null;
|
|
112
|
+
}
|
|
113
|
+
//# sourceMappingURL=precognition.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"precognition.js","sourceRoot":"","sources":["../src/precognition.ts"],"names":[],"mappings":"AAAA;;;;;;;;;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rE,MAAM,MAAM,GAAG,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,gBAAgB,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS,CAAA;QAE3F,OAAO,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAA;IACjC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,uBAAuB,CAAC,KAAK,CAAC,EAAE,CAAC;YACnC,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;YAEzC,OAAO,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAA;QACjC,CAAC;QAED,wEAAwE;QACxE,wEAAwE;QACxE,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;YAAE,OAAO,CAAC,KAAK,CAAC,gDAAgD,EAAE,KAAK,CAAC,CAAA;QAE5F,OAAO,EAAE,CAAA;IACX,CAAC;YAAS,CAAC;QACT,QAAQ,EAAE,CAAA;IACZ,CAAC;AACH,CAAC;AAED,gFAAgF;AAChF,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,eAAe,CAAC,KAAK,CAAC,IAAI,gBAAgB,CAAC,KAAK,CAAC,IAAI,gBAAgB,CAAC,KAAK,CAAC,KAAK,IAAI,CAAA;AAC9F,CAAC","sourcesContent":["/**\n * Checking a form's fields against the server before it is submitted.\n *\n * Laravel calls this Precognition: the request runs the route's middleware\n * and its form request - authorization, then the rules for the fields named -\n * and stops before the controller. Here it is the same idea for any backend.\n * `<Form>` asks on blur and when its `validate()` is called, and the action's\n * guards and validation run while its body never does.\n *\n * Two kinds of action can be asked:\n *\n * - A generated stub for a backend function the backend lists in\n * `validates` (rsc-host.json). The stub's one host call goes out with\n * `validate: [fields]` - empty for every field - and the backend answers\n * as it would the call: a 422 with `validationErrors`, or a null result\n * when the fields pass.\n * A function the backend does not list is never sent one: a backend that\n * has never heard of `validate` would run the call.\n * - An action built by createActionClient with an input schema. Its schema\n * and middleware run, and the handler is skipped.\n *\n * Anything else answers `unsupported`, and the form stops asking.\n */\n\nimport { checksEarly, isActionRefusal, isActionValidationError, turnedAwayStatus } from './action.js'\nimport { isRedirectSignal } from './redirectDigest.js'\nimport { CHECK_FIELD, errorsFor } from './js/checkField.js'\nimport { beginCheck, endCheck } from './request.js'\n\nexport { CHECK_FIELD }\n\n/** What a check answers with: the fields' errors, or nothing to say. */\nexport interface Checked {\n /** Errors for the fields that were asked about, and only those. Absent when they pass. */\n errors?: Record<string, string[]>\n /** The action cannot be checked without running it. */\n unsupported?: true\n}\n\n/**\n * The fields a call asks to check, when it is a check - an empty list is\n * every field. The mark is taken out of the form, so what the action sees is\n * the form as it was sent.\n *\n * A mark that cannot be read is still a mark: 'malformed', answered with\n * nothing and never run, because whatever sent it meant a check.\n */\nexport function checkOf(args: unknown[]): string[] | 'malformed' | null {\n const form = args[args.length - 1]\n let raw: unknown\n\n if (form instanceof FormData) {\n if (!form.has(CHECK_FIELD)) return null\n\n raw = form.get(CHECK_FIELD)\n form.delete(CHECK_FIELD)\n } else if (typeof form === 'object' && form !== null && Object.hasOwn(form, CHECK_FIELD)) {\n // A FormData the encoder did not recognise as one arrives as its fields,\n // an object - and the mark with them. Missed here, the check is a submit.\n raw = (form as Record<string, unknown>)[CHECK_FIELD]\n delete (form as Record<string, unknown>)[CHECK_FIELD]\n } else {\n return null\n }\n\n try {\n const fields = JSON.parse(String(raw)) as unknown\n\n if (Array.isArray(fields) && fields.every((field) => typeof field === 'string')) return fields\n } catch {\n // Malformed, below.\n }\n\n return 'malformed'\n}\n\nfunction only(errors: Record<string, string[]>, fields: string[]): Record<string, string[]> | undefined {\n const kept = errorsFor(errors, fields)\n\n return Object.keys(kept).length > 0 ? kept : undefined\n}\n\ninterface HostForms {\n actions?: Map<unknown, string>\n validates?: Set<string>\n}\n\n/**\n * Run `action` as a check of `fields`.\n *\n * Errors are kept to the fields asked about, whatever the backend sent: a\n * schema has no notion of one field, and a backend may answer for the whole\n * form. Anything that is not about the fields - a refusal, a redirect, a\n * guard turning the visitor away - is no verdict on them, and is left for the\n * submit to say.\n */\nexport async function checkOnly(action: unknown, args: unknown[], fields: string[] | 'malformed'): Promise<Checked> {\n const forms = (globalThis as Record<symbol, unknown>)[Symbol.for('rsc-kit.host-forms')] as HostForms | undefined\n const target = forms?.actions?.get(action)\n const checks = target !== undefined ? forms?.validates?.has(target) === true : checksEarly(action)\n\n if (!checks || typeof action !== 'function') return { unsupported: true }\n\n if (fields === 'malformed') return {}\n\n if (!beginCheck(fields, target ?? null)) return { unsupported: true }\n\n try {\n const result = (await (action as (...a: unknown[]) => unknown)(...args)) as { validationErrors?: Record<string, string[]> } | null\n\n // A client-built action returns its refusal rather than throwing it.\n const errors = result?.validationErrors ? only(result.validationErrors, fields) : undefined\n\n return errors ? { errors } : {}\n } catch (error) {\n if (isActionValidationError(error)) {\n const errors = only(error.errors, fields)\n\n return errors ? { errors } : {}\n }\n\n // Not the visitor's to see on a blur, and not silent either: the submit\n // that follows will most likely fail the same way, and this is earlier.\n if (!isAnswer(error)) console.error('[rsc-kit] Checking an action\\'s fields failed:', error)\n\n return {}\n } finally {\n endCheck()\n }\n}\n\n/** A refusal, a redirect or a turn-away: the backend answering, not failing. */\nfunction isAnswer(error: unknown): boolean {\n return isActionRefusal(error) || isRedirectSignal(error) || turnedAwayStatus(error) !== null\n}\n"]}
|
package/dist/request.d.ts
CHANGED
|
@@ -245,6 +245,21 @@ export declare function withoutVisitorCookies(request: Request): Request;
|
|
|
245
245
|
export declare function renderAsNobody(): void;
|
|
246
246
|
/** Whether the render that is open is one renderAsNobody() marked. */
|
|
247
247
|
export declare function renderingAsNobody(): boolean;
|
|
248
|
+
/**
|
|
249
|
+
* Mark this request a check of `fields` rather than a run. False when there is
|
|
250
|
+
* no request in scope to mark - and then nothing may be checked, because a
|
|
251
|
+
* mark nobody can read is a call that runs.
|
|
252
|
+
*/
|
|
253
|
+
export declare function beginCheck(fields: string[], target: string | null): boolean;
|
|
254
|
+
export declare function endCheck(): void;
|
|
255
|
+
/** Whether the action running now is only being checked: its body must not run. */
|
|
256
|
+
export declare function checkingOnly(): boolean;
|
|
257
|
+
/**
|
|
258
|
+
* The fields a host call should check instead of running, when it is the one
|
|
259
|
+
* the stub being checked makes. Null for every other call - a read a guard
|
|
260
|
+
* makes runs as it always does.
|
|
261
|
+
*/
|
|
262
|
+
export declare function checkedCall(name: string): string[] | null;
|
|
248
263
|
/**
|
|
249
264
|
* Note the tags of an answer the render used, in a render that may be kept for
|
|
250
265
|
* everyone: the kept copy is stale when any of them changes, and its Cache-Tag
|
package/dist/request.js
CHANGED
|
@@ -719,6 +719,43 @@ export function renderAsNobody() {
|
|
|
719
719
|
export function renderingAsNobody() {
|
|
720
720
|
return scope()?.getStore()?.asNobody === true;
|
|
721
721
|
}
|
|
722
|
+
/**
|
|
723
|
+
* Mark this request a check of `fields` rather than a run. False when there is
|
|
724
|
+
* no request in scope to mark - and then nothing may be checked, because a
|
|
725
|
+
* mark nobody can read is a call that runs.
|
|
726
|
+
*/
|
|
727
|
+
export function beginCheck(fields, target) {
|
|
728
|
+
const store = scope()?.getStore();
|
|
729
|
+
if (!store)
|
|
730
|
+
return false;
|
|
731
|
+
store.checking = { fields, target, sent: false };
|
|
732
|
+
return true;
|
|
733
|
+
}
|
|
734
|
+
export function endCheck() {
|
|
735
|
+
const store = scope()?.getStore();
|
|
736
|
+
if (store)
|
|
737
|
+
store.checking = undefined;
|
|
738
|
+
}
|
|
739
|
+
/** Whether the action running now is only being checked: its body must not run. */
|
|
740
|
+
export function checkingOnly() {
|
|
741
|
+
return scope()?.getStore()?.checking !== undefined;
|
|
742
|
+
}
|
|
743
|
+
/**
|
|
744
|
+
* The fields a host call should check instead of running, when it is the one
|
|
745
|
+
* the stub being checked makes. Null for every other call - a read a guard
|
|
746
|
+
* makes runs as it always does.
|
|
747
|
+
*/
|
|
748
|
+
export function checkedCall(name) {
|
|
749
|
+
const checking = scope()?.getStore()?.checking;
|
|
750
|
+
if (!checking || checking.target !== name)
|
|
751
|
+
return null;
|
|
752
|
+
// A stub makes one call. A second to the same function is not the stub's,
|
|
753
|
+
// and sending it unmarked would run what was only to be checked.
|
|
754
|
+
if (checking.sent)
|
|
755
|
+
throw new Error(`Host call ${JSON.stringify(name)} was made twice while its input was being checked.`);
|
|
756
|
+
checking.sent = true;
|
|
757
|
+
return checking.fields;
|
|
758
|
+
}
|
|
722
759
|
/**
|
|
723
760
|
* Note the tags of an answer the render used, in a render that may be kept for
|
|
724
761
|
* everyone: the kept copy is stale when any of them changes, and its Cache-Tag
|