@rsc-kit/core 0.32.0 → 0.34.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/conformance.d.ts +10 -0
- package/dist/conformance.js +36 -3
- package/dist/conformance.js.map +1 -1
- package/dist/devActionError.d.ts +35 -0
- package/dist/devActionError.js +53 -0
- package/dist/devActionError.js.map +1 -0
- package/dist/host.d.ts +6 -0
- package/dist/host.js +6 -1
- package/dist/host.js.map +1 -1
- package/dist/hostRouting.d.ts +9 -0
- package/dist/hostRouting.js +19 -0
- package/dist/hostRouting.js.map +1 -1
- package/dist/js/devErrorOverlay.d.ts +39 -0
- package/dist/js/devErrorOverlay.js +73 -0
- package/dist/js/devErrorOverlay.js.map +1 -0
- package/dist/js/errors.js +4 -0
- package/dist/js/errors.js.map +1 -1
- package/dist/routes.d.ts +37 -0
- package/dist/routes.js +10 -0
- package/dist/routes.js.map +1 -1
- package/dist/shadowedRootFiles.d.ts +12 -0
- package/dist/shadowedRootFiles.js +63 -0
- package/dist/shadowedRootFiles.js.map +1 -0
- package/dist/vite.d.ts +18 -0
- package/dist/vite.js +125 -8
- package/dist/vite.js.map +1 -1
- package/package.json +2 -2
package/dist/hostRouting.d.ts
CHANGED
|
@@ -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;
|
package/dist/hostRouting.js
CHANGED
|
@@ -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
|
package/dist/hostRouting.js.map
CHANGED
|
@@ -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,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,IAA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,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;QACxD,CAAC;QAAC,MAAM,CAAC;YACP,mEAAmE;QACrE,CAAC;IACH,CAAC;IAED,KAAK,MAAM,IAAI,IAAI,KAAK;QAAE,GAAG,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;IAElD,KAAK,MAAM,IAAI,IAAI,CAAC,GAAG,GAAG,CAAC,EAAE,CAAC;QAC5B,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC;YAAE,GAAG,CAAC,GAAG,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IACvD,CAAC;IAED,OAAO,CAAC,GAAG,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;AACzC,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,YAAY,CAC1B,OAAe,EACf,MAA2E;IAE3E,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC3B,MAAM,KAAK,GAAG,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;QAEhC,IAAI,CAAC,KAAK;YAAE,SAAS;QACrB,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM;YAAE,OAAO,IAAI,CAAC;QACvC,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,IAAI,KAAK,CAAC,KAAK,KAAK,OAAO;YAAE,OAAO,IAAI,CAAC;IACtE,CAAC;IAED,OAAO,KAAK,CAAC;AACf,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"]}
|
|
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;QAAE,OAAO,IAAI,CAAC;IACpC,IAAI,IAAI,KAAK,WAAW,IAAI,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC;QACvE,OAAO,IAAI,CAAC;IAEd,KAAK,MAAM,IAAI,IAAI,GAAG,EAAE,CAAC;QACvB,IAAI,IAAI,CAA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*\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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AAC,SAAS,CAAC,CAAC,CAAC,cAAc,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;IAE7G,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,aAAa,CAAC,GAAG,KAAK,CAAC,OAAO,KAAK,KAAK,CAAC,KAAK,EAAE,CAAC,CAAC;QAElD,OAAO;IACT,CAAC;IAED,sEAAsE;IACtE,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,gBAAgB,CAAC,oBAAoB,CAAC,CAAC;QAAE,IAAI,CAAC,MAAM,EAAE,CAAC;IAE9F,QAAQ,CAAC,IAAI,CAAC,WAAW,CAAC,IAAK,OAAwD,CAAC,KAAK,CAAC,CAAC,CAAC;AAClG,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,sBAAsB;IACnC,UAAiF,CAAC,sBAAsB,GAAG,KAAK,EAAE,QAAQ,EAAE,EAAE;QAC7H,IAAI,QAAQ,CAAC,OAAO,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
|
/**
|
package/dist/js/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/js/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;AAE9C,SAAS,IAAI,CAAC,KAAY,EAAE,IAAY;IACtC,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;AACtD,CAAC;AAED,SAAS,MAAM,CAAC,KAAc,EAAE,IAAY;IAC1C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC;AAC1G,CAAC;AAED,MAAM,OAAO,qBAAsB,SAAQ,KAAK;IAC9C,wDAAwD;IACxD,MAAM,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,KAAc;QACxC,OAAO,MAAM,CAAC,KAAK,E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y 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,CAAC,oBAAoB,CAAC,CAAC;AAE9C,SAAS,IAAI,CAAC,KAAY,EAAE,IAAY;IACtC,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;AACtD,CAAC;AAED,SAAS,MAAM,CAAC,KAAc,EAAE,IAAY;IAC1C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC;AAC1G,CAAC;AAED,MAAM,OAAO,qBAAsB,SAAQ,KAAK;IAC9C,wDAAwD;IACxD,MAAM,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,KAAc;QACxC,OAAO,MAAM,CAAC,KAAK,EAAE,uBAAuB,CAAC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AC,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"]}
|
package/dist/routes.d.ts
CHANGED
|
@@ -207,4 +207,41 @@ export declare function withSearch(path: string, search: object | undefined): st
|
|
|
207
207
|
* `prefetch`, `redirect` and anything else that wants the finished string.
|
|
208
208
|
*/
|
|
209
209
|
export declare function href<H extends Route>(path: H, ...rest: {} extends SearchFor<H> ? [search?: SearchFor<H>] : [search: SearchFor<H>]): Route;
|
|
210
|
+
/** A top-level folder a url can begin with: `merchant` for app/merchant. */
|
|
211
|
+
type TopFolder<P> = P extends `/${infer F}/${string}` ? F extends `[${string}` ? never : F : P extends `/${infer F}` ? F extends `[${string}` | "" ? never : F : never;
|
|
212
|
+
/** The patterns under `/${F}`, with the folder taken off: `/merchant/orders` → `/orders`. */
|
|
213
|
+
type Under<P, F extends string> = P extends `/${F}` ? "/" : P extends `/${F}/${infer R}` ? `/${R}` : never;
|
|
214
|
+
/** A tenant tree's patterns, with the tenant taken off: `/[domain]/settings` → `/settings`. */
|
|
215
|
+
type TenantPaths<P> = P extends `/[domain]${infer R}` | `/[host]${infer R}` ? R extends "" ? "/" : R : never;
|
|
216
|
+
type WithQuery<P extends string> = P | `${P}?${string}` | `${P}#${string}`;
|
|
217
|
+
/**
|
|
218
|
+
* What `hostUrl`'s first argument autocompletes to: every top-level folder.
|
|
219
|
+
* Any other string is taken too - a tenant's subdomain, a custom domain.
|
|
220
|
+
*/
|
|
221
|
+
export type HostName = Unregistered extends true ? string : HostFolder | (string & {});
|
|
222
|
+
/** The top-level folders of the route tree: `merchant` for app/merchant. */
|
|
223
|
+
export type HostFolder = TopFolder<RoutePattern>;
|
|
224
|
+
/**
|
|
225
|
+
* The paths a host answers: for a folder's subdomain the pages under that
|
|
226
|
+
* folder; for anything else the tenant tree's, or any path when there is none.
|
|
227
|
+
*/
|
|
228
|
+
export type HostPath<H extends string> = Unregistered extends true ? string : H extends HostFolder ? WithQuery<Filled<Under<RoutePattern, H>>> : [TenantPaths<RoutePattern>] extends [never] ? `/${string}` : WithQuery<Filled<TenantPaths<RoutePattern>>>;
|
|
229
|
+
/**
|
|
230
|
+
* A url on another host of the site, for `<Link href>`, `visit()` and
|
|
231
|
+
* `redirect()`:
|
|
232
|
+
*
|
|
233
|
+
* hostUrl('merchant', '/orders') // //merchant.example.com/orders
|
|
234
|
+
* hostUrl('testbrand', '/settings') // //testbrand.example.com/settings - a tenant
|
|
235
|
+
* hostUrl('acme.com', '/settings') // //acme.com/settings - a name with a dot is a whole domain
|
|
236
|
+
* hostUrl('/pricing') // //example.com/pricing - the site itself
|
|
237
|
+
*
|
|
238
|
+
* The site's host is the one rscKit({ hosts }) names first. Where none is
|
|
239
|
+
* named, a folder's url is its path - `/merchant/orders` - as every page is
|
|
240
|
+
* then reached by path; a tenant or a domain still names its host.
|
|
241
|
+
*
|
|
242
|
+
* The same string on the server and in the browser, so a link hydrates as
|
|
243
|
+
* it rendered. On the host it names already, Link navigates without a reload.
|
|
244
|
+
*/
|
|
245
|
+
export declare function hostUrl(path: Route): Route;
|
|
246
|
+
export declare function hostUrl<H extends HostName>(host: H, path: HostPath<H>): Route;
|
|
210
247
|
export {};
|
package/dist/routes.js
CHANGED
|
@@ -80,4 +80,14 @@ export function withSearch(path, search) {
|
|
|
80
80
|
export function href(path, ...rest) {
|
|
81
81
|
return withSearch(path, rest[0]);
|
|
82
82
|
}
|
|
83
|
+
export function hostUrl(host, path) {
|
|
84
|
+
const site = typeof __RSC_SITE_HOST__ === "string" ? __RSC_SITE_HOST__ : null;
|
|
85
|
+
if (path === undefined)
|
|
86
|
+
return (site ? `//${site}${host}` : host);
|
|
87
|
+
if (host.includes("."))
|
|
88
|
+
return `//${host}${path}`;
|
|
89
|
+
if (site)
|
|
90
|
+
return `//${host}.${site}${path}`;
|
|
91
|
+
return `/${host}${path === "/" ? "" : path.startsWith("/?") || path.startsWith("/#") ? path.slice(1) : path}`;
|
|
92
|
+
}
|
|
83
93
|
//# sourceMappingURL=routes.js.map
|
package/dist/routes.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routes.js","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,EAAE;AACF,kEAAkE;AAClE,8EAA8E;AAC9E,4EAA4E;AAC5E,6EAA6E;AAC7E,mCAAmC;AACnC,EAAE;AACF,wEAAwE;AACxE,kEAAkE;AAClE,6EAA6E;AAC7E,8EAA8E;AAC9E,8CAA8C;AAC9C,EAAE;AACF,8EAA8E;AAC9E,sCAAsC;AACtC,EAAE;AACF,4CAA4C;AAC5C,2DAA2D;AAC3D,MAAM;AACN,EAAE;AACF,0EAA0E;AAC1E,6EAA6E;AAC7E,8EAA8E;AAC9E,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,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IACpC,MAAM,IAAI,GAAG,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;IAChE,MAAM,QAAQ,GAAG,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC;IACjE,MAAM,KAAK,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC;IACnC,MAAM,KAAK,GAAG,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAE1D,OAAO,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,IAAI,KAAK,GAAG,IAAI,EAAE,CAAC,CAAC,CAAC,GAAG,IAAI,GAAG,IAAI,EAAE,CAAC;AAC9D,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,IAAI,CAClB,IAAO,EACP,GAAG,IAEuB;IAE1B,OAAO,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAuB,CAAU,CAAC;AAClE,CAAC","sourcesContent":["// Typed routes: the urls this app can actually answer, as a type.\n//\n// Laravel needs route() because the url lives in PHP and can move\n// independently of the name it is called by. Here the url *is* the file path,\n// so a name would be indirection that buys nothing. What is worth having is\n// the other half — a link to a page that does not exist should fail at build\n// time rather than in the browser.\n//\n// There is no route() builder to go with this, deliberately. A template\n// literal is checked the same way — `/posts/${slug}` compiles and\n// `/postz/${slug}` does not — so a builder would only wrap what the language\n// already does. Encoding a value that is not url-safe is `encodeURIComponent`\n// in the template, the same as anywhere else.\n//\n// The build already walks app/ and knows every route's segments, so it writes\n// one line into the app's source dir:\n//\n// declare module '@rsc-kit/core/routes' {\n// interface Register { routes: '/' | '/posts/[slug]' }\n// }\n//\n// Everything below is derived from that union. An app that never runs the\n// generator — a generic host, a Laravel app that has not rebuilt — registers\n// nothing, `RoutePattern` stays `string`, and every url-taking API is exactly\n// as permissive as it was before. That fallback is the reason this can ship\n// without a flag.\n\n/**\n * Augmented by the generated `rsc-routes.d.ts`. Empty here on purpose.\n *\n * Declaration merging rather than a generic parameter, because the routes are\n * a property of the project, not of each call site — threading them through\n * every component that renders a Link is not a thing anyone would do twice.\n */\nexport interface Register {}\n\n/** The route patterns this app declared: `'/posts/[slug]'`. */\nexport type RoutePattern = Register extends { routes: infer R extends string }\n ? R\n : string;\n\n/** Whether anything was registered. `string` means the generator never ran. */\ntype Unregistered = string extends RoutePattern ? true : false;\n\n/**\n * A pattern with its dynamic segments opened up: `/posts/[slug]` accepts\n * `/posts/anything`.\n *\n * Catch-all and single params both become `${string}`, which for a catch-all\n * also swallows the slashes — `/docs/[...path]` accepts `/docs/a/b/c`.\n */\ntype Filled<P extends string> = P extends `${infer A}[...${string}]${infer B}`\n ? `${A}${string}${Filled<B>}`\n : P extends `${infer A}[${string}]${infer B}`\n ? `${A}${string}${Filled<B>}`\n : P;\n\n/**\n * Not a route, but a legitimate href: another site, a mail client, a phone\n * number, an anchor on this page, a bare query string.\n */\ntype OffRoute =\n | `${string}://${string}`\n | `mailto:${string}`\n | `tel:${string}`\n | `#${string}`\n | `?${string}`;\n\n/**\n * A url this app can answer, or one that deliberately leaves it.\n *\n * Cast when the destination is computed rather than written:\n * `href={path as Route}`.\n */\n/**\n * A url this app answers - a page or a route.ts - or one that deliberately\n * leaves it. One type, as Next's `Route` is one type: what `<Link href>`,\n * `visit()` and `redirect()` take. A route.ts is a full navigation rather\n * than a payload fetch, and never prefetched - the client knows which urls\n * are routes and treats a link to one as the anchor it is - so the type\n * does not have to keep them apart to keep a hover from running one.\n *\n * `Route` is the same type under the name Next uses, so a port keeps the\n * word it already has.\n */\nexport type Route = Unregistered extends true\n ? string\n : | Filled<RoutePattern>\n | `${Filled<RoutePattern>}?${string}`\n | `${Filled<RoutePattern>}#${string}`\n | Filled<ApiPattern>\n | `${Filled<ApiPattern>}?${string}`\n | BackendUrl\n | OffRoute;\n\n// ── The backend's urls ───────────────────────────────────────────────────────\n//\n// `rscKit({ backendPaths: ['/gitlab'] })` names the prefixes the backend owns.\n// They are not in the route tree, so a link or a redirect to `/gitlab/connect`\n// needed a cast to compile, for a url the app itself had declared. They are a\n// place to go and, like a route.ts, a full page load.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterBackend {}\n\n/** The prefixes `backendPaths` named: `'/gitlab'`. */\ntype BackendPrefix = RegisterBackend extends { paths: infer P extends string }\n ? P\n : never;\n\n/**\n * A prefix and everything under it, at a segment boundary: `/gitlab`,\n * `/gitlab/connect?next=/`, never `/gitlabs`. `never` when nothing was named.\n */\ntype BackendUrl =\n | BackendPrefix\n | `${BackendPrefix}/${string}`\n | `${BackendPrefix}?${string}`\n | `${BackendPrefix}#${string}`;\n\n// ── Api routes ───────────────────────────────────────────────────────────────\n//\n// Their own union rather than part of Route, because they are not pages and a\n// link to one is almost always a mistake — an <a href=\"/api/orders\"> navigates\n// the browser away to a json document. Keeping them apart means `Link` refuses\n// an api url and `apiUrl()` refuses a page, which is the pair of mistakes worth\n// catching.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterApi {}\n\n// ── Regions a page can re-render on its own ──────────────────────────────────\n//\n// Every `section('name', …)` the build found, and every `@slot` directory.\n// `revalidate('orders')` is checked against them, so a name that matches no\n// section - a typo, or a section renamed since - stops compiling instead of\n// being refused by the renderer at runtime.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterRegions {}\n\n/** The region names the build found: section names and slot names. */\nexport type RegionName = RegisterRegions extends {\n regions: infer R extends string;\n}\n ? R\n : string;\n\ntype NoRegions = string extends RegionName ? true : false;\n\n/**\n * What `revalidate()` takes: the page, the whole document, or a region by\n * name. `string` until the build has written the types.\n */\nexport type RevalidateTarget = NoRegions extends true\n ? string\n : \"page\" | \"all\" | RegionName;\n\n/** The api route patterns this app declared: `'/api/orders/[id]'`. */\nexport type ApiPattern = RegisterApi extends { apis: infer R extends string }\n ? R\n : string;\n\ntype NoApis = string extends ApiPattern ? true : false;\n\n/**\n * A url an api route in this app answers.\n *\n * `/api/orders/[id]` accepts `/api/orders/42`, and a query string is allowed\n * because that is how a GET is parameterised.\n */\nexport type ApiRoute = NoApis extends true\n ? string\n : Filled<ApiPattern> | `${Filled<ApiPattern>}?${string}`;\n\n/**\n * An api url, checked against the routes the build found.\n *\n * await fetch(apiUrl(`/api/orders/${id}`))\n *\n * A function rather than a bare type so it can be used inline at a call site\n * that is typed `string` — `fetch` takes any string, so nothing would check the\n * argument without somewhere to put the type. It returns what it was given.\n *\n * Wrong path, and it stops compiling. Renamed the directory, and every call\n * site says so rather than one of them 404ing in production.\n */\nexport function apiUrl(href: ApiRoute): string {\n return href;\n}\n\n// ── What an events route sends ───────────────────────────────────────────────\n//\n// A route.ts whose GET is `events(...)` says, as a type, what its generator\n// yields. The generated file records that per api pattern:\n//\n// interface RegisterApi {\n// events: { '/api/orders/[id]/events': EventsExportOf<typeof import('../src/app/api/orders/[id]/events/route')> }\n// }\n//\n// and `useEvents` reads a url's messages from it, so the hook and the route\n// cannot disagree about a message's shape.\n\n/** What a route module's GET yields, when it is `events(...)`; `unknown` for any other stream. */\nexport type EventsExportOf<M> = M extends {\n GET: { readonly \"~events\"?: infer S };\n}\n ? NonNullable<S> extends { yields: infer Y }\n ? Y\n : unknown\n : unknown;\n\ntype EventsMap = RegisterApi extends { events: infer M } ? M : {};\n\ntype Split<S extends string> = S extends `${infer A}/${infer B}`\n ? [A, ...Split<B>]\n : [S];\n\n/**\n * Whether a url's segments fit a pattern's, one segment at a time. Unlike\n * `Filled`, a `[id]` takes exactly one segment, so `/api/orders/42/events`\n * is `/api/orders/[id]/events` and not also `/api/orders/[id]`.\n */\ntype Fits<H extends string[], P extends string[]> = P extends [\n infer P0 extends string,\n ...infer PR extends string[],\n]\n ? P0 extends `[...${string}]`\n ? H extends [string, ...string[]]\n ? true\n : false\n : H extends [infer H0 extends string, ...infer HR extends string[]]\n ? P0 extends `[${string}]`\n ? Fits<HR, PR>\n : H0 extends P0\n ? Fits<HR, PR>\n : false\n : false\n : H extends []\n ? true\n : false;\n\n/** The api pattern a written url belongs to: `/api/orders/42/events` is `/api/orders/[id]/events`. */\ntype ApiPatternOf<H extends string> = ApiPattern extends infer P\n ? P extends string\n ? Fits<Split<StripQuery<H>>, Split<P>> extends true\n ? P\n : never\n : never\n : never;\n\n/**\n * Everything the stream at `H` yields, named events included. `unknown` when\n * `H` is not one api route the build found - a url computed at runtime, or\n * another site's - since there is nothing to read it from.\n */\nexport type EventsAt<H extends string> = NoApis extends true\n ? unknown\n : IsUnion<H> extends true\n ? unknown\n : [ApiPatternOf<H>] extends [never]\n ? unknown\n : ApiPatternOf<H> extends keyof EventsMap\n ? EventsMap[ApiPatternOf<H>]\n : unknown;\n\n/** A url `useEvents` may open: an api route this app answers, or another site's stream. */\nexport type EventsUrl = ApiRoute | `${string}://${string}`;\n\n// ── Search params, typed per route ───────────────────────────────────────────\n//\n// A page that exports a `searchParams` schema has said what its query string\n// means. The generated file records that schema per pattern:\n//\n// interface Register {\n// search: { '/search': SearchExportOf<typeof import('../src/app/search/page')> }\n// }\n//\n// and from there a link to `/search` is checked against the same schema the\n// page parses with — a `page` that must be a number is a number on the link,\n// a `q` the page requires is required to write the link, and a key the page\n// never reads does not compile. One schema, both ends. A route that exports\n// none takes anything; an href that is not a single route (computed, cast, or\n// off-site) takes anything too, because there is nothing to check it against.\n\n/** What a page module contributes: its `searchParams` export, or nothing. For the generated file. */\nexport type SearchExportOf<M> = M extends { searchParams: infer S }\n ? S\n : undefined;\n\ntype SearchMap = Register extends { search: infer M } ? M : {};\n\ntype StripQuery<H extends string> = H extends `${infer P}?${string}`\n ? P\n : H extends `${infer P}#${string}`\n ? P\n : H;\n\n/** The pattern a written href belongs to: `/posts/hello` is `/posts/[slug]`. */\ntype PatternOf<H extends string> = RoutePattern extends infer P\n ? P extends string\n ? StripQuery<H> extends Filled<P>\n ? P\n : never\n : never\n : never;\n\ntype IsUnion<T, U = T> = T extends unknown\n ? [U] extends [T]\n ? false\n : true\n : never;\n\ntype SchemaFor<P> = P extends keyof SearchMap ? SearchMap[P] : undefined;\n\ntype InputOf<S> = S extends { \"~standard\": { types?: { input: infer I } } }\n ? I\n : never;\ntype OutputOf<S> = S extends { \"~standard\": { types?: { output: infer O } } }\n ? O\n : never;\n\ntype OptionalKeys<T> = {\n [K in keyof T]-?: {} extends Pick<T, K> ? K : never;\n}[keyof T];\ntype RequiredKeys<T> = Exclude<keyof T, OptionalKeys<T>>;\ntype Simplify<T> = { [K in keyof T]: T[K] } & {};\n\n/**\n * What a link may write for a schema: the keys the schema's input requires\n * are required, the rest optional, and every value is the schema's OUTPUT\n * type. Output rather than input because `z.coerce.number()` takes `unknown`\n * in - that is what coercion means - and a link typed by it would accept\n * `page: 'two'`. The output is the number the page will actually see.\n */\ntype LinkInputOf<S> = Simplify<\n { [K in RequiredKeys<InputOf<S>> & keyof OutputOf<S>]: OutputOf<S>[K] } & {\n [K in OptionalKeys<InputOf<S>> & keyof OutputOf<S>]?: OutputOf<S>[K];\n }\n>;\n\ntype Scalar = string | number | boolean | null | undefined;\n\n/** What a link may carry when nothing declares otherwise. */\nexport type LooseSearch = Record<string, Scalar | readonly (string | number)[]>;\n\n/**\n * The search params a link to `H` may carry.\n *\n * The page's schema input when `H` is one declared route with a schema;\n * otherwise anything. \"One route\" matters: `path as Route` is every route at\n * once, and a link that could go anywhere cannot be held to one page's schema.\n */\nexport type SearchFor<H extends string> = Unregistered extends true\n ? LooseSearch\n : IsUnion<H> extends true\n ? LooseSearch\n : [PatternOf<H>] extends [never]\n ? LooseSearch\n : SchemaFor<PatternOf<H>> extends undefined\n ? LooseSearch\n : LinkInputOf<SchemaFor<PatternOf<H>>>;\n\n/**\n * The `search` prop, required exactly when the page's schema has a required\n * key. A page that needs `q` is not reachable without one, so the link that\n * omits it is the bug — caught here rather than on the page's error boundary.\n */\nexport type SearchProp<H extends string> =\n {} extends SearchFor<H>\n ? { search?: SearchFor<H> }\n : { search: SearchFor<H> };\n\n/** A query string from an object: scalars stringified, arrays repeated, null and undefined dropped. */\nexport function searchString(search: object): string {\n const params = new URLSearchParams();\n\n for (const [key, value] of Object.entries(search)) {\n if (value === null || value === undefined) continue;\n\n if (Array.isArray(value)) {\n for (const item of value) params.append(key, String(item));\n } else {\n params.set(key, String(value));\n }\n }\n\n return params.toString();\n}\n\n/** `path` with `search` appended, keeping any query and hash already on it. */\nexport function withSearch(path: string, search: object | undefined): string {\n if (!search) return path;\n\n const hashAt = path.indexOf(\"#\");\n const hash = hashAt === -1 ? \"\" : path.slice(hashAt);\n const before = hashAt === -1 ? path : path.slice(0, hashAt);\n const queryAt = before.indexOf(\"?\");\n const base = queryAt === -1 ? before : before.slice(0, queryAt);\n const existing = queryAt === -1 ? \"\" : before.slice(queryAt + 1);\n const added = searchString(search);\n const query = [existing, added].filter(Boolean).join(\"&\");\n\n return query ? `${base}?${query}${hash}` : `${base}${hash}`;\n}\n\n/**\n * A typed url with its search params, for the places that take a string.\n *\n * visit(href('/search', { q: 'shoes', page: 2 }))\n *\n * `Link` has the same check on its own `search` prop. This is for `visit`,\n * `prefetch`, `redirect` and anything else that wants the finished string.\n */\nexport function href<H extends Route>(\n path: H,\n ...rest: {} extends SearchFor<H>\n ? [search?: SearchFor<H>]\n : [search: SearchFor<H>]\n): Route {\n return withSearch(path, rest[0] as object | undefined) as Route;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"routes.js","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,EAAE;AACF,kEAAkE;AAClE,8EAA8E;AAC9E,4EAA4E;AAC5E,6EAA6E;AAC7E,mCAAmC;AACnC,EAAE;AACF,wEAAwE;AACxE,kEAAkE;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AC,CAAC,KAAK,IAAI,GAAG,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAU,CAAC;IAC3E,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,KAAK,IAAI,GAAG,IAAI,EAAW,CAAC;IAC3D,IAAI,IAAI;QAAE,OAAO,KAAK,IAAI,IAAI,IAAI,GAAG,IAAI,EAAW,CAAC;IAErD,OAAO,IAAI,IAAI,GAAG,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAW,CAAC;AACzH,CAAC","sourcesContent":["// Typed routes: the urls this app can actually answer, as a type.\n//\n// Laravel needs route() because the url lives in PHP and can move\n// independently of the name it is called by. Here the url *is* the file path,\n// so a name would be indirection that buys nothing. What is worth having is\n// the other half — a link to a page that does not exist should fail at build\n// time rather than in the browser.\n//\n// There is no route() builder to go with this, deliberately. A template\n// literal is checked the same way — `/posts/${slug}` compiles and\n// `/postz/${slug}` does not — so a builder would only wrap what the language\n// already does. Encoding a value that is not url-safe is `encodeURIComponent`\n// in the template, the same as anywhere else.\n//\n// The build already walks app/ and knows every route's segments, so it writes\n// one line into the app's source dir:\n//\n// declare module '@rsc-kit/core/routes' {\n// interface Register { routes: '/' | '/posts/[slug]' }\n// }\n//\n// Everything below is derived from that union. An app that never runs the\n// generator — a generic host, a Laravel app that has not rebuilt — registers\n// nothing, `RoutePattern` stays `string`, and every url-taking API is exactly\n// as permissive as it was before. That fallback is the reason this can ship\n// without a flag.\n\n/**\n * Augmented by the generated `rsc-routes.d.ts`. Empty here on purpose.\n *\n * Declaration merging rather than a generic parameter, because the routes are\n * a property of the project, not of each call site — threading them through\n * every component that renders a Link is not a thing anyone would do twice.\n */\nexport interface Register {}\n\n/** The route patterns this app declared: `'/posts/[slug]'`. */\nexport type RoutePattern = Register extends { routes: infer R extends string }\n ? R\n : string;\n\n/** Whether anything was registered. `string` means the generator never ran. */\ntype Unregistered = string extends RoutePattern ? true : false;\n\n/**\n * A pattern with its dynamic segments opened up: `/posts/[slug]` accepts\n * `/posts/anything`.\n *\n * Catch-all and single params both become `${string}`, which for a catch-all\n * also swallows the slashes — `/docs/[...path]` accepts `/docs/a/b/c`.\n */\ntype Filled<P extends string> = P extends `${infer A}[...${string}]${infer B}`\n ? `${A}${string}${Filled<B>}`\n : P extends `${infer A}[${string}]${infer B}`\n ? `${A}${string}${Filled<B>}`\n : P;\n\n/**\n * Not a route, but a legitimate href: another site, a mail client, a phone\n * number, an anchor on this page, a bare query string.\n */\ntype OffRoute =\n | `${string}://${string}`\n | `mailto:${string}`\n | `tel:${string}`\n | `#${string}`\n | `?${string}`;\n\n/**\n * A url this app can answer, or one that deliberately leaves it.\n *\n * Cast when the destination is computed rather than written:\n * `href={path as Route}`.\n */\n/**\n * A url this app answers - a page or a route.ts - or one that deliberately\n * leaves it. One type, as Next's `Route` is one type: what `<Link href>`,\n * `visit()` and `redirect()` take. A route.ts is a full navigation rather\n * than a payload fetch, and never prefetched - the client knows which urls\n * are routes and treats a link to one as the anchor it is - so the type\n * does not have to keep them apart to keep a hover from running one.\n *\n * `Route` is the same type under the name Next uses, so a port keeps the\n * word it already has.\n */\nexport type Route = Unregistered extends true\n ? string\n : | Filled<RoutePattern>\n | `${Filled<RoutePattern>}?${string}`\n | `${Filled<RoutePattern>}#${string}`\n | Filled<ApiPattern>\n | `${Filled<ApiPattern>}?${string}`\n | BackendUrl\n | OffRoute;\n\n// ── The backend's urls ───────────────────────────────────────────────────────\n//\n// `rscKit({ backendPaths: ['/gitlab'] })` names the prefixes the backend owns.\n// They are not in the route tree, so a link or a redirect to `/gitlab/connect`\n// needed a cast to compile, for a url the app itself had declared. They are a\n// place to go and, like a route.ts, a full page load.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterBackend {}\n\n/** The prefixes `backendPaths` named: `'/gitlab'`. */\ntype BackendPrefix = RegisterBackend extends { paths: infer P extends string }\n ? P\n : never;\n\n/**\n * A prefix and everything under it, at a segment boundary: `/gitlab`,\n * `/gitlab/connect?next=/`, never `/gitlabs`. `never` when nothing was named.\n */\ntype BackendUrl =\n | BackendPrefix\n | `${BackendPrefix}/${string}`\n | `${BackendPrefix}?${string}`\n | `${BackendPrefix}#${string}`;\n\n// ── Api routes ───────────────────────────────────────────────────────────────\n//\n// Their own union rather than part of Route, because they are not pages and a\n// link to one is almost always a mistake — an <a href=\"/api/orders\"> navigates\n// the browser away to a json document. Keeping them apart means `Link` refuses\n// an api url and `apiUrl()` refuses a page, which is the pair of mistakes worth\n// catching.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterApi {}\n\n// ── Regions a page can re-render on its own ──────────────────────────────────\n//\n// Every `section('name', …)` the build found, and every `@slot` directory.\n// `revalidate('orders')` is checked against them, so a name that matches no\n// section - a typo, or a section renamed since - stops compiling instead of\n// being refused by the renderer at runtime.\n\n/** Augmented by the generated `rsc-routes.d.ts`, like `Register`. */\nexport interface RegisterRegions {}\n\n/** The region names the build found: section names and slot names. */\nexport type RegionName = RegisterRegions extends {\n regions: infer R extends string;\n}\n ? R\n : string;\n\ntype NoRegions = string extends RegionName ? true : false;\n\n/**\n * What `revalidate()` takes: the page, the whole document, or a region by\n * name. `string` until the build has written the types.\n */\nexport type RevalidateTarget = NoRegions extends true\n ? string\n : \"page\" | \"all\" | RegionName;\n\n/** The api route patterns this app declared: `'/api/orders/[id]'`. */\nexport type ApiPattern = RegisterApi extends { apis: infer R extends string }\n ? R\n : string;\n\ntype NoApis = string extends ApiPattern ? true : false;\n\n/**\n * A url an api route in this app answers.\n *\n * `/api/orders/[id]` accepts `/api/orders/42`, and a query string is allowed\n * because that is how a GET is parameterised.\n */\nexport type ApiRoute = NoApis extends true\n ? string\n : Filled<ApiPattern> | `${Filled<ApiPattern>}?${string}`;\n\n/**\n * An api url, checked against the routes the build found.\n *\n * await fetch(apiUrl(`/api/orders/${id}`))\n *\n * A function rather than a bare type so it can be used inline at a call site\n * that is typed `string` — `fetch` takes any string, so nothing would check the\n * argument without somewhere to put the type. It returns what it was given.\n *\n * Wrong path, and it stops compiling. Renamed the directory, and every call\n * site says so rather than one of them 404ing in production.\n */\nexport function apiUrl(href: ApiRoute): string {\n return href;\n}\n\n// ── What an events route sends ───────────────────────────────────────────────\n//\n// A route.ts whose GET is `events(...)` says, as a type, what its generator\n// yields. The generated file records that per api pattern:\n//\n// interface RegisterApi {\n// events: { '/api/orders/[id]/events': EventsExportOf<typeof import('../src/app/api/orders/[id]/events/route')> }\n// }\n//\n// and `useEvents` reads a url's messages from it, so the hook and the route\n// cannot disagree about a message's shape.\n\n/** What a route module's GET yields, when it is `events(...)`; `unknown` for any other stream. */\nexport type EventsExportOf<M> = M extends {\n GET: { readonly \"~events\"?: infer S };\n}\n ? NonNullable<S> extends { yields: infer Y }\n ? Y\n : unknown\n : unknown;\n\ntype EventsMap = RegisterApi extends { events: infer M } ? M : {};\n\ntype Split<S extends string> = S extends `${infer A}/${infer B}`\n ? [A, ...Split<B>]\n : [S];\n\n/**\n * Whether a url's segments fit a pattern's, one segment at a time. Unlike\n * `Filled`, a `[id]` takes exactly one segment, so `/api/orders/42/events`\n * is `/api/orders/[id]/events` and not also `/api/orders/[id]`.\n */\ntype Fits<H extends string[], P extends string[]> = P extends [\n infer P0 extends string,\n ...infer PR extends string[],\n]\n ? P0 extends `[...${string}]`\n ? H extends [string, ...string[]]\n ? true\n : false\n : H extends [infer H0 extends string, ...infer HR extends string[]]\n ? P0 extends `[${string}]`\n ? Fits<HR, PR>\n : H0 extends P0\n ? Fits<HR, PR>\n : false\n : false\n : H extends []\n ? true\n : false;\n\n/** The api pattern a written url belongs to: `/api/orders/42/events` is `/api/orders/[id]/events`. */\ntype ApiPatternOf<H extends string> = ApiPattern extends infer P\n ? P extends string\n ? Fits<Split<StripQuery<H>>, Split<P>> extends true\n ? P\n : never\n : never\n : never;\n\n/**\n * Everything the stream at `H` yields, named events included. `unknown` when\n * `H` is not one api route the build found - a url computed at runtime, or\n * another site's - since there is nothing to read it from.\n */\nexport type EventsAt<H extends string> = NoApis extends true\n ? unknown\n : IsUnion<H> extends true\n ? unknown\n : [ApiPatternOf<H>] extends [never]\n ? unknown\n : ApiPatternOf<H> extends keyof EventsMap\n ? EventsMap[ApiPatternOf<H>]\n : unknown;\n\n/** A url `useEvents` may open: an api route this app answers, or another site's stream. */\nexport type EventsUrl = ApiRoute | `${string}://${string}`;\n\n// ── Search params, typed per route ───────────────────────────────────────────\n//\n// A page that exports a `searchParams` schema has said what its query string\n// means. The generated file records that schema per pattern:\n//\n// interface Register {\n// search: { '/search': SearchExportOf<typeof import('../src/app/search/page')> }\n// }\n//\n// and from there a link to `/search` is checked against the same schema the\n// page parses with — a `page` that must be a number is a number on the link,\n// a `q` the page requires is required to write the link, and a key the page\n// never reads does not compile. One schema, both ends. A route that exports\n// none takes anything; an href that is not a single route (computed, cast, or\n// off-site) takes anything too, because there is nothing to check it against.\n\n/** What a page module contributes: its `searchParams` export, or nothing. For the generated file. */\nexport type SearchExportOf<M> = M extends { searchParams: infer S }\n ? S\n : undefined;\n\ntype SearchMap = Register extends { search: infer M } ? M : {};\n\ntype StripQuery<H extends string> = H extends `${infer P}?${string}`\n ? P\n : H extends `${infer P}#${string}`\n ? P\n : H;\n\n/** The pattern a written href belongs to: `/posts/hello` is `/posts/[slug]`. */\ntype PatternOf<H extends string> = RoutePattern extends infer P\n ? P extends string\n ? StripQuery<H> extends Filled<P>\n ? P\n : never\n : never\n : never;\n\ntype IsUnion<T, U = T> = T extends unknown\n ? [U] extends [T]\n ? false\n : true\n : never;\n\ntype SchemaFor<P> = P extends keyof SearchMap ? SearchMap[P] : undefined;\n\ntype InputOf<S> = S extends { \"~standard\": { types?: { input: infer I } } }\n ? I\n : never;\ntype OutputOf<S> = S extends { \"~standard\": { types?: { output: infer O } } }\n ? O\n : never;\n\ntype OptionalKeys<T> = {\n [K in keyof T]-?: {} extends Pick<T, K> ? K : never;\n}[keyof T];\ntype RequiredKeys<T> = Exclude<keyof T, OptionalKeys<T>>;\ntype Simplify<T> = { [K in keyof T]: T[K] } & {};\n\n/**\n * What a link may write for a schema: the keys the schema's input requires\n * are required, the rest optional, and every value is the schema's OUTPUT\n * type. Output rather than input because `z.coerce.number()` takes `unknown`\n * in - that is what coercion means - and a link typed by it would accept\n * `page: 'two'`. The output is the number the page will actually see.\n */\ntype LinkInputOf<S> = Simplify<\n { [K in RequiredKeys<InputOf<S>> & keyof OutputOf<S>]: OutputOf<S>[K] } & {\n [K in OptionalKeys<InputOf<S>> & keyof OutputOf<S>]?: OutputOf<S>[K];\n }\n>;\n\ntype Scalar = string | number | boolean | null | undefined;\n\n/** What a link may carry when nothing declares otherwise. */\nexport type LooseSearch = Record<string, Scalar | readonly (string | number)[]>;\n\n/**\n * The search params a link to `H` may carry.\n *\n * The page's schema input when `H` is one declared route with a schema;\n * otherwise anything. \"One route\" matters: `path as Route` is every route at\n * once, and a link that could go anywhere cannot be held to one page's schema.\n */\nexport type SearchFor<H extends string> = Unregistered extends true\n ? LooseSearch\n : IsUnion<H> extends true\n ? LooseSearch\n : [PatternOf<H>] extends [never]\n ? LooseSearch\n : SchemaFor<PatternOf<H>> extends undefined\n ? LooseSearch\n : LinkInputOf<SchemaFor<PatternOf<H>>>;\n\n/**\n * The `search` prop, required exactly when the page's schema has a required\n * key. A page that needs `q` is not reachable without one, so the link that\n * omits it is the bug — caught here rather than on the page's error boundary.\n */\nexport type SearchProp<H extends string> =\n {} extends SearchFor<H>\n ? { search?: SearchFor<H> }\n : { search: SearchFor<H> };\n\n/** A query string from an object: scalars stringified, arrays repeated, null and undefined dropped. */\nexport function searchString(search: object): string {\n const params = new URLSearchParams();\n\n for (const [key, value] of Object.entries(search)) {\n if (value === null || value === undefined) continue;\n\n if (Array.isArray(value)) {\n for (const item of value) params.append(key, String(item));\n } else {\n params.set(key, String(value));\n }\n }\n\n return params.toString();\n}\n\n/** `path` with `search` appended, keeping any query and hash already on it. */\nexport function withSearch(path: string, search: object | undefined): string {\n if (!search) return path;\n\n const hashAt = path.indexOf(\"#\");\n const hash = hashAt === -1 ? \"\" : path.slice(hashAt);\n const before = hashAt === -1 ? path : path.slice(0, hashAt);\n const queryAt = before.indexOf(\"?\");\n const base = queryAt === -1 ? before : before.slice(0, queryAt);\n const existing = queryAt === -1 ? \"\" : before.slice(queryAt + 1);\n const added = searchString(search);\n const query = [existing, added].filter(Boolean).join(\"&\");\n\n return query ? `${base}?${query}${hash}` : `${base}${hash}`;\n}\n\n/**\n * A typed url with its search params, for the places that take a string.\n *\n * visit(href('/search', { q: 'shoes', page: 2 }))\n *\n * `Link` has the same check on its own `search` prop. This is for `visit`,\n * `prefetch`, `redirect` and anything else that wants the finished string.\n */\nexport function href<H extends Route>(\n path: H,\n ...rest: {} extends SearchFor<H>\n ? [search?: SearchFor<H>]\n : [search: SearchFor<H>]\n): Route {\n return withSearch(path, rest[0] as object | undefined) as Route;\n}\n\n// ── Another host ─────────────────────────────────────────────────────────────\n//\n// A page under app/merchant is reached as merchant.example.com/orders as well\n// as example.com/merchant/orders, and a page under app/[domain] only from the\n// tenant's own host. A typed `href` names the folder path, which is the second\n// of those - and the first is a host Link cannot know you meant. So the host is\n// said where it is meant, and the path is typed for it.\n\n/** The site's host, from rscKit({ hosts }) or a literal metadataBase, baked in by the build. */\ndeclare const __RSC_SITE_HOST__: string | null | undefined;\n\n/** A top-level folder a url can begin with: `merchant` for app/merchant. */\ntype TopFolder<P> = P extends `/${infer F}/${string}`\n ? F extends `[${string}` ? never : F\n : P extends `/${infer F}`\n ? F extends `[${string}` | \"\" ? never : F\n : never;\n\n/** The patterns under `/${F}`, with the folder taken off: `/merchant/orders` → `/orders`. */\ntype Under<P, F extends string> = P extends `/${F}`\n ? \"/\"\n : P extends `/${F}/${infer R}`\n ? `/${R}`\n : never;\n\n/** A tenant tree's patterns, with the tenant taken off: `/[domain]/settings` → `/settings`. */\ntype TenantPaths<P> = P extends `/[domain]${infer R}` | `/[host]${infer R}`\n ? R extends \"\" ? \"/\" : R\n : never;\n\ntype WithQuery<P extends string> = P | `${P}?${string}` | `${P}#${string}`;\n\n/**\n * What `hostUrl`'s first argument autocompletes to: every top-level folder.\n * Any other string is taken too - a tenant's subdomain, a custom domain.\n */\nexport type HostName = Unregistered extends true ? string : HostFolder | (string & {});\n\n/** The top-level folders of the route tree: `merchant` for app/merchant. */\nexport type HostFolder = TopFolder<RoutePattern>;\n\n/**\n * The paths a host answers: for a folder's subdomain the pages under that\n * folder; for anything else the tenant tree's, or any path when there is none.\n */\nexport type HostPath<H extends string> = Unregistered extends true\n ? string\n : H extends HostFolder\n ? WithQuery<Filled<Under<RoutePattern, H>>>\n : [TenantPaths<RoutePattern>] extends [never]\n ? `/${string}`\n : WithQuery<Filled<TenantPaths<RoutePattern>>>;\n\n/**\n * A url on another host of the site, for `<Link href>`, `visit()` and\n * `redirect()`:\n *\n * hostUrl('merchant', '/orders') // //merchant.example.com/orders\n * hostUrl('testbrand', '/settings') // //testbrand.example.com/settings - a tenant\n * hostUrl('acme.com', '/settings') // //acme.com/settings - a name with a dot is a whole domain\n * hostUrl('/pricing') // //example.com/pricing - the site itself\n *\n * The site's host is the one rscKit({ hosts }) names first. Where none is\n * named, a folder's url is its path - `/merchant/orders` - as every page is\n * then reached by path; a tenant or a domain still names its host.\n *\n * The same string on the server and in the browser, so a link hydrates as\n * it rendered. On the host it names already, Link navigates without a reload.\n */\nexport function hostUrl(path: Route): Route;\nexport function hostUrl<H extends HostName>(host: H, path: HostPath<H>): Route;\nexport function hostUrl(host: string, path?: string): Route {\n const site = typeof __RSC_SITE_HOST__ === \"string\" ? __RSC_SITE_HOST__ : null;\n\n if (path === undefined) return (site ? `//${site}${host}` : host) as Route;\n if (host.includes(\".\")) return `//${host}${path}` as Route;\n if (site) return `//${host}.${site}${path}` as Route;\n\n return `/${host}${path === \"/\" ? \"\" : path.startsWith(\"/?\") || path.startsWith(\"/#\") ? path.slice(1) : path}` as Route;\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,eAAe,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAalE,MAAM,iBAAiB,GAAG,CAAC,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;AAErD,4FAA4F;AAC5F,SAAS,YAAY,CAAC,MAAc;IAClC,MAAM,KAAK,GAAG,IAAI,GAAG,EAAkB,CAAC;IAExC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC;QAAE,OAAO,KAAK,CAAC;IAEtC,MAAM,KAAK,GAAG,WAAW,CAAC,MAAM,CAAC,CAAC;IAElC,IAAI,KAAK,CAAC,QAAQ,CAAC,aAAa,CAAC;QAAE,KAAK,CAAC,GAAG,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC;IAE3E,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,IAAI,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC;YAAE,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACnD,CAAC;IAED,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,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,23 @@ 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
|
+
/**
|
|
514
|
+
* The host hostUrl() puts a subdomain in front of: the first rscKit({ hosts })
|
|
515
|
+
* entry, or a literal metadataBase's, as written - a port kept, for
|
|
516
|
+
* localhost:8000 - with www. taken off. Null when neither names one.
|
|
517
|
+
*/
|
|
518
|
+
export declare function siteHostOf(metadataBase: string | URL | null | undefined, hosts: readonly string[]): string | null;
|
|
519
|
+
export declare function samePageUrl(routes: {
|
|
520
|
+
component: string;
|
|
521
|
+
segments: RouteSegment[];
|
|
522
|
+
}[]): string | null;
|
|
505
523
|
/**
|
|
506
524
|
* The identifier a route file is imported as in the generated entries.
|
|
507
525
|
*
|