@rsc-kit/core 0.32.0 → 0.33.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.
@@ -51,3 +51,12 @@ export declare function routableHost(segment: string, routes: readonly {
51
51
  value: string;
52
52
  }[];
53
53
  }[]): boolean;
54
+ /**
55
+ * A subdomain of the site that no route begins with is served by path, as
56
+ * the site's own: a preview deployment under the production domain keeps
57
+ * working. In development it is said, once per host - otherwise
58
+ * merchant.example.test showed the home page and nothing said why.
59
+ */
60
+ export declare function unroutedHostMessage(host: string, segment: string): string;
61
+ /** Says unroutedHostMessage once per host; what the dev server passes as onUnroutedHost. */
62
+ export declare function sayUnroutedHost(host: string, segment: string): void;
@@ -97,4 +97,23 @@ export function routableHost(segment, routes) {
97
97
  }
98
98
  return false;
99
99
  }
100
+ /**
101
+ * A subdomain of the site that no route begins with is served by path, as
102
+ * the site's own: a preview deployment under the production domain keeps
103
+ * working. In development it is said, once per host - otherwise
104
+ * merchant.example.test showed the home page and nothing said why.
105
+ */
106
+ export function unroutedHostMessage(host, segment) {
107
+ return (`[rsc-kit] ${bareHost(host)} has no app/${segment}/ - served by path, as the site's own. ` +
108
+ `Add app/${segment}/ to route the subdomain there.`);
109
+ }
110
+ const saidUnrouted = new Set();
111
+ /** Says unroutedHostMessage once per host; what the dev server passes as onUnroutedHost. */
112
+ export function sayUnroutedHost(host, segment) {
113
+ const bare = bareHost(host);
114
+ if (saidUnrouted.has(bare))
115
+ return;
116
+ saidUnrouted.add(bare);
117
+ console.warn(unroutedHostMessage(bare, segment));
118
+ }
100
119
  //# sourceMappingURL=hostRouting.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hostRouting.js","sourceRoot":"","sources":["../src/hostRouting.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,4EAA4E;AAC5E,MAAM,UAAU,QAAQ,CAAC,IAA+B;IACtD,OAAO,CAAC,IAAI,IAAI,EAAE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ent":["/**\n * A host as a route segment.\n *\n * A request's host is matched the way Next matches one after a middleware\n * rewrite: prepended to the path. The difference is that the build can see\n * it. `admin.example.com/users` matches `app/admin/users/page.tsx`, the\n * same file `example.com/admin/users` reaches by path; `acme.example.com/`\n * matches `app/[domain]/page.tsx` with `domain = \"acme\"`; a custom domain,\n * `acme.com/`, matches the same file with `domain = \"acme.com\"`.\n *\n * What is prepended:\n * - nothing, for the site's own hosts (metadataBase, `www.` of it, and any\n * `hosts` named in rscKit()) - the apex keeps path routing, so an app\n * adds tenants without moving a file;\n * - the subdomain, for a host under an own one: `admin.example.com` ->\n * `admin`, `a.b.example.com` -> `a.b`;\n * - the whole host otherwise: `acme.com` -> `acme.com`.\n *\n * Off entirely when the build knows no own host: every request is then the\n * site's own, and nothing here changes a path.\n *\n * Pure, and the same function in the browser: a link to `/settings` on\n * `acme.example.com` is matched as `/acme/settings` on both sides, so the\n * payload the client asks for is the one the server would render.\n */\n\n/** The host without a port, lower-cased; the form every comparison uses. */\nexport function bareHost(host: string | null | undefined): string {\n return (host ?? \"\").split(\":\")[0].toLowerCase();\n}\n\n/**\n * The segment a host contributes, or null for the site's own host.\n * `own` is the build's list, already bare and lower-case.\n */\nexport function hostSegment(\n host: string | null | undefined,\n own: readonly string[],\n): string | null {\n const bare = bareHost(host);\n\n if (!bare || own.length === 0) return null;\n if (own.includes(bare)) return null;\n if (bare === \"localhost\" || /^[\\d.]+$/.test(bare) || bare.startsWith(\"[\"))\n return null;\n\n for (const site of own) {\n if (bare.endsWith(\".\" + site)) {\n const sub = bare.slice(0, -(site.length + 1));\n\n return sub === \"www\" ? null : sub;\n }\n }\n\n return bare;\n}\n\n/** The pathname to match, with the host's segment in front when it has one. */\nexport function hostPath(\n host: string | null | undefined,\n pathname: string,\n own: readonly string[],\n): string {\n const segment = hostSegment(host, own);\n\n if (segment === null) return pathname;\n\n const rest = pathname === \"/\" ? \"\" : pathname;\n\n return \"/\" + segment + rest;\n}\n\n/**\n * The site's own hosts, from what the build was told. `www.` of each is\n * included, so `www.example.com` is never a tenant called `www`.\n */\nexport function ownHosts(\n metadataBase: string | URL | null | undefined,\n hosts: readonly string[] = [],\n): string[] {\n const out = new Set<string>();\n\n if (metadataBase) {\n try {\n out.add(bareHost(new URL(String(metadataBase)).host));\n } catch {\n // Not a url the build could read; the option is checked elsewhere.\n }\n }\n\n for (const host of hosts) out.add(bareHost(host));\n\n for (const host of [...out]) {\n if (!host.startsWith(\"www.\")) out.add(\"www.\" + host);\n }\n\n return [...out].filter(Boolean).sort();\n}\n\n/**\n * Whether a host's segment is one some route can begin with: a host segment\n * ([domain] at the top of app/), or a static directory of that name. Without\n * one, the host is treated as the site's own - so an app that declares a\n * metadataBase and has no tenant tree routes every host by path, and a\n * proxy that forwards to the app by an internal name is not turned into a\n * tenant called \"internal\".\n */\nexport function routableHost(\n segment: string,\n routes: readonly { segments: readonly { type: string; value: string }[] }[],\n): boolean {\n for (const route of routes) {\n const first = route.segments[0];\n\n if (!first) continue;\n if (first.type === \"host\") return true;\n if (first.type === \"static\" && first.value === segment) return true;\n }\n\n return false;\n}\n"]}
1
+ {"version":3,"file":"hostRouting.js","sourceRoot":"","sources":["../src/hostRouting.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,4EAA4E;AAC5E,MAAM,UAAU,QAAQ,CAAC,IAA+B;IACtD,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;AAClD,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,WAAW,CACzB,IAA+B,EAC/B,GAAsB;IAEtB,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;IAE5B,IAAI,CAAC,IAAI,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IAC3C,IAAI,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC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C;IAE5B,IAAI,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC;QAAE,OAAO;IAEnC,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACvB,OAAO,CAAC,IAAI,CAAC,mBAAmB,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;AACnD,CAAC","sourcesContent":["/**\n * A host as a route segment.\n *\n * A request's host is matched the way Next matches one after a middleware\n * rewrite: prepended to the path. The difference is that the build can see\n * it. `admin.example.com/users` matches `app/admin/users/page.tsx`, the\n * same file `example.com/admin/users` reaches by path; `acme.example.com/`\n * matches `app/[domain]/page.tsx` with `domain = \"acme\"`; a custom domain,\n * `acme.com/`, matches the same file with `domain = \"acme.com\"`.\n *\n * What is prepended:\n * - nothing, for the site's own hosts (metadataBase, `www.` of it, and any\n * `hosts` named in rscKit()) - the apex keeps path routing, so an app\n * adds tenants without moving a file;\n * - the subdomain, for a host under an own one: `admin.example.com` ->\n * `admin`, `a.b.example.com` -> `a.b`;\n * - the whole host otherwise: `acme.com` -> `acme.com`.\n *\n * Off entirely when the build knows no own host: every request is then the\n * site's own, and nothing here changes a path.\n *\n * Pure, and the same function in the browser: a link to `/settings` on\n * `acme.example.com` is matched as `/acme/settings` on both sides, so the\n * payload the client asks for is the one the server would render.\n */\n\n/** The host without a port, lower-cased; the form every comparison uses. */\nexport function bareHost(host: string | null | undefined): string {\n return (host ?? \"\").split(\":\")[0].toLowerCase();\n}\n\n/**\n * The segment a host contributes, or null for the site's own host.\n * `own` is the build's list, already bare and lower-case.\n */\nexport function hostSegment(\n host: string | null | undefined,\n own: readonly string[],\n): string | null {\n const bare = bareHost(host);\n\n if (!bare || own.length === 0) return null;\n if (own.includes(bare)) return null;\n if (bare === \"localhost\" || /^[\\d.]+$/.test(bare) || bare.startsWith(\"[\"))\n return null;\n\n for (const site of own) {\n if (bare.endsWith(\".\" + site)) {\n const sub = bare.slice(0, -(site.length + 1));\n\n return sub === \"www\" ? null : sub;\n }\n }\n\n return bare;\n}\n\n/** The pathname to match, with the host's segment in front when it has one. */\nexport function hostPath(\n host: string | null | undefined,\n pathname: string,\n own: readonly string[],\n): string {\n const segment = hostSegment(host, own);\n\n if (segment === null) return pathname;\n\n const rest = pathname === \"/\" ? \"\" : pathname;\n\n return \"/\" + segment + rest;\n}\n\n/**\n * The site's own hosts, from what the build was told. `www.` of each is\n * included, so `www.example.com` is never a tenant called `www`.\n */\nexport function ownHosts(\n metadataBase: string | URL | null | undefined,\n hosts: readonly string[] = [],\n): string[] {\n const out = new Set<string>();\n\n if (metadataBase) {\n try {\n out.add(bareHost(new URL(String(metadataBase)).host));\n } catch {\n // Not a url the build could read; the option is checked elsewhere.\n }\n }\n\n for (const host of hosts) out.add(bareHost(host));\n\n for (const host of [...out]) {\n if (!host.startsWith(\"www.\")) out.add(\"www.\" + host);\n }\n\n return [...out].filter(Boolean).sort();\n}\n\n/**\n * Whether a host's segment is one some route can begin with: a host segment\n * ([domain] at the top of app/), or a static directory of that name. Without\n * one, the host is treated as the site's own - so an app that declares a\n * metadataBase and has no tenant tree routes every host by path, and a\n * proxy that forwards to the app by an internal name is not turned into a\n * tenant called \"internal\".\n */\nexport function routableHost(\n segment: string,\n routes: readonly { segments: readonly { type: string; value: string }[] }[],\n): boolean {\n for (const route of routes) {\n const first = route.segments[0];\n\n if (!first) continue;\n if (first.type === \"host\") return true;\n if (first.type === \"static\" && first.value === segment) return true;\n }\n\n return false;\n}\n\n/**\n * A subdomain of the site that no route begins with is served by path, as\n * the site's own: a preview deployment under the production domain keeps\n * working. In development it is said, once per host - otherwise\n * merchant.example.test showed the home page and nothing said why.\n */\nexport function unroutedHostMessage(host: string, segment: string): string {\n return (\n `[rsc-kit] ${bareHost(host)} has no app/${segment}/ - served by path, as the site's own. ` +\n `Add app/${segment}/ to route the subdomain there.`\n );\n}\n\nconst saidUnrouted = new Set<string>();\n\n/** Says unroutedHostMessage once per host; what the dev server passes as onUnroutedHost. */\nexport function sayUnroutedHost(host: string, segment: string): void {\n const bare = bareHost(host);\n\n if (saidUnrouted.has(bare)) return;\n\n saidUnrouted.add(bare);\n console.warn(unroutedHostMessage(bare, segment));\n}\n"]}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * A failed server action, shown on the page in development.
3
+ *
4
+ * In Vite's own error overlay - the one a broken import or a failed render
5
+ * opens - so the failure looks like every other one the developer has seen
6
+ * here. Its first line is the backend's exception when the backend threw,
7
+ * its file the first frame in the app's own code rather than the framework's,
8
+ * and the framework's frames are counted rather than listed. Where the
9
+ * overlay is not defined (the page was not served by Vite's dev server) the
10
+ * dev notice says it instead.
11
+ *
12
+ * Installed by the generated browser entry under import.meta.env.DEV, which
13
+ * Vite removes from a production build, as a hook the action's failure path
14
+ * calls: imported there directly, all of it would be in the runtime every
15
+ * production page loads.
16
+ */
17
+ export interface DescribedActionError {
18
+ message: string;
19
+ stack: string;
20
+ backend?: {
21
+ type: string;
22
+ message: string;
23
+ frames: string[];
24
+ };
25
+ }
26
+ /** What Vite's overlay takes: its message, the file it names, and the stack under it. */
27
+ export declare function overlayError(described: DescribedActionError): {
28
+ message: string;
29
+ stack: string;
30
+ id?: string;
31
+ plugin: string;
32
+ };
33
+ export declare function showDevActionError(described: DescribedActionError): void;
34
+ /**
35
+ * Read a failed action's answer for what the renderer said about it
36
+ * (devActionError.ts) and, when it said something, show it and throw it -
37
+ * the message, so the caller sees what failed rather than a status.
38
+ */
39
+ export declare function installDevActionErrors(): void;
@@ -0,0 +1,73 @@
1
+ /**
2
+ * A failed server action, shown on the page in development.
3
+ *
4
+ * In Vite's own error overlay - the one a broken import or a failed render
5
+ * opens - so the failure looks like every other one the developer has seen
6
+ * here. Its first line is the backend's exception when the backend threw,
7
+ * its file the first frame in the app's own code rather than the framework's,
8
+ * and the framework's frames are counted rather than listed. Where the
9
+ * overlay is not defined (the page was not served by Vite's dev server) the
10
+ * dev notice says it instead.
11
+ *
12
+ * Installed by the generated browser entry under import.meta.env.DEV, which
13
+ * Vite removes from a production build, as a hook the action's failure path
14
+ * calls: imported there directly, all of it would be in the runtime every
15
+ * production page loads.
16
+ */
17
+ import { showDevNotice } from "./devNotice.js";
18
+ /** A dependency's frame, not the app's: Composer's, npm's, Go's module cache. */
19
+ const DEPENDENCY = /(^|[\s/])(vendor|node_modules|pkg\/mod)\//;
20
+ /** What Vite's overlay takes: its message, the file it names, and the stack under it. */
21
+ export function overlayError(described) {
22
+ const backend = described.backend;
23
+ if (!backend)
24
+ return { message: described.message, stack: described.stack, plugin: "rsc-kit" };
25
+ const own = backend.frames.filter((frame) => !DEPENDENCY.test(frame));
26
+ const hidden = backend.frames.length - own.length;
27
+ const where = own.map((frame) => frame.split(" ")[0]).find((file) => /:\d+$/.test(file));
28
+ const lines = [
29
+ "In the backend:",
30
+ ...own.map((frame) => " at " + frame),
31
+ ...(hidden > 0 ? [` … ${hidden} more in dependencies`] : []),
32
+ "",
33
+ "In the renderer:",
34
+ described.stack,
35
+ ];
36
+ return {
37
+ message: `${backend.type}: ${backend.message}`,
38
+ stack: lines.join("\n"),
39
+ ...(where ? { id: where } : {}),
40
+ plugin: "rsc-kit",
41
+ };
42
+ }
43
+ export function showDevActionError(described) {
44
+ if (typeof document === "undefined")
45
+ return;
46
+ const error = overlayError(described);
47
+ const Overlay = typeof customElements === "undefined" ? undefined : customElements.get("vite-error-overlay");
48
+ if (!Overlay) {
49
+ showDevNotice(`${error.message}\n${error.stack}`);
50
+ return;
51
+ }
52
+ // One at a time: a second failure replaces the first, as Vite's does.
53
+ for (const open of Array.from(document.querySelectorAll("vite-error-overlay")))
54
+ open.remove();
55
+ document.body.appendChild(new Overlay(error));
56
+ }
57
+ /**
58
+ * Read a failed action's answer for what the renderer said about it
59
+ * (devActionError.ts) and, when it said something, show it and throw it -
60
+ * the message, so the caller sees what failed rather than a status.
61
+ */
62
+ export function installDevActionErrors() {
63
+ globalThis.__rscKitDevActionError = async (response) => {
64
+ if (response.headers.get("X-RSC-Dev-Error") !== "1")
65
+ return;
66
+ const described = (await response.json().catch(() => null));
67
+ if (!described?.message)
68
+ return;
69
+ showDevActionError(described);
70
+ throw new Error(described.message);
71
+ };
72
+ }
73
+ //# sourceMappingURL=devErrorOverlay.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"devErrorOverlay.js","sourceRoot":"","sources":["../../src/js/devErrorOverlay.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAQ/C,iFAAiF;AACjF,MAAM,UAAU,GAAG,2CAA2C,CAAC;AAE/D,yFAAyF;AACzF,MAAM,UAAU,YAAY,CAAC,SAA+B;IAC1D,MAAM,OAAO,GAAG,SAAS,CAAC,OAAO,CAAC;IAElC,IAAI,CAAC,OAAO;QAAE,OAAO,EAAE,OAAO,EAAE,SAAS,CAAC,OAAO,EAAE,KAAK,EAAE,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;IAE/F,MAAM,GAAG,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;IACtE,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,CAAC;IAClD,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAE,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IAC1F,MAAM,KAAK,GAAG;QACZ,iBAAiB;QACjB,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,SAAS,GAAG,KAAK,CAAC;QACxC,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC,CAA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,CAAC,GAAG,CAAC,iBAAiB,CAAC,KAAK,GAAG;YAAE,OAAO;QAE5D,MAAM,SAAS,GAAG,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAgC,CAAC;QAE3F,IAAI,CAAC,SAAS,EAAE,OAAO;YAAE,OAAO;QAEhC,kBAAkB,CAAC,SAAS,CAAC,CAAC;QAE9B,MAAM,IAAI,KAAK,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;IACrC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * A failed server action, shown on the page in development.\n *\n * In Vite's own error overlay - the one a broken import or a failed render\n * opens - so the failure looks like every other one the developer has seen\n * here. Its first line is the backend's exception when the backend threw,\n * its file the first frame in the app's own code rather than the framework's,\n * and the framework's frames are counted rather than listed. Where the\n * overlay is not defined (the page was not served by Vite's dev server) the\n * dev notice says it instead.\n *\n * Installed by the generated browser entry under import.meta.env.DEV, which\n * Vite removes from a production build, as a hook the action's failure path\n * calls: imported there directly, all of it would be in the runtime every\n * production page loads.\n */\n\nimport { showDevNotice } from \"./devNotice.js\";\n\nexport interface DescribedActionError {\n message: string;\n stack: string;\n backend?: { type: string; message: string; frames: string[] };\n}\n\n/** A dependency's frame, not the app's: Composer's, npm's, Go's module cache. */\nconst DEPENDENCY = /(^|[\\s/])(vendor|node_modules|pkg\\/mod)\\//;\n\n/** What Vite's overlay takes: its message, the file it names, and the stack under it. */\nexport function overlayError(described: DescribedActionError): { message: string; stack: string; id?: string; plugin: string } {\n const backend = described.backend;\n\n if (!backend) return { message: described.message, stack: described.stack, plugin: \"rsc-kit\" };\n\n const own = backend.frames.filter((frame) => !DEPENDENCY.test(frame));\n const hidden = backend.frames.length - own.length;\n const where = own.map((frame) => frame.split(\" \")[0]!).find((file) => /:\\d+$/.test(file));\n const lines = [\n \"In the backend:\",\n ...own.map((frame) => \" at \" + frame),\n ...(hidden > 0 ? [` … ${hidden} more in dependencies`] : []),\n \"\",\n \"In the renderer:\",\n described.stack,\n ];\n\n return {\n message: `${backend.type}: ${backend.message}`,\n stack: lines.join(\"\\n\"),\n ...(where ? { id: where } : {}),\n plugin: \"rsc-kit\",\n };\n}\n\nexport function showDevActionError(described: DescribedActionError): void {\n if (typeof document === \"undefined\") return;\n\n const error = overlayError(described);\n const Overlay = typeof customElements === \"undefined\" ? undefined : customElements.get(\"vite-error-overlay\");\n\n if (!Overlay) {\n showDevNotice(`${error.message}\\n${error.stack}`);\n\n return;\n }\n\n // One at a time: a second failure replaces the first, as Vite's does.\n for (const open of Array.from(document.querySelectorAll(\"vite-error-overlay\"))) open.remove();\n\n document.body.appendChild(new (Overlay as unknown as new (err: unknown) => HTMLElement)(error));\n}\n\n/**\n * Read a failed action's answer for what the renderer said about it\n * (devActionError.ts) and, when it said something, show it and throw it -\n * the message, so the caller sees what failed rather than a status.\n */\nexport function installDevActionErrors(): void {\n (globalThis as { __rscKitDevActionError?: (response: Response) => Promise<void> }).__rscKitDevActionError = async (response) => {\n if (response.headers.get(\"X-RSC-Dev-Error\") !== \"1\") return;\n\n const described = (await response.json().catch(() => null)) as DescribedActionError | null;\n\n if (!described?.message) return;\n\n showDevActionError(described);\n\n throw new Error(described.message);\n };\n}\n"]}
package/dist/js/errors.js CHANGED
@@ -219,6 +219,10 @@ export async function throwForFailedAction(response) {
219
219
  throw new Error("Server action refused: the request body is larger than the server accepts. " +
220
220
  "A file upload is the usual cause; the limit is the host's maxActionBody.");
221
221
  }
222
+ // In development the renderer says what failed, and the overlay shows it
223
+ // (devErrorOverlay.ts, installed by the dev browser entry only - a hook,
224
+ // so none of it is in the runtime every production page loads).
225
+ await globalThis.__rscKitDevActionError?.(response);
222
226
  throw new Error(`Server action failed with ${response.status}`);
223
227
  }
224
228
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/js/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,IAAI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AC1C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC,CAAC,QAAQ,CAAC,kBAAkB,CAAC,CAAC;AACnF,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAC,KAAa,EAAE,KAAc;IAC/D,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;QAClC,MAAM,CAAC,aAAa,CAAC,IAAI,WAAW,CAAC,kBAAkB,EAAE,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,CAAC;IAC1F,CAAC;IAED,OAAO,CAAC,KAAK,CAAC,aAAa,KAAK,EAAE,EAAE,KAAK,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["/**\n * Which of these an error is, readable by every copy of this module.\n *\n * The app's code and the server's are bundled apart, so an app can hold one\n * copy of these classes while the rpc() client throws from another - and\n * instanceof compares classes, so a server component's\n * `error instanceof ServerAuthenticationError` never matched an rpc() that\n * failed because the visitor was signed out. Each instance is marked under a\n * registry symbol both copies share, and instanceof reads the mark.\n */\nconst KIND = Symbol.for(\"rsc-kit.error-kind\");\n\nfunction mark(error: Error, kind: string): void {\n Object.defineProperty(error, KIND, { value: kind });\n}\n\nfunction isKind(value: unknown, kind: string): boolean {\n return typeof value === \"object\" && value !== null && (value as Record<symbol, unknown>)[KIND] === kind;\n}\n\nexport class ServerValidationError extends Error {\n /** Whichever copy of this module threw it; see KIND. */\n static [Symbol.hasInstance](value: unknown): boolean {\n return isKind(value, \"ServerValidationError\");\n }\n\n public readonly errors: Record<string, string[]>;\n\n constructor(message: string, errors: Record<string, string[]>) {\n super(message);\n this.name = \"ServerValidationError\";\n mark(this, \"ServerValidationError\");\n this.errors = errors;\n }\n\n /** The messages about one input or another, by field name - a nested one dot-joined. */\n get fieldErrors(): Record<string, string[]> {\n const { \"\": _form, ...fields } = this.errors;\n\n return fields;\n }\n\n /** The messages about the input as a whole, kept under \"\" in `errors`. */\n get formErrors(): string[] {\n return this.errors[\"\"] ?? [];\n }\n}\n\n/**\n * What a call to a server action resolves with when the answer was a\n * redirect: not the action's result, and never `T`.\n *\n * Resolved rather than thrown. The navigation is already under way, and a\n * caller that awaits inside `startTransition` with no catch would have its\n * rejection reach React and unmount the root - a white page on every logout.\n * So the type says what the value can be, and `isRedirected` narrows it.\n */\nexport interface Redirected {\n /** Where the visitor is being taken. */\n redirected: string;\n}\n\n/**\n * Whether this is the answer to a redirect, rather than the result you asked\n * for.\n *\n * const secret = await databasesReveal(id);\n * if (isRedirected(secret)) return; // the page is on its way to /login\n * copy(secret.Password);\n *\n * A void action needs it too: `await stub(); toast.success()` runs after the\n * redirect has started, and shows success for a write that never happened.\n */\nexport function isRedirected(value: unknown): value is Redirected {\n return typeof value === \"object\" && value !== null && typeof (value as Redirected).redirected === \"string\";\n}\n\n/**\n * A backend turned a call to a server action down, and said why.\n *\n * Thrown to whoever awaited the stub, so the code after the await - a success\n * toast, a navigation to the id it expected - does not run for a write that did\n * not happen. Not for a redirect, which resolves: that is the page being taken\n * somewhere, and a rejection inside a transition with no catch unmounts the root.\n *\n * Built in the browser from an answer the server returned, because React strips\n * the message of anything a server action throws. `<Form>` shows it as\n * `formError`, and `useAction` as `serverError`.\n */\nexport class ActionRefusedError extends Error {\n /** Whichever copy of this module threw it; see KIND. */\n static [Symbol.hasInstance](value: unknown): boolean {\n return isKind(value, \"ActionRefusedError\");\n }\n\n /** The status the backend gave it: 429 for a throttle, 503 for maintenance. */\n public readonly status: number;\n\n constructor(message: string, status: number = 409) {\n super(message);\n this.name = \"ActionRefusedError\";\n mark(this, \"ActionRefusedError\");\n this.status = status;\n }\n}\n\n/** Marks an answer that is a refusal, so a plain function's result is not mistaken for one. */\nexport const REFUSED = \"__rscRefused\";\n\n/**\n * The refusal a server action answered with, or null for a result.\n *\n * Only a plain `\"use server\"` function is answered this way - the stub the build\n * writes for a backend action is one. An action built with `createActionClient()`\n * returns its failures as its result and is never thrown for.\n */\nexport function refusalOf(\n value: unknown,\n): { message: string; status: number; errors?: Record<string, string[]> } | null {\n if (typeof value !== \"object\" || value === null) return null;\n\n const answer = value as { [REFUSED]?: unknown; serverError?: unknown; validationErrors?: unknown };\n\n if (typeof answer[REFUSED] !== \"number\") return null;\n\n // The input was refused field by field: fieldErrors() in a plain function, a\n // ValidationException behind a backend stub.\n if (typeof answer.validationErrors === \"object\" && answer.validationErrors !== null) {\n return {\n message: \"Validation failed\",\n status: answer[REFUSED],\n errors: answer.validationErrors as Record<string, string[]>,\n };\n }\n\n if (typeof answer.serverError !== \"string\") return null;\n\n return { message: answer.serverError, status: answer[REFUSED] };\n}\n\n/** An action answered with a location instead of a result. */\n/**\n * The redirect the last action answered with, for the one caller that asks.\n *\n * An action that redirects resolves - the navigation is already under way\n * and the caller has nothing to do - which leaves a form that wants to know\n * whether to say \"saved\" with no way to tell a redirect from a void answer.\n * callServer notes the destination here; <Form> clears it before its action\n * runs and reads it, always, right after its await - so a form only ever sees\n * a redirect its own action made. A note nobody reads (an action called\n * outside a Form) is cleared by the next form's submit instead of being taken\n * for that form's redirect. Nothing else needs to read it.\n */\nlet lastRedirect: string | null = null;\n\nexport function noteRedirected(location: string): void {\n lastRedirect = location;\n}\n\n/** The redirect the action just performed, if it did - read once. */\nexport function redirectedTo(): string | null {\n const location = lastRedirect;\n\n lastRedirect = null;\n\n return location;\n}\n\nexport class ServerRedirectError extends Error {\n /** Whichever copy of this module threw it; see KIND. */\n static [Symbol.hasInstance](value: unknown): boolean {\n return isKind(value, \"ServerRedirectError\");\n }\n\n public readonly location: string;\n /** What the action revalidated before it redirected. */\n public readonly revalidated: string[];\n\n constructor(location: string, revalidated: string[] = []) {\n super(`Server action redirected to ${location}`);\n this.name = \"ServerRedirectError\";\n mark(this, \"ServerRedirectError\");\n this.location = location;\n this.revalidated = revalidated;\n }\n}\n\nexport class ServerAuthenticationError extends Error {\n /** Whichever copy of this module threw it; see KIND. */\n static [Symbol.hasInstance](value: unknown): boolean {\n return isKind(value, \"ServerAuthenticationError\");\n }\n\n constructor(message: string = \"Unauthenticated.\") {\n super(message);\n this.name = \"ServerAuthenticationError\";\n mark(this, \"ServerAuthenticationError\");\n }\n}\n\nexport class ServerAuthorizationError extends Error {\n /** Whichever copy of this module threw it; see KIND. */\n static [Symbol.hasInstance](value: unknown): boolean {\n return isKind(value, \"ServerAuthorizationError\");\n }\n\n constructor(message: string = \"This action is unauthorized.\") {\n super(message);\n this.name = \"ServerAuthorizationError\";\n mark(this, \"ServerAuthorizationError\");\n }\n}\n\nexport class ServerDumpError extends Error {\n /** Whichever copy of this module threw it; see KIND. */\n static [Symbol.hasInstance](value: unknown): boolean {\n return isKind(value, \"ServerDumpError\");\n }\n\n constructor() {\n super(\"Server returned a dump response.\");\n this.name = \"ServerDumpError\";\n mark(this, \"ServerDumpError\");\n }\n}\n\nexport class ServerSessionExpiredError extends Error {\n /** Whichever copy of this module threw it; see KIND. */\n static [Symbol.hasInstance](value: unknown): boolean {\n return isKind(value, \"ServerSessionExpiredError\");\n }\n\n constructor(message: string = \"Your session has expired. Please refresh the page.\") {\n super(message);\n this.name = \"ServerSessionExpiredError\";\n mark(this, \"ServerSessionExpiredError\");\n }\n}\n\n/**\n * Turn a failed server-action response into the error it describes.\n *\n * A server action that does not succeed answers with JSON or a redirect\n * header rather than a Flight stream. Passing one of those to the Flight\n * decoder does not produce the server's message — it produces an internal\n * parser failure (\"enqueueModel is not a function\") or a truncated read\n * (\"Connection closed.\"), which is what reached onError before this existed.\n *\n * Returns without throwing when the response is a stream to be decoded.\n */\nexport async function throwForFailedAction(response: Response): Promise<void> {\n // Before the status: a redirect the action asked for is a 204 with the\n // destination in this header - an ok answer with no Flight in it - and\n // an expired session's is a 401. Read first, the header decides for both.\n // Read after `ok`, the 204 fell through to the Flight decoder with an\n // empty body, and the form waited forever.\n const location = response.headers.get(\"X-RSC-Redirect\");\n\n if (location !== null && location !== \"\") {\n throw new ServerRedirectError(\n location,\n response.headers.get(\"X-RSC-Revalidate\")?.split(\",\") ?? [],\n );\n }\n\n if (response.ok) return;\n\n if (response.status === 422) {\n const payload = (await response.json().catch(() => null)) as\n | { message?: string; errors?: Record<string, string[]> }\n | null;\n\n throw new ServerValidationError(\n payload?.message ?? \"Validation failed\",\n payload?.errors ?? {},\n );\n }\n\n if (response.status === 413) {\n throw new Error(\n \"Server action refused: the request body is larger than the server accepts. \" +\n \"A file upload is the usual cause; the limit is the host's maxActionBody.\",\n );\n }\n\n throw new Error(`Server action failed with ${response.status}`);\n}\n\n/**\n * Reject a payload response that is not one.\n *\n * The page a PPR route serves is a static shell: real HTML, status 200, with\n * its Suspense fallbacks showing. Everything below them arrives in a second\n * request. If that request fails there is nothing on screen to say so — the\n * skeletons simply stay, for ever — and handing the failure body to the Flight\n * decoder reports the decoder's confusion rather than the status.\n */\nexport function throwForFailedPayload(response: Response): void {\n if (response.ok) return;\n\n // A 404 that is a payload is the not-found page, rendered: a url a\n // pattern's shell answered with a 200 and a page that, run for real,\n // found no row - a subcategory under the wrong category. The page is\n // what the visitor should see; refusing it left the shell's content on\n // screen with nothing hydrated behind it, and every tap dead.\n if (isPayload(response)) return;\n\n throw new Error(`RSC payload request failed with ${response.status}`);\n}\n\n/** Whether a response is a Flight payload, whatever its status. */\nexport function isPayload(response: Response): boolean {\n return (response.headers.get(\"Content-Type\") ?? \"\").includes(\"text/x-component\");\n}\n\n/**\n * Announce a failure that nothing else will.\n *\n * Dispatched as well as logged: an app that wants to replace a stuck skeleton\n * with something honest has no other way to find out.\n */\nexport function reportClientFailure(scope: string, error: unknown): void {\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new CustomEvent(\"rsc-client-error\", { detail: { scope, error } }));\n }\n\n console.error(`[rsc-kit] ${scope}`, error);\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/js/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,IAAI,GAAG,MAAM,CAAC,GAAG,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,EAAE,CAAC,CAAC;AACxE,CAAC;AAED,mEAAmE;AACnE,MAAM,UAAU,SAAS,CAAC,QAAkB;IAC1C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC,CAAC,QAAQ,CAAC,kBAAkB,CAAC,CAAC;AACnF,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAC,KAAa,EAAE,KAAc;IAC/D,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;QAClC,MAAM,CAAC,aAAa,CAAC,IAAI,WAAW,CAAC,kBAAkB,EAAE,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,CAAC;IAC1F,CAAC;IAED,OAAO,CAAC,KAAK,CAAC,aAAa,KAAK,EAAE,EAAE,KAAK,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["/**\n * Which of these an error is, readable by every copy of this module.\n *\n * The app's code and the server's are bundled apart, so an app can hold one\n * copy of these classes while the rpc() client throws from another - and\n * instanceof compares classes, so a server component's\n * `error instanceof ServerAuthenticationError` never matched an rpc() that\n * failed because the visitor was signed out. Each instance is marked under a\n * registry symbol both copies share, and instanceof reads the mark.\n */\nconst KIND = Symbol.for(\"rsc-kit.error-kind\");\n\nfunction mark(error: Error, kind: string): void {\n Object.defineProperty(error, KIND, { value: kind });\n}\n\nfunction isKind(value: unknown, kind: string): boolean {\n return typeof value === \"object\" && value !== null && (value as Record<symbol, unknown>)[KIND] === kind;\n}\n\nexport class ServerValidationError extends Error {\n /** Whichever copy of this module threw it; see KIND. */\n static [Symbol.hasInstance](value: unknown): boolean {\n return isKind(value, \"ServerValidationError\");\n }\n\n public readonly errors: Record<string, string[]>;\n\n constructor(message: string, errors: Record<string, string[]>) {\n super(message);\n this.name = \"ServerValidationError\";\n mark(this, \"ServerValidationError\");\n this.errors = errors;\n }\n\n /** The messages about one input or another, by field name - a nested one dot-joined. */\n get fieldErrors(): Record<string, string[]> {\n const { \"\": _form, ...fields } = this.errors;\n\n return fields;\n }\n\n /** The messages about the input as a whole, kept under \"\" in `errors`. */\n get formErrors(): string[] {\n return this.errors[\"\"] ?? [];\n }\n}\n\n/**\n * What a call to a server action resolves with when the answer was a\n * redirect: not the action's result, and never `T`.\n *\n * Resolved rather than thrown. The navigation is already under way, and a\n * caller that awaits inside `startTransition` with no catch would have its\n * rejection reach React and unmount the root - a white page on every logout.\n * So the type says what the value can be, and `isRedirected` narrows it.\n */\nexport interface Redirected {\n /** Where the visitor is being taken. */\n redirected: string;\n}\n\n/**\n * Whether this is the answer to a redirect, rather than the result you asked\n * for.\n *\n * const secret = await databasesReveal(id);\n * if (isRedirected(secret)) return; // the page is on its way to /login\n * copy(secret.Password);\n *\n * A void action needs it too: `await stub(); toast.success()` runs after the\n * redirect has started, and shows success for a write that never happened.\n */\nexport function isRedirected(value: unknown): value is Redirected {\n return typeof value === \"object\" && value !== null && typeof (value as Redirected).redirected === \"string\";\n}\n\n/**\n * A backend turned a call to a server action down, and said why.\n *\n * Thrown to whoever awaited the stub, so the code after the await - a success\n * toast, a navigation to the id it expected - does not run for a write that did\n * not happen. Not for a redirect, which resolves: that is the page being taken\n * somewhere, and a rejection inside a transition with no catch unmounts the root.\n *\n * Built in the browser from an answer the server returned, because React strips\n * the message of anything a server action throws. `<Form>` shows it as\n * `formError`, and `useAction` as `serverError`.\n */\nexport class ActionRefusedError extends Error {\n /** Whichever copy of this module threw it; see KIND. */\n static [Symbol.hasInstance](value: unknown): boolean {\n return isKind(value, \"ActionRefusedError\");\n }\n\n /** The status the backend gave it: 429 for a throttle, 503 for maintenance. */\n public readonly status: number;\n\n constructor(message: string, status: number = 409) {\n super(message);\n this.name = \"ActionRefusedError\";\n mark(this, \"ActionRefusedError\");\n this.status = status;\n }\n}\n\n/** Marks an answer that is a refusal, so a plain function's result is not mistaken for one. */\nexport const REFUSED = \"__rscRefused\";\n\n/**\n * The refusal a server action answered with, or null for a result.\n *\n * Only a plain `\"use server\"` function is answered this way - the stub the build\n * writes for a backend action is one. An action built with `createActionClient()`\n * returns its failures as its result and is never thrown for.\n */\nexport function refusalOf(\n value: unknown,\n): { message: string; status: number; errors?: Record<string, string[]> } | null {\n if (typeof value !== \"object\" || value === null) return null;\n\n const answer = value as { [REFUSED]?: unknown; serverError?: unknown; validationErrors?: unknown };\n\n if (typeof answer[REFUSED] !== \"number\") return null;\n\n // The input was refused field by field: fieldErrors() in a plain function, a\n // ValidationException behind a backend stub.\n if (typeof answer.validationErrors === \"object\" && answer.validationErrors !== null) {\n return {\n message: \"Validation failed\",\n status: answer[REFUSED],\n errors: answer.validationErrors as Record<string, string[]>,\n };\n }\n\n if (typeof answer.serverError !== \"string\") return null;\n\n return { message: answer.serverError, status: answer[REFUSED] };\n}\n\n/** An action answered with a location instead of a result. */\n/**\n * The redirect the last action answered with, for the one caller that asks.\n *\n * An action that redirects resolves - the navigation is already under way\n * and the caller has nothing to do - which leaves a form that wants to know\n * whether to say \"saved\" with no way to tell a redirect from a void answer.\n * callServer notes the destination here; <Form> clears it before its action\n * runs and reads it, always, right after its await - so a form only ever sees\n * a redirect its own action made. A note nobody reads (an action called\n * outside a Form) is cleared by the next form's submit instead of being taken\n * for that form's redirect. Nothing else needs to read it.\n */\nlet lastRedirect: string | null = null;\n\nexport function noteRedirected(location: string): void {\n lastRedirect = location;\n}\n\n/** The redirect the action just performed, if it did - read once. */\nexport function redirectedTo(): string | null {\n const location = lastRedirect;\n\n lastRedirect = null;\n\n return location;\n}\n\nexport class ServerRedirectError extends Error {\n /** Whichever copy of this module threw it; see KIND. */\n static [Symbol.hasInstance](value: unknown): boolean {\n return isKind(value, \"ServerRedirectError\");\n }\n\n public readonly location: string;\n /** What the action revalidated before it redirected. */\n public readonly revalidated: string[];\n\n constructor(location: string, revalidated: string[] = []) {\n super(`Server action redirected to ${location}`);\n this.name = \"ServerRedirectError\";\n mark(this, \"ServerRedirectError\");\n this.location = location;\n this.revalidated = revalidated;\n }\n}\n\nexport class ServerAuthenticationError extends Error {\n /** Whichever copy of this module threw it; see KIND. */\n static [Symbol.hasInstance](value: unknown): boolean {\n return isKind(value, \"ServerAuthenticationError\");\n }\n\n constructor(message: string = \"Unauthenticated.\") {\n super(message);\n this.name = \"ServerAuthenticationError\";\n mark(this, \"ServerAuthenticationError\");\n }\n}\n\nexport class ServerAuthorizationError extends Error {\n /** Whichever copy of this module threw it; see KIND. */\n static [Symbol.hasInstance](value: unknown): boolean {\n return isKind(value, \"ServerAuthorizationError\");\n }\n\n constructor(message: string = \"This action is unauthorized.\") {\n super(message);\n this.name = \"ServerAuthorizationError\";\n mark(this, \"ServerAuthorizationError\");\n }\n}\n\nexport class ServerDumpError extends Error {\n /** Whichever copy of this module threw it; see KIND. */\n static [Symbol.hasInstance](value: unknown): boolean {\n return isKind(value, \"ServerDumpError\");\n }\n\n constructor() {\n super(\"Server returned a dump response.\");\n this.name = \"ServerDumpError\";\n mark(this, \"ServerDumpError\");\n }\n}\n\nexport class ServerSessionExpiredError extends Error {\n /** Whichever copy of this module threw it; see KIND. */\n static [Symbol.hasInstance](value: unknown): boolean {\n return isKind(value, \"ServerSessionExpiredError\");\n }\n\n constructor(message: string = \"Your session has expired. Please refresh the page.\") {\n super(message);\n this.name = \"ServerSessionExpiredError\";\n mark(this, \"ServerSessionExpiredError\");\n }\n}\n\n/**\n * Turn a failed server-action response into the error it describes.\n *\n * A server action that does not succeed answers with JSON or a redirect\n * header rather than a Flight stream. Passing one of those to the Flight\n * decoder does not produce the server's message — it produces an internal\n * parser failure (\"enqueueModel is not a function\") or a truncated read\n * (\"Connection closed.\"), which is what reached onError before this existed.\n *\n * Returns without throwing when the response is a stream to be decoded.\n */\nexport async function throwForFailedAction(response: Response): Promise<void> {\n // Before the status: a redirect the action asked for is a 204 with the\n // destination in this header - an ok answer with no Flight in it - and\n // an expired session's is a 401. Read first, the header decides for both.\n // Read after `ok`, the 204 fell through to the Flight decoder with an\n // empty body, and the form waited forever.\n const location = response.headers.get(\"X-RSC-Redirect\");\n\n if (location !== null && location !== \"\") {\n throw new ServerRedirectError(\n location,\n response.headers.get(\"X-RSC-Revalidate\")?.split(\",\") ?? [],\n );\n }\n\n if (response.ok) return;\n\n if (response.status === 422) {\n const payload = (await response.json().catch(() => null)) as\n | { message?: string; errors?: Record<string, string[]> }\n | null;\n\n throw new ServerValidationError(\n payload?.message ?? \"Validation failed\",\n payload?.errors ?? {},\n );\n }\n\n if (response.status === 413) {\n throw new Error(\n \"Server action refused: the request body is larger than the server accepts. \" +\n \"A file upload is the usual cause; the limit is the host's maxActionBody.\",\n );\n }\n\n // In development the renderer says what failed, and the overlay shows it\n // (devErrorOverlay.ts, installed by the dev browser entry only - a hook,\n // so none of it is in the runtime every production page loads).\n await (globalThis as { __rscKitDevActionError?: (r: Response) => Promise<void> }).__rscKitDevActionError?.(response);\n\n throw new Error(`Server action failed with ${response.status}`);\n}\n\n/**\n * Reject a payload response that is not one.\n *\n * The page a PPR route serves is a static shell: real HTML, status 200, with\n * its Suspense fallbacks showing. Everything below them arrives in a second\n * request. If that request fails there is nothing on screen to say so — the\n * skeletons simply stay, for ever — and handing the failure body to the Flight\n * decoder reports the decoder's confusion rather than the status.\n */\nexport function throwForFailedPayload(response: Response): void {\n if (response.ok) return;\n\n // A 404 that is a payload is the not-found page, rendered: a url a\n // pattern's shell answered with a 200 and a page that, run for real,\n // found no row - a subcategory under the wrong category. The page is\n // what the visitor should see; refusing it left the shell's content on\n // screen with nothing hydrated behind it, and every tap dead.\n if (isPayload(response)) return;\n\n throw new Error(`RSC payload request failed with ${response.status}`);\n}\n\n/** Whether a response is a Flight payload, whatever its status. */\nexport function isPayload(response: Response): boolean {\n return (response.headers.get(\"Content-Type\") ?? \"\").includes(\"text/x-component\");\n}\n\n/**\n * Announce a failure that nothing else will.\n *\n * Dispatched as well as logged: an app that wants to replace a stuck skeleton\n * with something honest has no other way to find out.\n */\nexport function reportClientFailure(scope: string, error: unknown): void {\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new CustomEvent(\"rsc-client-error\", { detail: { scope, error } }));\n }\n\n console.error(`[rsc-kit] ${scope}`, error);\n}\n"]}
@@ -0,0 +1,12 @@
1
+ export interface ShadowedRootFile {
2
+ /** The url both claim, e.g. /favicon.ico. */
3
+ url: string;
4
+ /** The file in public/ that is answered instead. */
5
+ publicFile: string;
6
+ /** The app's own, which is never reached. */
7
+ appFile: string;
8
+ /** The public/ file is empty: a placeholder, Laravel's skeleton's own. */
9
+ empty: boolean;
10
+ }
11
+ export declare function shadowedRootFiles(appDir: string, publicDir: string): ShadowedRootFile[];
12
+ export declare function shadowedRootFileMessage(file: ShadowedRootFile, root: string): string;
@@ -0,0 +1,63 @@
1
+ // A file in public/ at a url the app also answers.
2
+ //
3
+ // The app serves a few files at the site's root from beside its root layout:
4
+ // favicon.ico, robots.txt (or robots.ts), a sitemap, llms.txt. public/ is
5
+ // served at the root too, and whatever serves it - Herd's or any nginx in
6
+ // front of Laravel, Nitro's static handler - answers before the request
7
+ // reaches the app. So a file of the same name there wins, and the app's is
8
+ // never seen.
9
+ //
10
+ // It happens without anyone choosing it: Laravel's skeleton ships an empty
11
+ // public/favicon.ico and a public/robots.txt. The empty favicon answers 404
12
+ // through Herd, and the browser's console says only "favicon.ico not found"
13
+ // on an app that has one. Said at dev start and at build, naming both files.
14
+ import { existsSync, readdirSync, statSync } from "node:fs";
15
+ import { join, relative } from "node:path";
16
+ import { METADATA_ROUTES, ROOT_FILES } from "./metadataRoutes.js";
17
+ const SOURCE_EXTENSIONS = ["ts", "tsx", "js", "mjs"];
18
+ /** Every url the app's own directory answers at the root, with the file that answers it. */
19
+ function appRootFiles(appDir) {
20
+ const owned = new Map();
21
+ if (!existsSync(appDir))
22
+ return owned;
23
+ const names = readdirSync(appDir);
24
+ if (names.includes("favicon.ico"))
25
+ owned.set("favicon.ico", "favicon.ico");
26
+ for (const name of names) {
27
+ if (ROOT_FILES.test(name))
28
+ owned.set(name, name);
29
+ }
30
+ for (const [kind, { file }] of Object.entries(METADATA_ROUTES)) {
31
+ const source = SOURCE_EXTENSIONS.map((ext) => `${kind}.${ext}`).find((name) => names.includes(name));
32
+ if (source)
33
+ owned.set(file, source);
34
+ }
35
+ return owned;
36
+ }
37
+ export function shadowedRootFiles(appDir, publicDir) {
38
+ if (!existsSync(publicDir))
39
+ return [];
40
+ const shadowed = [];
41
+ for (const [served, source] of appRootFiles(appDir)) {
42
+ const publicFile = join(publicDir, served);
43
+ if (!existsSync(publicFile) || !statSync(publicFile).isFile())
44
+ continue;
45
+ shadowed.push({
46
+ url: `/${served}`,
47
+ publicFile,
48
+ appFile: join(appDir, source),
49
+ empty: statSync(publicFile).size === 0,
50
+ });
51
+ }
52
+ return shadowed.sort((a, b) => a.url.localeCompare(b.url));
53
+ }
54
+ export function shadowedRootFileMessage(file, root) {
55
+ const pub = relative(root, file.publicFile);
56
+ const app = relative(root, file.appFile);
57
+ return (`[rsc-kit] ${pub} is answered at ${file.url}, not ${app}: public/ is served before the app is reached. ` +
58
+ (file.empty
59
+ ? `It is empty - a placeholder, as Laravel's skeleton ships - so ${file.url} answers nothing (Herd: 404). `
60
+ : "") +
61
+ `Delete ${pub} to serve the app's.`);
62
+ }
63
+ //# sourceMappingURL=shadowedRootFiles.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shadowedRootFiles.js","sourceRoot":"","sources":["../src/shadowedRootFiles.ts"],"names":[],"mappings":"AAAA,mDAAmD;AACnD,EAAE;AACF,6EAA6E;AAC7E,0EAA0E;AAC1E,0EAA0E;AAC1E,wEAAwE;AACxE,2EAA2E;AAC3E,cAAc;AACd,EAAE;AACF,2EAA2E;AAC3E,4EAA4E;AAC5E,4EAA4E;AAC5E,6EAA6E;AAE7E,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC5D,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,e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C;IAExC,KAAK,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,IAAI,YAAY,CAAC,MAAM,CAAC,EAAE,CAAC;QACpD,MAAM,UAAU,GAAG,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;QAE3C,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,MAAM,EAAE;YAAE,SAAS;QAExE,QAAQ,CAAC,IAAI,CAAC;YACZ,GAAG,EAAE,IAAI,MAAM,EAAE;YACjB,UAAU;YACV,OAAO,EAAE,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC;YAC7B,KAAK,EAAE,QAAQ,CAAC,UAAU,CAAC,CAAC,IAAI,KAAK,CAAC;SACvC,CAAC,CAAC;IACL,CAAC;IAED,OAAO,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAC7D,CAAC;AAED,MAAM,UAAU,uBAAuB,CAAC,IAAsB,EAAE,IAAY;IAC1E,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IAC5C,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;IAEzC,OAAO,CACL,aAAa,GAAG,mBAAmB,IAAI,CAAC,GAAG,SAAS,GAAG,iDAAiD;QACxG,CAAC,IAAI,CAAC,KAAK;YACT,CAAC,CAAC,iEAAiE,IAAI,CAAC,GAAG,gCAAgC;YAC3G,CAAC,CAAC,EAAE,CAAC;QACP,UAAU,GAAG,sBAAsB,CACpC,CAAC;AACJ,CAAC","sourcesContent":["// A file in public/ at a url the app also answers.\n//\n// The app serves a few files at the site's root from beside its root layout:\n// favicon.ico, robots.txt (or robots.ts), a sitemap, llms.txt. public/ is\n// served at the root too, and whatever serves it - Herd's or any nginx in\n// front of Laravel, Nitro's static handler - answers before the request\n// reaches the app. So a file of the same name there wins, and the app's is\n// never seen.\n//\n// It happens without anyone choosing it: Laravel's skeleton ships an empty\n// public/favicon.ico and a public/robots.txt. The empty favicon answers 404\n// through Herd, and the browser's console says only \"favicon.ico not found\"\n// on an app that has one. Said at dev start and at build, naming both files.\n\nimport { existsSync, readdirSync, statSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { METADATA_ROUTES, ROOT_FILES } from \"./metadataRoutes.js\";\n\nexport interface ShadowedRootFile {\n /** The url both claim, e.g. /favicon.ico. */\n url: string;\n /** The file in public/ that is answered instead. */\n publicFile: string;\n /** The app's own, which is never reached. */\n appFile: string;\n /** The public/ file is empty: a placeholder, Laravel's skeleton's own. */\n empty: boolean;\n}\n\nconst SOURCE_EXTENSIONS = [\"ts\", \"tsx\", \"js\", \"mjs\"];\n\n/** Every url the app's own directory answers at the root, with the file that answers it. */\nfunction appRootFiles(appDir: string): Map<string, string> {\n const owned = new Map<string, string>();\n\n if (!existsSync(appDir)) return owned;\n\n const names = readdirSync(appDir);\n\n if (names.includes(\"favicon.ico\")) owned.set(\"favicon.ico\", \"favicon.ico\");\n\n for (const name of names) {\n if (ROOT_FILES.test(name)) owned.set(name, name);\n }\n\n for (const [kind, { file }] of Object.entries(METADATA_ROUTES)) {\n const source = SOURCE_EXTENSIONS.map((ext) => `${kind}.${ext}`).find((name) => names.includes(name));\n\n if (source) owned.set(file, source);\n }\n\n return owned;\n}\n\nexport function shadowedRootFiles(appDir: string, publicDir: string): ShadowedRootFile[] {\n if (!existsSync(publicDir)) return [];\n\n const shadowed: ShadowedRootFile[] = [];\n\n for (const [served, source] of appRootFiles(appDir)) {\n const publicFile = join(publicDir, served);\n\n if (!existsSync(publicFile) || !statSync(publicFile).isFile()) continue;\n\n shadowed.push({\n url: `/${served}`,\n publicFile,\n appFile: join(appDir, source),\n empty: statSync(publicFile).size === 0,\n });\n }\n\n return shadowed.sort((a, b) => a.url.localeCompare(b.url));\n}\n\nexport function shadowedRootFileMessage(file: ShadowedRootFile, root: string): string {\n const pub = relative(root, file.publicFile);\n const app = relative(root, file.appFile);\n\n return (\n `[rsc-kit] ${pub} is answered at ${file.url}, not ${app}: public/ is served before the app is reached. ` +\n (file.empty\n ? `It is empty - a placeholder, as Laravel's skeleton ships - so ${file.url} answers nothing (Herd: 404). `\n : \"\") +\n `Delete ${pub} to serve the app's.`\n );\n}\n"]}
package/dist/vite.d.ts CHANGED
@@ -2,6 +2,7 @@ import type { PrerenderResult } from "./prerender.js";
2
2
  import { type ContentSecurityPolicyOptions } from "./csp.js";
3
3
  import type { WebManifestOptions } from "./webManifest.js";
4
4
  import type { Plugin, PluginOption } from "vite";
5
+ import type { RouteSegment } from "./manifest.js";
5
6
  export interface RscKitOptions {
6
7
  /** Project root. Defaults to RSC_PROJECT_ROOT, then cwd. */
7
8
  projectRoot?: string;
@@ -502,6 +503,17 @@ export interface KnownAction {
502
503
  name: string;
503
504
  file: string;
504
505
  }
506
+ /**
507
+ * Two pages at one url. A route group adds nothing to the url, so
508
+ * (home)/page.tsx and (preview)/(home)/page.tsx are both / - and the first
509
+ * found answered while the other was never reached, with nothing said. A
510
+ * parameter's name does not tell two urls apart either: [id] and [slug] in
511
+ * one place match the same requests.
512
+ */
513
+ export declare function samePageUrl(routes: {
514
+ component: string;
515
+ segments: RouteSegment[];
516
+ }[]): string | null;
505
517
  /**
506
518
  * The identifier a route file is imported as in the generated entries.
507
519
  *
package/dist/vite.js CHANGED
@@ -36,6 +36,7 @@ import { serverImportsOfClientPackages } from "./clientImports.js";
36
36
  import { automaticSitemap, METADATA_ROUTES, ROOT_FILES, rootFileType, } from "./metadataRoutes.js";
37
37
  import { ownHosts } from "./hostRouting.js";
38
38
  import { unrollBarrelImports } from "./barrelImports.js";
39
+ import { shadowedRootFileMessage, shadowedRootFiles } from "./shadowedRootFiles.js";
39
40
  import { hasUseSsr, serverRendererMessage, SERVER_RENDERER, ssrProxyModule, UseSsrError, withoutSsrDirective } from "./useSsr.js";
40
41
  import { backendHeaders, httpHostCalls } from "./hostCalls.js";
41
42
  import { BARE_COMMANDS_ENVIRONMENT, BARE_COMMANDS_MODULE_ID, COMMANDS_MODULE_ID, bareCommandsModule, commandFiles, commandsEntry, commandsEntrySource, commandsModule, compileEntryWithCommands } from "./commandFiles.js";
@@ -912,6 +913,9 @@ function routeManifest() {
912
913
  ...revalidateOf([...layouts, name].map((n) => components.get(n).absPath)),
913
914
  });
914
915
  }
916
+ const clash = samePageUrl(routes);
917
+ if (clash)
918
+ throw new Error(clash);
915
919
  // What the build decided, for a host that has to act on it afterwards —
916
920
  // writing the site out, and knowing which filename the client will ask for.
917
921
  return {
@@ -2265,6 +2269,30 @@ async function exportAfterPrerender(results, staticDir, assetsDir) {
2265
2269
  throw new Error(`[rsc-kit] ${error.message}`);
2266
2270
  }
2267
2271
  }
2272
+ /**
2273
+ * Two pages at one url. A route group adds nothing to the url, so
2274
+ * (home)/page.tsx and (preview)/(home)/page.tsx are both / - and the first
2275
+ * found answered while the other was never reached, with nothing said. A
2276
+ * parameter's name does not tell two urls apart either: [id] and [slug] in
2277
+ * one place match the same requests.
2278
+ */
2279
+ export function samePageUrl(routes) {
2280
+ const seen = new Map();
2281
+ for (const route of routes) {
2282
+ const key = route.segments
2283
+ .map((segment) => (segment.type === "static" ? `s:${segment.value}` : segment.type))
2284
+ .join("/");
2285
+ const first = seen.get(key);
2286
+ if (first) {
2287
+ const url = patternOf(route.segments.filter((segment) => segment.type !== "host"));
2288
+ return (`[rsc-kit] ${first} and ${route.component} are both the page at ${url}. ` +
2289
+ "A route group - a (name) directory - adds nothing to the url, so the two cannot be told apart. " +
2290
+ "Keep one, or give the other a directory that is part of the url.");
2291
+ }
2292
+ seen.set(key, route.component);
2293
+ }
2294
+ return null;
2295
+ }
2268
2296
  /** `/posts/[slug]` — the pattern, in the shape the app writes its links in. */
2269
2297
  function patternOf(segments) {
2270
2298
  if (segments.length === 0)
@@ -2812,6 +2840,8 @@ function openApiPlugin() {
2812
2840
  }
2813
2841
  /** Files beside the root layout served at the root as they are: robots.txt, a hand-written sitemap.xml, humans.txt. */
2814
2842
  let rootFiles = [];
2843
+ /** Shadowed root files already warned about, so a dev restart does not repeat them. */
2844
+ const saidShadowed = new Set();
2815
2845
  const METADATA_ROUTE_ID = "virtual:rsc-kit/metadata-route/";
2816
2846
  /**
2817
2847
  * robots.ts, sitemap.ts, llms.ts beside the root layout, each registered as
@@ -3094,21 +3124,59 @@ function metadataExports(absPath) {
3094
3124
  export function revalidateOf(files) {
3095
3125
  let smallest;
3096
3126
  for (const file of files) {
3097
- const src = readFileSync(file, "utf-8");
3098
- const declared = /export\s+const\s+revalidate\s*(?::[^=]+)?=\s*([^;\n]+)/.exec(src);
3127
+ const declared = exportedConst(file, "revalidate");
3099
3128
  if (!declared)
3100
3129
  continue;
3101
- const value = declared[1].trim().replace(/_/g, "");
3102
- if (!/^\d+$/.test(value)) {
3103
- throw new Error(`${file}: export const revalidate must be a number of seconds the build can read, like 60. Found: ${declared[1].trim()}`);
3130
+ const value = unwrapTypes(declared.init);
3131
+ if (value?.type !== "Literal" || typeof value.value !== "number" || !Number.isInteger(value.value) || value.value < 0) {
3132
+ throw new Error(`${file}: export const revalidate must be a number of seconds the build can read, like 60. Found: ${declared.source}`);
3104
3133
  }
3105
- smallest = Math.min(smallest ?? Infinity, Number(value));
3134
+ smallest = Math.min(smallest ?? Infinity, value.value);
3106
3135
  }
3107
3136
  return smallest ? { revalidate: smallest } : {};
3108
3137
  }
3138
+ /**
3139
+ * A module's top-level statements, parsed - not its text. A regex over the
3140
+ * source matched `export const revalidate = 60` written as prose in a page's
3141
+ * JSX, in a comment, in a string, and failed the build on a page that
3142
+ * declared nothing.
3143
+ */
3144
+ function topLevel(file) {
3145
+ const src = readFileSync(file, "utf-8");
3146
+ const ext = file.slice(file.lastIndexOf(".") + 1);
3147
+ const lang = ext === "tsx" || ext === "ts" || ext === "jsx" ? ext : "js";
3148
+ return { body: parseAst(src, { lang }).body, src };
3149
+ }
3150
+ function exportedDeclarations(body) {
3151
+ return body.filter((node) => node.type === "ExportNamedDeclaration" && node.declaration).map((node) => node.declaration);
3152
+ }
3153
+ /** `export const <name> = …`: its initialiser, and the text of it for a message. */
3154
+ function exportedConst(file, name) {
3155
+ const { body, src } = topLevel(file);
3156
+ for (const declaration of exportedDeclarations(body)) {
3157
+ if (declaration.type !== "VariableDeclaration")
3158
+ continue;
3159
+ for (const declarator of declaration.declarations) {
3160
+ if (declarator.id?.type === "Identifier" && declarator.id.name === name) {
3161
+ const init = declarator.init ?? null;
3162
+ return { init, source: init ? src.slice(init.start, init.end) : "nothing" };
3163
+ }
3164
+ }
3165
+ }
3166
+ return null;
3167
+ }
3168
+ /** `60 as const`, `60 satisfies number`, `(60)`: the value under them. */
3169
+ function unwrapTypes(node) {
3170
+ while (node && ["TSAsExpression", "TSSatisfiesExpression", "TSNonNullExpression", "ParenthesizedExpression"].includes(node.type)) {
3171
+ node = node.expression;
3172
+ }
3173
+ return node;
3174
+ }
3109
3175
  function hasStaticParams(absPath) {
3110
- const src = readFileSync(absPath, "utf-8");
3111
- return /export\s+((async\s+)?function\s+generateStaticParams|const\s+generateStaticParams)/.test(src);
3176
+ return exportedDeclarations(topLevel(absPath).body).some((declaration) => declaration.type === "FunctionDeclaration"
3177
+ ? declaration.id?.name === "generateStaticParams"
3178
+ : declaration.type === "VariableDeclaration" &&
3179
+ declaration.declarations.some((d) => d.id?.type === "Identifier" && d.id.name === "generateStaticParams"));
3112
3180
  }
3113
3181
  /**
3114
3182
  * Which url schemas a page exports.
@@ -3566,6 +3634,8 @@ import { isActionValidationError, isActionRefusal, isClientBuilt, turnedAwayStat
3566
3634
  import { forgetCached } from ${JSON.stringify(join(packageDir, "cache"))}
3567
3635
  import { noteFallback as noteCaughtRead } from ${JSON.stringify(join(packageDir, "request"))}
3568
3636
  import { isOutdatedOptimizedDep, outdatedDepResponse } from ${JSON.stringify(join(packageDir, "devReload"))}
3637
+ import { devActionErrorResponse, isActionCall } from ${JSON.stringify(join(packageDir, "devActionError"))}
3638
+ import { sayUnroutedHost } from ${JSON.stringify(join(packageDir, "hostRouting"))}
3569
3639
  import { paramsFor, segmentNames, sharedDepth } from ${JSON.stringify(join(packageDir, "routing"))}
3570
3640
  import { Suspense, createElement, Fragment } from 'react'
3571
3641
  import { AsyncLocalStorage } from 'node:async_hooks'
@@ -6311,6 +6381,15 @@ async function served(request: Request): Promise<Response> {
6311
6381
  // is over already; the page is asked to load again.
6312
6382
  if (import.meta.env.DEV && isOutdatedOptimizedDep(error)) return outdatedDepResponse(request)
6313
6383
 
6384
+ // A failed action, in development: its error and the backend's frames,
6385
+ // for the browser's overlay. Left to the server's generic 500 the page
6386
+ // said nothing, and the cause was in the terminal. Still printed there.
6387
+ if (import.meta.env.DEV && isActionCall(request)) {
6388
+ console.error(error)
6389
+
6390
+ return devActionErrorResponse(error)
6391
+ }
6392
+
6314
6393
  throw error
6315
6394
  }
6316
6395
  }
@@ -6353,6 +6432,7 @@ async function serve(request: Request): Promise<Response> {
6353
6432
  } as never,
6354
6433
  ${NITRO_HANDLER_OPTIONS}${NITRO_PRERENDERED} maxActionBody: ${maxActionBody === undefined ? "undefined" : String(maxActionBody)},
6355
6434
  trustedOrigins: ${JSON.stringify(trustedOrigins ?? [])},
6435
+ onUnroutedHost: import.meta.env.DEV ? sayUnroutedHost : undefined,
6356
6436
  })
6357
6437
 
6358
6438
  ${fallbackOrigin === false ? NO_FALLBACK_BODY : FALLBACK_BODY}}
@@ -6846,6 +6926,7 @@ function generateEntryBrowser() {
6846
6926
  : null;
6847
6927
  const refreshModule = join(packageDir, "js/navigate");
6848
6928
  const chunkPreload = join(packageDir, "js/chunkPreload");
6929
+ const devErrorOverlay = join(packageDir, "js/devErrorOverlay");
6849
6930
  return `// GENERATED by rscKit() — do not edit.
6850
6931
  import { createViteRscApp } from ${JSON.stringify(clientBootstrap)}
6851
6932
  import { refresh } from ${JSON.stringify(refreshModule)}
@@ -6861,6 +6942,13 @@ if (import.meta.env.PROD) {
6861
6942
  setChunkLoader((id) => references[id]?.())
6862
6943
  }
6863
6944
 
6945
+ // A failed server action, on the page as Vite's error overlay - development
6946
+ // only, and loaded only there: removed from a production build with the
6947
+ // branch it is in.
6948
+ if (import.meta.env.DEV) {
6949
+ void import(${JSON.stringify(devErrorOverlay)}).then((overlay) => overlay.installDevActionErrors())
6950
+ }
6951
+
6864
6952
  createViteRscApp(document, ${JSON.stringify(interceptManifest())}, ${JSON.stringify({
6865
6953
  staticPayloads: staticPayloads || null,
6866
6954
  routes: routesForClient,
@@ -8110,6 +8198,16 @@ export function rscKit(options = {}) {
8110
8198
  discover(appDir);
8111
8199
  registerMetadataRoutes(appDir);
8112
8200
  registerOpenApiRoutes();
8201
+ // A file in public/ answered in place of the app's own - Laravel's
8202
+ // empty favicon.ico and robots.txt. Once per message: this hook runs
8203
+ // again on every dev restart.
8204
+ for (const shadowed of shadowedRootFiles(appDir, join(projectRoot, "public"))) {
8205
+ const message = shadowedRootFileMessage(shadowed, projectRoot);
8206
+ if (!saidShadowed.has(message)) {
8207
+ saidShadowed.add(message);
8208
+ console.warn(message);
8209
+ }
8210
+ }
8113
8211
  siteHosts = ownHosts(rootMetadataBase(appDir), hostsOption);
8114
8212
  // Silent when it worked. The names were printed on every dev start and
8115
8213
  // every build — thirty of them for a middling app, above the output that