@rsc-kit/core 0.35.0 → 0.36.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.
@@ -2,7 +2,11 @@ export interface FilesManifest {
2
2
  v: 1;
3
3
  /** The directory the files are in, relative to the manifest. */
4
4
  root: string;
5
- /** Every file a request may be answered with, by url path, sorted. */
5
+ /**
6
+ * Every file a request may be answered with, by url path, sorted. A path
7
+ * is the file's name as it is on disk, not percent-encoded: a request's
8
+ * path is decoded before it is looked up.
9
+ */
6
10
  files: string[];
7
11
  /**
8
12
  * The encodings some files also exist in, as a sibling with the suffix
@@ -11,9 +15,10 @@ export interface FilesManifest {
11
15
  */
12
16
  precompressed: string[];
13
17
  /**
14
- * The headers a file goes out with beyond its Content-Type, in order, each
15
- * applying to an exact path or, ending in `/**`, to every path under it.
16
- * A file matched by none gets none.
18
+ * The headers a file goes out with beyond its Content-Type, each applying
19
+ * to an exact path or, ending in `/**`, to every path under it. Every entry
20
+ * that matches applies, in order; a later one replaces an earlier one's
21
+ * header of the same name. A file matched by none gets none.
17
22
  */
18
23
  headers: {
19
24
  match: string;
@@ -22,9 +27,28 @@ export interface FilesManifest {
22
27
  /** Whether anything of the app's runs for a file: never. */
23
28
  middleware: false;
24
29
  }
30
+ /** The route rules Nitro resolves for a url path, as its matcher merges them. */
31
+ export type ResolveRouteRules = (path: string) => Record<string, unknown>;
25
32
  /** Whether a route rule's key matches a path: exact, or `/x/**` for everything under /x. */
26
33
  export declare function ruleMatches(rule: string, path: string): boolean;
27
34
  export declare function filesManifest(publicDir: string, routeRules: Record<string, unknown> | undefined, options?: {
28
35
  root?: string;
29
36
  exclude?: string[];
37
+ /** The app's base url; the files are under it. */
38
+ baseURL?: string;
39
+ /**
40
+ * Nitro's own resolution of a path's rules. Without it a file is checked
41
+ * against the rules by their keys, and one under a pattern the manifest
42
+ * cannot state is left out by the pattern's literal prefix.
43
+ */
44
+ resolve?: ResolveRouteRules | null;
45
+ /** Told about each file left to the app, and why. */
46
+ onLeftOut?: (path: string, why: string) => void;
30
47
  }): FilesManifest;
48
+ /**
49
+ * The route rules Nitro resolves for a path, by the matcher it compiles them
50
+ * with - h3's, loaded from the app's own Nitro so the answer is that
51
+ * version's. Null when it cannot be loaded or refuses the rules: files.json
52
+ * then falls back to the rules' keys, leaving out more rather than less.
53
+ */
54
+ export declare function nitroRouteRules(root: string, routeRules: Record<string, unknown> | undefined, baseURL: string): Promise<ResolveRouteRules | null>;
@@ -1,19 +1,37 @@
1
1
  // `.output/files.json`: what a server in front of the app may answer from
2
2
  // disk, before the app runs.
3
3
  //
4
- // Everything under `.output/public` is answered by Nitro's static handler
5
- // before the request reaches the renderer: no middleware.ts, no route.ts,
6
- // no rscKit({ headers }) - those are a page's. A proxy, a CDN or a PHP front
7
- // controller serving these files itself only has to match what that handler
8
- // sends, and the build already knows all of it: the files it wrote, and the
9
- // route rules Nitro serves them under (an asset directory's maxAge is one,
10
- // `/assets/**` immutable; the service worker's `max-age=0` is another). So
11
- // the build says so, rather than every front re-deriving it from a reading of
12
- // Nitro and getting the service worker wrong.
4
+ // Everything under the public directory is answered by Nitro's static
5
+ // handler before the request reaches the renderer: no middleware.ts, no
6
+ // route.ts, no rscKit({ headers }) - those are a page's. A proxy, a CDN or a
7
+ // PHP front controller serving these files itself only has to match what
8
+ // that handler sends, and the build already knows all of it: the files it
9
+ // wrote, and the route rules Nitro serves them under (an asset directory's
10
+ // maxAge is one, `/assets/**` immutable; the service worker's `max-age=0` is
11
+ // another). So the build says so, rather than every front re-deriving it from
12
+ // a reading of Nitro and getting the service worker wrong.
13
+ //
14
+ // It fails closed. Nitro's route rules run before its static handler, so a
15
+ // rule decides what a file goes out with - and a rule the manifest cannot
16
+ // state (`/:name.js`, a redirect, cors, a proxy, a `headers: false` reset)
17
+ // would make a front's answer differ from the app's with nobody seeing it.
18
+ // A file under such a rule is left out of `files`: the front sends it to the
19
+ // app, which answers it the way it always would. Each file is checked against
20
+ // Nitro's own matcher (h3's, which Nitro compiles its rules with), not a
21
+ // reading of it: what the front would send has to equal what Nitro resolves.
13
22
  import { existsSync, readdirSync, statSync } from "node:fs";
23
+ import { createRequire } from "node:module";
14
24
  import { join } from "node:path";
25
+ import { pathToFileURL } from "node:url";
15
26
  /** The encodings Nitro precompresses to, by the suffix of the sibling it writes. */
16
27
  const ENCODINGS = { ".br": "br", ".gz": "gzip", ".zst": "zstd" };
28
+ /**
29
+ * Rules that never touch a file Nitro's static handler answers: `prerender`
30
+ * is build-time, and the cache rule wraps route handlers, which run after it.
31
+ * Any other rule - redirect, proxy, cors, one an app or module added - leaves
32
+ * the file to the app.
33
+ */
34
+ const INERT = new Set(["headers", "prerender", "cache"]);
17
35
  function walk(dir, base, skip, out) {
18
36
  for (const name of readdirSync(dir).sort()) {
19
37
  const full = join(dir, name);
@@ -32,7 +50,30 @@ export function ruleMatches(rule, path) {
32
50
  return path.startsWith(rule.slice(0, -2));
33
51
  return rule === path;
34
52
  }
53
+ /** Whether a front can follow a rule's key without Nitro's router. */
54
+ function expressible(rule) {
55
+ return !/[*:?(){}\\]/.test(rule.endsWith("/**") ? rule.slice(0, -3) : rule);
56
+ }
57
+ /** The literal part of a pattern, before its first dynamic segment. */
58
+ function literalPrefix(rule) {
59
+ const segments = rule.split("/");
60
+ const dynamic = segments.findIndex((segment) => /[*:?(){}\\]/.test(segment));
61
+ return segments.slice(0, dynamic).join("/") + "/";
62
+ }
63
+ function lower(headers) {
64
+ return Object.fromEntries(Object.entries(headers).map(([name, value]) => [name.toLowerCase(), String(value)]));
65
+ }
66
+ function same(a, b) {
67
+ const keys = Object.keys(a);
68
+ return keys.length === Object.keys(b).length && keys.every((key) => b[key] === a[key]);
69
+ }
70
+ function headersOf(rule) {
71
+ const set = rule?.headers;
72
+ return set && typeof set === "object" && Object.keys(set).length > 0 ? set : null;
73
+ }
35
74
  export function filesManifest(publicDir, routeRules, options = {}) {
75
+ const base = (options.baseURL ?? "/").replace(/\/+$/, "");
76
+ const rules = Object.entries(routeRules ?? {});
36
77
  const all = [];
37
78
  const exclude = options.exclude ?? [];
38
79
  if (existsSync(publicDir)) {
@@ -40,33 +81,85 @@ export function filesManifest(publicDir, routeRules, options = {}) {
40
81
  }
41
82
  const present = new Set(all);
42
83
  const encodings = new Set();
43
- const files = all.filter((path) => {
84
+ const listed = all
85
+ .filter((path) => {
44
86
  const suffix = Object.keys(ENCODINGS).find((ext) => path.endsWith(ext));
45
87
  if (!suffix || !present.has(path.slice(0, -suffix.length)))
46
88
  return true;
47
89
  encodings.add(ENCODINGS[suffix]);
48
90
  return false;
91
+ })
92
+ .map((path) => base + path);
93
+ // What a front can state, broadest first: a prefix rule before a longer
94
+ // one, an exact rule last - the order Nitro merges them in, so applying
95
+ // them in turn gives what its matcher resolves.
96
+ const stated = rules
97
+ .filter(([key, rule]) => expressible(key) && headersOf(rule))
98
+ .map(([key, rule]) => ({ match: base + key, headers: { ...headersOf(rule) } }))
99
+ .sort((a, b) => {
100
+ const rank = (match) => (match.endsWith("/**") ? match.length : Number.MAX_SAFE_INTEGER);
101
+ return rank(a.match) - rank(b.match);
102
+ });
103
+ const frontSends = (path) => stated.filter((entry) => ruleMatches(entry.match, path)).reduce((out, entry) => ({ ...out, ...lower(entry.headers) }), {});
104
+ const leftOut = (path) => {
105
+ if (options.resolve) {
106
+ const resolved = options.resolve(path);
107
+ const active = Object.keys(resolved).find((name) => !INERT.has(name) && resolved[name] !== false && resolved[name] != null);
108
+ if (active)
109
+ return `a ${active} route rule applies to it`;
110
+ const nitroSends = lower((resolved.headers && typeof resolved.headers === "object" ? resolved.headers : {}));
111
+ return same(nitroSends, frontSends(path)) ? null : "its route rules' headers cannot be stated as exact or /** matches";
112
+ }
113
+ for (const [key, rule] of rules) {
114
+ const match = base + key;
115
+ if (!expressible(key)) {
116
+ if (path.startsWith(base + literalPrefix(key)))
117
+ return `route rule ${key} cannot be stated as an exact or /** match`;
118
+ continue;
119
+ }
120
+ if (!ruleMatches(match, path))
121
+ continue;
122
+ const active = Object.keys(rule ?? {}).find((name) => !INERT.has(name) && rule[name] !== false && rule[name] != null);
123
+ if (active)
124
+ return `a ${active} route rule applies to it`;
125
+ if (rule?.headers === false)
126
+ return `route rule ${key} resets its headers`;
127
+ }
128
+ return null;
129
+ };
130
+ const files = listed.filter((path) => {
131
+ const why = leftOut(path);
132
+ if (why)
133
+ options.onLeftOut?.(path, why);
134
+ return !why;
49
135
  });
50
- const headers = [];
51
- for (const [match, rule] of Object.entries(routeRules ?? {})) {
52
- const set = rule?.headers;
53
- // Only the forms a front can follow without Nitro's router - and only a
54
- // rule some file is under: a rule for pages is the renderer's business.
55
- if (!set || Object.keys(set).length === 0)
56
- continue;
57
- if (!match.endsWith("/**") ? /[*:]/.test(match) : /[*:]/.test(match.slice(0, -3)))
58
- continue;
59
- if (!files.some((path) => ruleMatches(match, path)))
60
- continue;
61
- headers.push({ match, headers: { ...set } });
62
- }
63
136
  return {
64
137
  v: 1,
65
138
  root: options.root ?? "public",
66
139
  files,
67
140
  precompressed: [...encodings].sort(),
68
- headers,
141
+ // Only a rule some served file is under: a rule for pages is the renderer's business.
142
+ headers: stated.filter((entry) => files.some((path) => ruleMatches(entry.match, path))),
69
143
  middleware: false,
70
144
  };
71
145
  }
146
+ /**
147
+ * The route rules Nitro resolves for a path, by the matcher it compiles them
148
+ * with - h3's, loaded from the app's own Nitro so the answer is that
149
+ * version's. Null when it cannot be loaded or refuses the rules: files.json
150
+ * then falls back to the rules' keys, leaving out more rather than less.
151
+ */
152
+ export async function nitroRouteRules(root, routeRules, baseURL) {
153
+ try {
154
+ const nitro = createRequire(join(root, "package.json")).resolve("nitro");
155
+ const rules = (await import(pathToFileURL(createRequire(nitro).resolve("h3/rules")).href));
156
+ if (!rules.normalizeRouteRules || !rules.createRouteRulesMatcher)
157
+ return null;
158
+ const match = rules.createRouteRulesMatcher(rules.normalizeRouteRules(routeRules ?? {}), { baseURL: baseURL || undefined });
159
+ return (path) => ({ ...(match("GET", path).routeRules ?? {}) });
160
+ }
161
+ catch {
162
+ return null;
163
+ }
164
+ }
72
165
  //# sourceMappingURL=filesManifest.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"filesManifest.js","sourceRoot":"","sources":["../src/filesManifest.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,6BAA6B;AAC7B,EAAE;AACF,0EAA0E;AAC1E,0EAA0E;AAC1E,6EAA6E;AAC7E,4EAA4E;AAC5E,4EAA4E;AAC5E,2EAA2E;AAC3E,2EAA2E;AAC3E,8EAA8E;AAC9E,8CAA8C;AAE9C,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC5D,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,oFAAoF;AACpF,MAAM,SAAS,GAA2B,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;AAwBzF,SAAS,IAAI,CAAC,GAAW,EAAE,IAAY,EAAE,IAA+B,EAAE,GAAa;IACrF,KAAK,MAAM,IAAI,IAAI,WAAW,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC;QAC3C,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QAC7B,MAAM,IAAI,GAAG,GAAG,IAAI,IAAI,IAAI,EAAE,CAAC;QAE/B,IAAI,IAAI,CAAC,IAAI,CAAC;YAAE,SAAS;QACzB,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE;YAAE,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC;;YACzD,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACtB,CAAC;AACH,CAAC;AAED,4FAA4F;AAC5F,MAAM,UAAU,WAAW,CAAC,IAAY,EAAE,IAAY;IACpD,IAAI,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC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MAAM,OAAO,GAA6B,EAAE,CAAC;IAE7C,KAAK,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,UAAU,IAAI,EAAE,CAAC,EAAE,CAAC;QAC7D,MAAM,GAAG,GAAI,IAAoD,EAAE,OAAO,CAAC;QAE3E,wEAAwE;QACxE,wEAAwE;QACxE,IAAI,CAAC,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,KAAK,CAAC;YAAE,SAAS;QACpD,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YAAE,SAAS;QAC5F,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;YAAE,SAAS;QAE9D,OAAO,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,GAAG,GAAG,EAAE,EAAE,CAAC,CAAC;IAC/C,CAAC;IAED,OAAO;QACL,CAAC,EAAE,CAAC;QACJ,IAAI,EAAE,OAAO,CAAC,IAAI,IAAI,QAAQ;QAC9B,KAAK;QACL,aAAa,EAAE,CAAC,GAAG,SAAS,CAAC,CAAC,IAAI,EAAE;QACpC,OAAO;QACP,UAAU,EAAE,KAAK;KAClB,CAAC;AACJ,CAAC","sourcesContent":["// `.output/files.json`: what a server in front of the app may answer from\n// disk, before the app runs.\n//\n// Everything under `.output/public` is answered by Nitro's static handler\n// before the request reaches the renderer: no middleware.ts, no route.ts,\n// no rscKit({ headers }) - those are a page's. A proxy, a CDN or a PHP front\n// controller serving these files itself only has to match what that handler\n// sends, and the build already knows all of it: the files it wrote, and the\n// route rules Nitro serves them under (an asset directory's maxAge is one,\n// `/assets/**` immutable; the service worker's `max-age=0` is another). So\n// the build says so, rather than every front re-deriving it from a reading of\n// Nitro and getting the service worker wrong.\n\nimport { existsSync, readdirSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\n/** The encodings Nitro precompresses to, by the suffix of the sibling it writes. */\nconst ENCODINGS: Record<string, string> = { \".br\": \"br\", \".gz\": \"gzip\", \".zst\": \"zstd\" };\n\nexport interface FilesManifest {\n v: 1;\n /** The directory the files are in, relative to the manifest. */\n root: string;\n /** Every file a request may be answered with, by url path, sorted. */\n files: string[];\n /**\n * The encodings some files also exist in, as a sibling with the suffix\n * (`/sw.js.br` is `/sw.js` in br). Served with `Content-Encoding` and\n * `Vary: Accept-Encoding` when the request accepts it.\n */\n precompressed: string[];\n /**\n * The headers a file goes out with beyond its Content-Type, in order, each\n * applying to an exact path or, ending in `/**`, to every path under it.\n * A file matched by none gets none.\n */\n headers: { match: string; headers: Record<string, string> }[];\n /** Whether anything of the app's runs for a file: never. */\n middleware: false;\n}\n\nfunction walk(dir: string, base: string, skip: (path: string) => boolean, out: string[]): void {\n for (const name of readdirSync(dir).sort()) {\n const full = join(dir, name);\n const path = `${base}/${name}`;\n\n if (skip(path)) continue;\n if (statSync(full).isDirectory()) walk(full, path, skip, out);\n else out.push(path);\n }\n}\n\n/** Whether a route rule's key matches a path: exact, or `/x/**` for everything under /x. */\nexport function ruleMatches(rule: string, path: string): boolean {\n if (rule.endsWith(\"/**\")) return path.startsWith(rule.slice(0, -2));\n\n return rule === path;\n}\n\nexport function filesManifest(\n publicDir: string,\n routeRules: Record<string, unknown> | undefined,\n options: { root?: string; exclude?: string[] } = {},\n): FilesManifest {\n const all: string[] = [];\n const exclude = options.exclude ?? [];\n\n if (existsSync(publicDir)) {\n walk(publicDir, \"\", (path) => exclude.some((prefix) => path === prefix || path.startsWith(prefix + \"/\")), all);\n }\n\n const present = new Set(all);\n const encodings = new Set<string>();\n const files = all.filter((path) => {\n const suffix = Object.keys(ENCODINGS).find((ext) => path.endsWith(ext));\n\n if (!suffix || !present.has(path.slice(0, -suffix.length))) return true;\n\n encodings.add(ENCODINGS[suffix]!);\n\n return false;\n });\n\n const headers: FilesManifest[\"headers\"] = [];\n\n for (const [match, rule] of Object.entries(routeRules ?? {})) {\n const set = (rule as { headers?: Record<string, string> } | null)?.headers;\n\n // Only the forms a front can follow without Nitro's router - and only a\n // rule some file is under: a rule for pages is the renderer's business.\n if (!set || Object.keys(set).length === 0) continue;\n if (!match.endsWith(\"/**\") ? /[*:]/.test(match) : /[*:]/.test(match.slice(0, -3))) continue;\n if (!files.some((path) => ruleMatches(match, path))) continue;\n\n headers.push({ match, headers: { ...set } });\n }\n\n return {\n v: 1,\n root: options.root ?? \"public\",\n files,\n precompressed: [...encodings].sort(),\n headers,\n middleware: false,\n };\n}\n"]}
1
+ {"version":3,"file":"filesManifest.js","sourceRoot":"","sources":["../src/filesManifest.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,6BAA6B;AAC7B,EAAE;AACF,sEAAsE;AACtE,wEAAwE;AACxE,6EAA6E;AAC7E,yEAAyE;AACzE,0EAA0E;AAC1E,2EAA2E;AAC3E,6EAA6E;AAC7E,8EAA8E;AAC9E,2DAA2D;AAC3D,EAAE;AACF,2EAA2E;AAC3E,0EAA0E;AAC1E,2EAA2E;AAC3E,2EAA2E;AAC3E,6EAA6E;AAC7E,8EAA8E;AAC9E,yEAAyE;AACzE,6EAA6E;AAE7E,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,oFAAoF;AACpF,MAAM,SAAS,GAA2B,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EA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G,CAAC,MAAM,MAAM,CAAC,aAAa,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,CAGxF,CAAC;QAEF,IAAI,CAAC,KAAK,CAAC,mBAAmB,IAAI,CAAC,KAAK,CAAC,uBAAuB;YAAE,OAAO,IAAI,CAAC;QAE9E,MAAM,KAAK,GAAG,KAAK,CAAC,uBAAuB,CAAC,KAAK,CAAC,mBAAmB,CAAC,UAAU,IAAI,EAAE,CAAC,EAAE,EAAE,OAAO,EAAE,OAAO,IAAI,SAAS,EAAE,CAAC,CAAC;QAE5H,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,UAAU,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC;IAClE,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["// `.output/files.json`: what a server in front of the app may answer from\n// disk, before the app runs.\n//\n// Everything under the public directory is answered by Nitro's static\n// handler before the request reaches the renderer: no middleware.ts, no\n// route.ts, no rscKit({ headers }) - those are a page's. A proxy, a CDN or a\n// PHP front controller serving these files itself only has to match what\n// that handler sends, and the build already knows all of it: the files it\n// wrote, and the route rules Nitro serves them under (an asset directory's\n// maxAge is one, `/assets/**` immutable; the service worker's `max-age=0` is\n// another). So the build says so, rather than every front re-deriving it from\n// a reading of Nitro and getting the service worker wrong.\n//\n// It fails closed. Nitro's route rules run before its static handler, so a\n// rule decides what a file goes out with - and a rule the manifest cannot\n// state (`/:name.js`, a redirect, cors, a proxy, a `headers: false` reset)\n// would make a front's answer differ from the app's with nobody seeing it.\n// A file under such a rule is left out of `files`: the front sends it to the\n// app, which answers it the way it always would. Each file is checked against\n// Nitro's own matcher (h3's, which Nitro compiles its rules with), not a\n// reading of it: what the front would send has to equal what Nitro resolves.\n\nimport { existsSync, readdirSync, statSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\n/** The encodings Nitro precompresses to, by the suffix of the sibling it writes. */\nconst ENCODINGS: Record<string, string> = { \".br\": \"br\", \".gz\": \"gzip\", \".zst\": \"zstd\" };\n\n/**\n * Rules that never touch a file Nitro's static handler answers: `prerender`\n * is build-time, and the cache rule wraps route handlers, which run after it.\n * Any other rule - redirect, proxy, cors, one an app or module added - leaves\n * the file to the app.\n */\nconst INERT = new Set([\"headers\", \"prerender\", \"cache\"]);\n\nexport interface FilesManifest {\n v: 1;\n /** The directory the files are in, relative to the manifest. */\n root: string;\n /**\n * Every file a request may be answered with, by url path, sorted. A path\n * is the file's name as it is on disk, not percent-encoded: a request's\n * path is decoded before it is looked up.\n */\n files: string[];\n /**\n * The encodings some files also exist in, as a sibling with the suffix\n * (`/sw.js.br` is `/sw.js` in br). Served with `Content-Encoding` and\n * `Vary: Accept-Encoding` when the request accepts it.\n */\n precompressed: string[];\n /**\n * The headers a file goes out with beyond its Content-Type, each applying\n * to an exact path or, ending in `/**`, to every path under it. Every entry\n * that matches applies, in order; a later one replaces an earlier one's\n * header of the same name. A file matched by none gets none.\n */\n headers: { match: string; headers: Record<string, string> }[];\n /** Whether anything of the app's runs for a file: never. */\n middleware: false;\n}\n\n/** The route rules Nitro resolves for a url path, as its matcher merges them. */\nexport type ResolveRouteRules = (path: string) => Record<string, unknown>;\n\nfunction walk(dir: string, base: string, skip: (path: string) => boolean, out: string[]): void {\n for (const name of readdirSync(dir).sort()) {\n const full = join(dir, name);\n const path = `${base}/${name}`;\n\n if (skip(path)) continue;\n if (statSync(full).isDirectory()) walk(full, path, skip, out);\n else out.push(path);\n }\n}\n\n/** Whether a route rule's key matches a path: exact, or `/x/**` for everything under /x. */\nexport function ruleMatches(rule: string, path: string): boolean {\n if (rule.endsWith(\"/**\")) return path.startsWith(rule.slice(0, -2));\n\n return rule === path;\n}\n\n/** Whether a front can follow a rule's key without Nitro's router. */\nfunction expressible(rule: string): boolean {\n return !/[*:?(){}\\\\]/.test(rule.endsWith(\"/**\") ? rule.slice(0, -3) : rule);\n}\n\n/** The literal part of a pattern, before its first dynamic segment. */\nfunction literalPrefix(rule: string): string {\n const segments = rule.split(\"/\");\n const dynamic = segments.findIndex((segment) => /[*:?(){}\\\\]/.test(segment));\n\n return segments.slice(0, dynamic).join(\"/\") + \"/\";\n}\n\nfunction lower(headers: Record<string, string>): Record<string, string> {\n return Object.fromEntries(Object.entries(headers).map(([name, value]) => [name.toLowerCase(), String(value)]));\n}\n\nfunction same(a: Record<string, string>, b: Record<string, string>): boolean {\n const keys = Object.keys(a);\n\n return keys.length === Object.keys(b).length && keys.every((key) => b[key] === a[key]);\n}\n\nfunction headersOf(rule: unknown): Record<string, string> | null {\n const set = (rule as { headers?: unknown } | null)?.headers;\n\n return set && typeof set === \"object\" && Object.keys(set).length > 0 ? (set as Record<string, string>) : null;\n}\n\nexport function filesManifest(\n publicDir: string,\n routeRules: Record<string, unknown> | undefined,\n options: {\n root?: string;\n exclude?: string[];\n /** The app's base url; the files are under it. */\n baseURL?: string;\n /**\n * Nitro's own resolution of a path's rules. Without it a file is checked\n * against the rules by their keys, and one under a pattern the manifest\n * cannot state is left out by the pattern's literal prefix.\n */\n resolve?: ResolveRouteRules | null;\n /** Told about each file left to the app, and why. */\n onLeftOut?: (path: string, why: string) => void;\n } = {},\n): FilesManifest {\n const base = (options.baseURL ?? \"/\").replace(/\\/+$/, \"\");\n const rules = Object.entries(routeRules ?? {});\n const all: string[] = [];\n const exclude = options.exclude ?? [];\n\n if (existsSync(publicDir)) {\n walk(publicDir, \"\", (path) => exclude.some((prefix) => path === prefix || path.startsWith(prefix + \"/\")), all);\n }\n\n const present = new Set(all);\n const encodings = new Set<string>();\n const listed = all\n .filter((path) => {\n const suffix = Object.keys(ENCODINGS).find((ext) => path.endsWith(ext));\n\n if (!suffix || !present.has(path.slice(0, -suffix.length))) return true;\n\n encodings.add(ENCODINGS[suffix]!);\n\n return false;\n })\n .map((path) => base + path);\n\n // What a front can state, broadest first: a prefix rule before a longer\n // one, an exact rule last - the order Nitro merges them in, so applying\n // them in turn gives what its matcher resolves.\n const stated = rules\n .filter(([key, rule]) => expressible(key) && headersOf(rule))\n .map(([key, rule]) => ({ match: base + key, headers: { ...headersOf(rule)! } }))\n .sort((a, b) => {\n const rank = (match: string) => (match.endsWith(\"/**\") ? match.length : Number.MAX_SAFE_INTEGER);\n\n return rank(a.match) - rank(b.match);\n });\n\n const frontSends = (path: string) =>\n stated.filter((entry) => ruleMatches(entry.match, path)).reduce<Record<string, string>>((out, entry) => ({ ...out, ...lower(entry.headers) }), {});\n\n const leftOut = (path: string): string | null => {\n if (options.resolve) {\n const resolved = options.resolve(path);\n const active = Object.keys(resolved).find((name) => !INERT.has(name) && resolved[name] !== false && resolved[name] != null);\n\n if (active) return `a ${active} route rule applies to it`;\n\n const nitroSends = lower((resolved.headers && typeof resolved.headers === \"object\" ? resolved.headers : {}) as Record<string, string>);\n\n return same(nitroSends, frontSends(path)) ? null : \"its route rules' headers cannot be stated as exact or /** matches\";\n }\n\n for (const [key, rule] of rules) {\n const match = base + key;\n\n if (!expressible(key)) {\n if (path.startsWith(base + literalPrefix(key))) return `route rule ${key} cannot be stated as an exact or /** match`;\n continue;\n }\n if (!ruleMatches(match, path)) continue;\n\n const active = Object.keys((rule as object | null) ?? {}).find(\n (name) => !INERT.has(name) && (rule as Record<string, unknown>)[name] !== false && (rule as Record<string, unknown>)[name] != null,\n );\n\n if (active) return `a ${active} route rule applies to it`;\n if ((rule as { headers?: unknown } | null)?.headers === false) return `route rule ${key} resets its headers`;\n }\n\n return null;\n };\n\n const files = listed.filter((path) => {\n const why = leftOut(path);\n\n if (why) options.onLeftOut?.(path, why);\n\n return !why;\n });\n\n return {\n v: 1,\n root: options.root ?? \"public\",\n files,\n precompressed: [...encodings].sort(),\n // Only a rule some served file is under: a rule for pages is the renderer's business.\n headers: stated.filter((entry) => files.some((path) => ruleMatches(entry.match, path))),\n middleware: false,\n };\n}\n\n/**\n * The route rules Nitro resolves for a path, by the matcher it compiles them\n * with - h3's, loaded from the app's own Nitro so the answer is that\n * version's. Null when it cannot be loaded or refuses the rules: files.json\n * then falls back to the rules' keys, leaving out more rather than less.\n */\nexport async function nitroRouteRules(\n root: string,\n routeRules: Record<string, unknown> | undefined,\n baseURL: string,\n): Promise<ResolveRouteRules | null> {\n try {\n const nitro = createRequire(join(root, \"package.json\")).resolve(\"nitro\");\n const rules = (await import(pathToFileURL(createRequire(nitro).resolve(\"h3/rules\")).href)) as {\n normalizeRouteRules?: (config: Record<string, unknown>) => Record<string, unknown>;\n createRouteRulesMatcher?: (rules: Record<string, unknown>, options: { baseURL?: string }) => (method: string, path: string) => { routeRules?: Record<string, unknown> };\n };\n\n if (!rules.normalizeRouteRules || !rules.createRouteRulesMatcher) return null;\n\n const match = rules.createRouteRulesMatcher(rules.normalizeRouteRules(routeRules ?? {}), { baseURL: baseURL || undefined });\n\n return (path) => ({ ...(match(\"GET\", path).routeRules ?? {}) });\n } catch {\n return null;\n }\n}\n"]}
package/dist/vite.js CHANGED
@@ -56,6 +56,25 @@ let clientLibraryImports = [];
56
56
  let nitroPreset = null;
57
57
  /** Set by Nitro's setup of a built server, which asks for the commands before Vite has resolved. */
58
58
  let nitroBuilding = false;
59
+ /**
60
+ * Where Nitro writes this build, from the module's setup. The preset decides
61
+ * it: `.output/server` on node, bun and Workers, a function directory on
62
+ * Vercel (`.vercel/output/functions/__server.func`) and Netlify, `_worker.js`
63
+ * on Cloudflare Pages. What the server reads at runtime goes in `serverDir`,
64
+ * because that is what the platform deploys as the server; what a deploy
65
+ * reads goes in `dir`. Neither is derivable from Vite's client outDir.
66
+ */
67
+ let nitroOutput = null;
68
+ /**
69
+ * Where the build's manifests for a deploy go - rsc-kit.json, edge.json,
70
+ * files.json: Nitro's output directory, unless that is the public one
71
+ * (Cloudflare Pages serves all of `dist`), when they would be published;
72
+ * then `.output/` at the app root, where the docs say they are.
73
+ */
74
+ function deployManifestDir(projectRoot, output) {
75
+ const inside = relative(output.publicDir, output.dir);
76
+ return inside === "" || (!inside.startsWith("..") && !isAbsolute(inside)) ? join(projectRoot, ".output") : output.dir;
77
+ }
59
78
  /** The mode this build bakes in, for the process that runs it. See nodeEnvPlugin. */
60
79
  let builtNodeEnv = "production";
61
80
  /** `src/commands`, read once per build; null until asked. See buildCommands(). */
@@ -7726,6 +7745,11 @@ function clientImportsAudit() {
7726
7745
  },
7727
7746
  };
7728
7747
  }
7748
+ /** `inner` as a path under `outer` - `["/x"]` - or nothing when it is not inside it. */
7749
+ function insideOf(outer, inner) {
7750
+ const path = relative(outer, inner).replace(/\\/g, "/");
7751
+ return path && !path.startsWith("..") && !isAbsolute(path) ? [`/${path}`] : [];
7752
+ }
7729
7753
  /** Whether the app's Nitro exports `nitro/services`: the release candidate on. */
7730
7754
  function nitroHasPublicServices(root) {
7731
7755
  try {
@@ -7992,6 +8016,11 @@ export function rscKit(options = {}) {
7992
8016
  return;
7993
8017
  nitroPreset = nitro.options.preset ?? null;
7994
8018
  nitroBuilding = true;
8019
+ nitroOutput = {
8020
+ dir: nitro.options.output.dir ?? dirname(nitro.options.output.serverDir),
8021
+ serverDir: nitro.options.output.serverDir,
8022
+ publicDir: nitro.options.output.publicDir ?? join(dirname(nitro.options.output.serverDir), "public"),
8023
+ };
7995
8024
  // The commands that did not ask for register() are an entry of the
7996
8025
  // rsc environment that Nitro would leave behind: it bundles the
7997
8026
  // server from the environment's main entry only. Given to it as an
@@ -8074,16 +8103,54 @@ export function rscKit(options = {}) {
8074
8103
  // Workers build copies into the public directory (the hook below)
8075
8104
  // are read through a binding, never served: left out by name, not
8076
8105
  // by running first.
8106
+ //
8107
+ // Written to Nitro's output directory - `.output` on node, bun and
8108
+ // Workers, `.vercel/output` on Vercel, `.output` at the app root when
8109
+ // the output directory is the public one (Cloudflare Pages) - never
8110
+ // beside the server bundle, which on some presets is a function
8111
+ // directory. A file's
8112
+ // path is its url: Nitro serves `<publicDir>/x` at `<baseURL>/x`, and
8113
+ // most presets nest the public directory under the base url, so
8114
+ // `root` is that directory with the base taken back off.
8077
8115
  nitro.hooks.hook("compiled", async () => {
8078
- const { filesManifest } = await import("./filesManifest.js");
8116
+ const { filesManifest, nitroRouteRules } = await import("./filesManifest.js");
8079
8117
  const { ASSETS_PREFIX } = await import("./files.js");
8080
- const serverDir = nitro.options.output.serverDir;
8081
- const publicDir = nitro.options.output.publicDir ?? join(dirname(serverDir), "public");
8082
- const manifest = filesManifest(publicDir, nitro.options.routeRules, {
8083
- root: relative(dirname(serverDir), publicDir).replace(/\\/g, "/") || ".",
8084
- exclude: [`/${ASSETS_PREFIX(NITRO_STATIC_DIR)}`],
8118
+ const publicDir = nitro.options.output.publicDir ?? join(nitro.options.output.dir ?? dirname(nitro.options.output.serverDir), "public");
8119
+ const outputDir = deployManifestDir(projectRoot, { dir: nitro.options.output.dir ?? dirname(nitro.options.output.serverDir), publicDir });
8120
+ const baseURL = (nitro.options.baseURL ?? "/").replace(/\/+$/, "");
8121
+ const publicRoot = baseURL && publicDir.replace(/[\\/]+$/, "").replace(/\\/g, "/").endsWith(baseURL)
8122
+ ? publicDir.replace(/[\\/]+$/, "").slice(0, -baseURL.length)
8123
+ : baseURL ? null : publicDir;
8124
+ const leftOut = [];
8125
+ const manifest = filesManifest(publicRoot === null ? join(outputDir, "-no-files-") : publicDir, nitro.options.routeRules, {
8126
+ root: relative(outputDir, publicRoot ?? publicDir).replace(/\\/g, "/") || ".",
8127
+ exclude: [
8128
+ `/${ASSETS_PREFIX(NITRO_STATIC_DIR)}`,
8129
+ // A platform's own configuration, which it reads and never
8130
+ // serves: Workers and Netlify take `_headers` and `_redirects`
8131
+ // from the public directory, Pages `_routes.json`.
8132
+ "/_headers",
8133
+ "/_redirects",
8134
+ "/_routes.json",
8135
+ "/.assetsignore",
8136
+ // The server itself, where a preset builds it inside the public
8137
+ // directory - Cloudflare Pages' `_worker.js`.
8138
+ ...insideOf(publicDir, nitro.options.output.serverDir),
8139
+ ],
8140
+ baseURL,
8141
+ resolve: await nitroRouteRules(projectRoot, nitro.options.routeRules, baseURL),
8142
+ onLeftOut: (path, why) => leftOut.push(`${path} (${why})`),
8085
8143
  });
8086
- writeFileSync(join(dirname(serverDir), "files.json"), JSON.stringify(manifest, null, 2) + "\n");
8144
+ // A public directory not under its base url cannot be served by
8145
+ // joining a root and a url path: nothing is listed, and every
8146
+ // request goes to the app.
8147
+ if (publicRoot === null)
8148
+ log(`files.json lists no files: the public directory ${publicDir} is not under the base url ${baseURL}`);
8149
+ if (leftOut.length) {
8150
+ log(`files.json leaves ${leftOut.length} file${leftOut.length === 1 ? "" : "s"} to the app, under route rules a server in front cannot follow: ${leftOut.slice(0, 5).join(", ")}${leftOut.length > 5 ? ", ..." : ""}`);
8151
+ }
8152
+ mkdirSync(outputDir, { recursive: true });
8153
+ writeFileSync(join(outputDir, "files.json"), JSON.stringify(manifest, null, 2) + "\n");
8087
8154
  });
8088
8155
  // On Workers the stored pages ride the static assets, not the bundle.
8089
8156
  // Copied once Nitro has listed its public files, so the copies are
@@ -8137,14 +8204,25 @@ export function rscKit(options = {}) {
8137
8204
  // deploy's list against the new server, every file 404s, and the
8138
8205
  // install fails - leaving the old worker in charge, serving the old
8139
8206
  // documents, for as long as the browser holds the script.
8140
- nitro.options.routeRules = {
8141
- ...(nitro.options.routeRules ?? {}),
8207
+ //
8208
+ // And the other files the build writes under a fixed name: the app's
8209
+ // own worker code the worker imports (src/app/sw.js, served as
8210
+ // /sw-app.js - kept by a heuristic it is the old code inside the new
8211
+ // worker), the web app manifest, and the icons, splash screens and
8212
+ // share images under /_app/, which hold nothing fingerprinted. Each
8213
+ // revalidates; its ETag makes that a 304. The app's own public/ files
8214
+ // are its own to decide. A rule the app set for one of these paths
8215
+ // keeps its headers over these.
8216
+ const revalidate = { "cache-control": "public, max-age=0, must-revalidate" };
8217
+ const rules = (nitro.options.routeRules ?? {});
8218
+ nitro.options.routeRules = { ...rules };
8219
+ for (const path of ["/sw.js", "/sw-app.js", "/manifest.webmanifest", `${ASSET_BASE}/**`]) {
8142
8220
  // Spelled with max-age=0 rather than no-cache: a CDN's browser
8143
8221
  // cache TTL - Cloudflare's, four hours - applies where the origin
8144
8222
  // names no max-age, and rewrote no-cache to max-age=14400; a
8145
8223
  // max-age of zero it leaves alone, as it leaves the documents'.
8146
- "/sw.js": { ...(nitro.options.routeRules?.["/sw.js"] ?? {}), headers: { "cache-control": "public, max-age=0, must-revalidate", ...(nitro.options.routeRules?.["/sw.js"]?.headers ?? {}) } },
8147
- };
8224
+ nitro.options.routeRules[path] = { ...(rules[path] ?? {}), headers: { ...revalidate, ...(rules[path]?.headers ?? {}) } };
8225
+ }
8148
8226
  // The names of functions survive Nitro's bundle. The pages were
8149
8227
  // prerendered against Vite's own server bundles, where a dependency
8150
8228
  // is loaded from node_modules under the names it was written with;
@@ -8803,10 +8881,20 @@ export function rscKit(options = {}) {
8803
8881
  // else exist on the build machine and nowhere after that. They go beside
8804
8882
  // the server bundle instead, and buildApp runs before Nitro assembles, so
8805
8883
  // they are in place by the time it does.
8884
+ //
8885
+ // Beside the server Nitro writes, wherever the preset puts it: a
8886
+ // function directory on Vercel and Netlify is what the platform
8887
+ // deploys, and a path next to it is left on the build machine - every
8888
+ // page then rendered live, with nothing to say so.
8806
8889
  const clientOut = builder?.environments?.client?.config?.build?.outDir;
8807
- const staticDir = clientOut
8808
- ? join(dirname(clientOut), "server", NITRO_STATIC_DIR)
8809
- : join(outDir, NITRO_STATIC_DIR);
8890
+ const staticDir = nitroOutput
8891
+ ? join(nitroOutput.serverDir, NITRO_STATIC_DIR)
8892
+ : clientOut
8893
+ ? join(dirname(clientOut), "server", NITRO_STATIC_DIR)
8894
+ : join(outDir, NITRO_STATIC_DIR);
8895
+ // Where a deploy reads what the build produced: Nitro's output
8896
+ // directory, as for files.json.
8897
+ const manifestDir = nitroOutput ? deployManifestDir(projectRoot, nitroOutput) : clientOut ? dirname(clientOut) : outDir;
8810
8898
  const { frozen, results, shells, routes, pathKey: pathKeyOf, build: clientBuild } = await prerenderAfterBundles(bundle, staticDir, clientOut ?? publicAssetsDir, builder ? knownActionsOf(builder.config, projectRoot) : []);
8811
8899
  // The edge contract's static pages, each given a payload it boots from
8812
8900
  // without the app - before the build id, which hashes the documents
@@ -8880,7 +8968,8 @@ export function rscKit(options = {}) {
8880
8968
  // compute it - or knowing where rsc-kit keeps things inside .output.
8881
8969
  // Written by the code that decided, so it cannot disagree with it.
8882
8970
  if (clientOut) {
8883
- writeFileSync(join(dirname(clientOut), "rsc-kit.json"), JSON.stringify(output === "export"
8971
+ mkdirSync(manifestDir, { recursive: true });
8972
+ writeFileSync(join(manifestDir, "rsc-kit.json"), JSON.stringify(output === "export"
8884
8973
  ? { version: PACKAGE_VERSION, output: "export", dir: relative(projectRoot, exportPath) }
8885
8974
  : {
8886
8975
  version: PACKAGE_VERSION,
@@ -8896,10 +8985,10 @@ export function rscKit(options = {}) {
8896
8985
  // belong to. Written by every server build, with empty lists when
8897
8986
  // there are none, so a platform can tell "none" from "an rsc-kit too
8898
8987
  // old to say". Not by an export, which has no origin to answer for it.
8899
- const markerFile = join(dirname(clientOut), "edge.json");
8988
+ const markerFile = join(manifestDir, "edge.json");
8900
8989
  // v1's marker, from a build before this one: an edge reading it
8901
8990
  // would ask for endpoints that are no longer here.
8902
- rmSync(join(dirname(clientOut), "ppr.json"), { force: true });
8991
+ rmSync(join(manifestDir, "ppr.json"), { force: true });
8903
8992
  if (output !== "export" && marker) {
8904
8993
  writeFileSync(markerFile, JSON.stringify(marker, null, 2) + "\n");
8905
8994
  }