@rsc-kit/core 0.30.23 → 0.30.25

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.
@@ -1,14 +1,23 @@
1
1
  /**
2
- * Server files that import a client library.
2
+ * Server files that reach client-only React on the server.
3
3
  *
4
4
  * A server component may import a client library - `<SheetClose>` from
5
5
  * base-ui rendered inside server output is legal here and in Next.js. What
6
6
  * is worth a line is the shape that cost an afternoon: a file with no
7
- * "use client" that only wraps client components (a shadcn ui/ file that
8
- * lost its directive in a port) imported from the server, so the library's
9
- * internals run in the rsc environment. The build cannot tell the two
10
- * apart; it can say which server files do it, and with which packages, so
11
- * the person reading can.
7
+ * "use client" (a shadcn ui/ file that lost its directive in a port) whose
8
+ * code, or a library's under it, calls a hook in the rsc environment, which
9
+ * fails at render as "(0, import_react_react_server.useState) is not a
10
+ * function" - naming React, not the file.
11
+ *
12
+ * This used to name every server file importing any package that depends on
13
+ * React, which on a real app was 26 files of icons, markdown and base-ui
14
+ * parts that carry their own "use client", and the one that mattered was
15
+ * lost among them. So the code is read instead: from the server file into
16
+ * the packages it imports, stopping at a client reference - a module with
17
+ * the directive, whose code never runs on the server - and a file is named
18
+ * only when what is left mentions a React API the server build does not
19
+ * have. Mentions, not calls: a library can hold a hook in an export the
20
+ * page never renders, so the line names the API for the reader to judge.
12
21
  *
13
22
  * Read off the rsc environment's module graph after it is built. A file with
14
23
  * the directive never appears: in that graph it is already a reference, and
@@ -17,8 +26,10 @@
17
26
  export interface ClientLibraryImport {
18
27
  /** The server file, relative to the source dir. */
19
28
  file: string;
20
- /** The client packages it imports, by name. */
29
+ /** The packages whose server-run code reaches a client-only API, by name. Empty when the file itself does. */
21
30
  packages: string[];
31
+ /** The client-only React APIs reached, by name. */
32
+ calls: string[];
22
33
  /** The first app file that imports it, relative to the source dir - or null for a route file. */
23
34
  from: string | null;
24
35
  }
@@ -26,7 +37,16 @@ export interface ModuleGraph {
26
37
  moduleIds(): Iterable<string>;
27
38
  importedIds(id: string): readonly string[];
28
39
  importers(id: string): readonly string[];
40
+ /** The module's code as built - for a client reference, the reference. */
41
+ code(id: string): string | null;
29
42
  }
43
+ /**
44
+ * React's APIs that its server build leaves out, as of React 19: the ones a
45
+ * render needs state or an effect for. A test reads them off React itself.
46
+ * Not Component or startTransition - the one is a word in every library's
47
+ * prose, the other runs in an event handler, never during a render.
48
+ */
49
+ export declare const CLIENT_ONLY_APIS: readonly ["createContext", "useActionState", "useContext", "useDeferredValue", "useEffect", "useEffectEvent", "useFormState", "useFormStatus", "useImperativeHandle", "useInsertionEffect", "useLayoutEffect", "useOptimistic", "useReducer", "useRef", "useState", "useSyncExternalStore", "useTransition"];
30
50
  /** The package a node_modules id belongs to, or null for anything else. */
31
51
  export declare function packageOf(id: string): string | null;
32
52
  export declare function serverImportsOfClientPackages(graph: ModuleGraph, options: {
@@ -1,3 +1,38 @@
1
+ /**
2
+ * React's APIs that its server build leaves out, as of React 19: the ones a
3
+ * render needs state or an effect for. A test reads them off React itself.
4
+ * Not Component or startTransition - the one is a word in every library's
5
+ * prose, the other runs in an event handler, never during a render.
6
+ */
7
+ export const CLIENT_ONLY_APIS = [
8
+ "createContext",
9
+ "useActionState",
10
+ "useContext",
11
+ "useDeferredValue",
12
+ "useEffect",
13
+ "useEffectEvent",
14
+ "useFormState",
15
+ "useFormStatus",
16
+ "useImperativeHandle",
17
+ "useInsertionEffect",
18
+ "useLayoutEffect",
19
+ "useOptimistic",
20
+ "useReducer",
21
+ "useRef",
22
+ "useState",
23
+ "useSyncExternalStore",
24
+ "useTransition",
25
+ ];
26
+ const CLIENT_ONLY = new RegExp(`\\b(${CLIENT_ONLY_APIS.join("|")})\\b`, "g");
27
+ const COMMENT = /\/\*[\s\S]*?\*\/|(^|[^:])\/\/[^\n]*/g;
28
+ /** plugin-rsc's reference for a "use client" module: its code stays on the client. */
29
+ const isReference = (code) => code.includes("registerClientReference");
30
+ /** The client-only APIs a module's own code mentions, outside its comments. */
31
+ function clientOnlyIn(code) {
32
+ if (!code || isReference(code))
33
+ return [];
34
+ return [...new Set([...code.replace(COMMENT, "$1").matchAll(CLIENT_ONLY)].map((m) => m[1]))];
35
+ }
1
36
  const PACKAGE = /\/node_modules\/(@[^/]+\/[^/]+|[^/@][^/]*)/;
2
37
  /** The package a node_modules id belongs to, or null for anything else. */
3
38
  export function packageOf(id) {
@@ -13,21 +48,54 @@ export function serverImportsOfClientPackages(graph, options) {
13
48
  !id.startsWith("\0");
14
49
  const relative = (id) => (id.split("?")[0] ?? id).slice(root.length);
15
50
  const out = [];
51
+ const inClientPackage = (id) => {
52
+ const name = packageOf(id);
53
+ return name !== null && client.has(name) && !ignore.has(name);
54
+ };
55
+ // What a package module and everything it runs on the server reach,
56
+ // memoised: one barrel is imported by many files. A cycle reads as nothing
57
+ // more on its second visit, which is all a union needs.
58
+ const reached = new Map();
59
+ const reach = (id) => {
60
+ const known = reached.get(id);
61
+ if (known)
62
+ return known;
63
+ const apis = new Set();
64
+ reached.set(id, apis);
65
+ const code = graph.code(id);
66
+ if (code !== null && isReference(code))
67
+ return apis;
68
+ for (const api of clientOnlyIn(code))
69
+ apis.add(api);
70
+ for (const next of graph.importedIds(id)) {
71
+ if (inClientPackage(next))
72
+ for (const api of reach(next))
73
+ apis.add(api);
74
+ }
75
+ return apis;
76
+ };
16
77
  for (const id of graph.moduleIds()) {
17
78
  if (!isApp(id))
18
79
  continue;
80
+ const calls = new Set(clientOnlyIn(graph.code(id)));
19
81
  const packages = new Set();
20
82
  for (const imported of graph.importedIds(id)) {
21
- const name = packageOf(imported);
22
- if (name && client.has(name) && !ignore.has(name))
23
- packages.add(name);
83
+ if (!inClientPackage(imported))
84
+ continue;
85
+ const apis = reach(imported);
86
+ if (apis.size === 0)
87
+ continue;
88
+ packages.add(packageOf(imported));
89
+ for (const api of apis)
90
+ calls.add(api);
24
91
  }
25
- if (packages.size === 0)
92
+ if (calls.size === 0)
26
93
  continue;
27
94
  const from = graph.importers(id).find(isApp);
28
95
  out.push({
29
96
  file: relative(id),
30
97
  packages: [...packages].sort(),
98
+ calls: [...calls].sort(),
31
99
  from: from ? relative(from) : null,
32
100
  });
33
101
  }
@@ -1 +1 @@
1
- {"version":3,"file":"clientImports.js","sourceRoot":"","sources":["../src/clientImports.ts"],"names":[],"mappings":"AA+BA,MAAM,OAAO,GAAG,4CAA4C,CAAC;AAE7D,2EAA2E;AAC3E,MAAM,UAAU,SAAS,CAAC,EAAU;IAClC,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;IAEnD,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AAClC,CAAC;AAED,MAAM,UAAU,6BAA6B,CAC3C,KAAkB,EAClB,OAIC;IAED,MAAM,IAAI,GAAG,OAAO,CAAC,SAAS,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,GAAG,GAAG,CAAC;IACzD,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;IAC/C,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC;IAC7C,MAAM,KAAK,GAAG,CAAC,EAAU,EAAE,EAAE,CAC3B,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC;QACnB,CAAC,EAAE,CAAC,QAAQ,CAAC,gBAAgB,CAAC;QAC9B,CAAC,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IACvB,MAAM,QAAQ,GAAG,CAAC,EAAU,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC7E,MAAM,GAAG,GAA0B,EAAE,CAAC;IAEtC,KAAK,MAAM,EAAE,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,CAAC;QACnC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YAAE,SAAS;QAEzB,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAU,CAAC;QAEnC,KAAK,MAAM,QAAQ,IAAI,KAAK,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,CAAC;YAC7C,MAAM,IAAI,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAC;YAEjC,IAAI,IAAI,IAAI,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC;gBAAE,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACxE,CAAC;QAED,IAAI,QAAQ,CAAC,IAAI,KAAK,CAAC;YAAE,SAAS;QAElC,MAAM,IAAI,GAAG,KAAK,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAE7C,GAAG,CAAC,IAAI,CAAC;YACP,IAAI,EAAE,QAAQ,CAAC,EAAE,CAAC;YAClB,QAAQ,EAAE,CAAC,GAAG,QAAQ,CAAC,CAAC,IAAI,EAAE;YAC9B,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI;SACnC,CAAC,CAAC;IACL,CAAC;IAED,OAAO,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * Server files that import a client library.\n *\n * A server component may import a client library - `<SheetClose>` from\n * base-ui rendered inside server output is legal here and in Next.js. What\n * is worth a line is the shape that cost an afternoon: a file with no\n * \"use client\" that only wraps client components (a shadcn ui/ file that\n * lost its directive in a port) imported from the server, so the library's\n * internals run in the rsc environment. The build cannot tell the two\n * apart; it can say which server files do it, and with which packages, so\n * the person reading can.\n *\n * Read off the rsc environment's module graph after it is built. A file with\n * the directive never appears: in that graph it is already a reference, and\n * a reference imports nothing.\n */\nexport interface ClientLibraryImport {\n /** The server file, relative to the source dir. */\n file: string;\n /** The client packages it imports, by name. */\n packages: string[];\n /** The first app file that imports it, relative to the source dir - or null for a route file. */\n from: string | null;\n}\n\nexport interface ModuleGraph {\n moduleIds(): Iterable<string>;\n importedIds(id: string): readonly string[];\n importers(id: string): readonly string[];\n}\n\nconst PACKAGE = /\\/node_modules\\/(@[^/]+\\/[^/]+|[^/@][^/]*)/;\n\n/** The package a node_modules id belongs to, or null for anything else. */\nexport function packageOf(id: string): string | null {\n const match = PACKAGE.exec(id.split(\"?\")[0] ?? id);\n\n return match ? match[1]! : null;\n}\n\nexport function serverImportsOfClientPackages(\n graph: ModuleGraph,\n options: {\n sourceDir: string;\n clientPackages: Iterable<string>;\n ignore?: Iterable<string>;\n },\n): ClientLibraryImport[] {\n const root = options.sourceDir.replace(/\\/+$/, \"\") + \"/\";\n const client = new Set(options.clientPackages);\n const ignore = new Set(options.ignore ?? []);\n const isApp = (id: string) =>\n id.startsWith(root) &&\n !id.includes(\"/node_modules/\") &&\n !id.startsWith(\"\\0\");\n const relative = (id: string) => (id.split(\"?\")[0] ?? id).slice(root.length);\n const out: ClientLibraryImport[] = [];\n\n for (const id of graph.moduleIds()) {\n if (!isApp(id)) continue;\n\n const packages = new Set<string>();\n\n for (const imported of graph.importedIds(id)) {\n const name = packageOf(imported);\n\n if (name && client.has(name) && !ignore.has(name)) packages.add(name);\n }\n\n if (packages.size === 0) continue;\n\n const from = graph.importers(id).find(isApp);\n\n out.push({\n file: relative(id),\n packages: [...packages].sort(),\n from: from ? relative(from) : null,\n });\n }\n\n return out.sort((a, b) => a.file.localeCompare(b.file));\n}\n"]}
1
+ {"version":3,"file":"clientImports.js","sourceRoot":"","sources":["../src/clientImports.ts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,SAAS,CAAC,QAAQ,CAAE,CAAC,CAAC;YACnC,KAAK,MAAM,GAAG,IAAI,IAAI;gBAAE,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACzC,CAAC;QAED,IAAI,KAAK,CAAC,IAAI,KAAK,CAAC;YAAE,SAAS;QAE/B,MAAM,IAAI,GAAG,KAAK,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAE7C,GAAG,CAAC,IAAI,CAAC;YACP,IAAI,EAAE,QAAQ,CAAC,EAAE,CAAC;YAClB,QAAQ,EAAE,CAAC,GAAG,QAAQ,CAAC,CAAC,IAAI,EAAE;YAC9B,KAAK,EAAE,CAAC,GAAG,KAAK,CAAC,CAAC,IAAI,EAAE;YACxB,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI;SACnC,CAAC,CAAC;IACL,CAAC;IAED,OAAO,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * Server files that reach client-only React on the server.\n *\n * A server component may import a client library - `<SheetClose>` from\n * base-ui rendered inside server output is legal here and in Next.js. What\n * is worth a line is the shape that cost an afternoon: a file with no\n * \"use client\" (a shadcn ui/ file that lost its directive in a port) whose\n * code, or a library's under it, calls a hook in the rsc environment, which\n * fails at render as \"(0, import_react_react_server.useState) is not a\n * function\" - naming React, not the file.\n *\n * This used to name every server file importing any package that depends on\n * React, which on a real app was 26 files of icons, markdown and base-ui\n * parts that carry their own \"use client\", and the one that mattered was\n * lost among them. So the code is read instead: from the server file into\n * the packages it imports, stopping at a client reference - a module with\n * the directive, whose code never runs on the server - and a file is named\n * only when what is left mentions a React API the server build does not\n * have. Mentions, not calls: a library can hold a hook in an export the\n * page never renders, so the line names the API for the reader to judge.\n *\n * Read off the rsc environment's module graph after it is built. A file with\n * the directive never appears: in that graph it is already a reference, and\n * a reference imports nothing.\n */\nexport interface ClientLibraryImport {\n /** The server file, relative to the source dir. */\n file: string;\n /** The packages whose server-run code reaches a client-only API, by name. Empty when the file itself does. */\n packages: string[];\n /** The client-only React APIs reached, by name. */\n calls: string[];\n /** The first app file that imports it, relative to the source dir - or null for a route file. */\n from: string | null;\n}\n\nexport interface ModuleGraph {\n moduleIds(): Iterable<string>;\n importedIds(id: string): readonly string[];\n importers(id: string): readonly string[];\n /** The module's code as built - for a client reference, the reference. */\n code(id: string): string | null;\n}\n\n/**\n * React's APIs that its server build leaves out, as of React 19: the ones a\n * render needs state or an effect for. A test reads them off React itself.\n * Not Component or startTransition - the one is a word in every library's\n * prose, the other runs in an event handler, never during a render.\n */\nexport const CLIENT_ONLY_APIS = [\n \"createContext\",\n \"useActionState\",\n \"useContext\",\n \"useDeferredValue\",\n \"useEffect\",\n \"useEffectEvent\",\n \"useFormState\",\n \"useFormStatus\",\n \"useImperativeHandle\",\n \"useInsertionEffect\",\n \"useLayoutEffect\",\n \"useOptimistic\",\n \"useReducer\",\n \"useRef\",\n \"useState\",\n \"useSyncExternalStore\",\n \"useTransition\",\n] as const;\n\nconst CLIENT_ONLY = new RegExp(`\\\\b(${CLIENT_ONLY_APIS.join(\"|\")})\\\\b`, \"g\");\nconst COMMENT = /\\/\\*[\\s\\S]*?\\*\\/|(^|[^:])\\/\\/[^\\n]*/g;\n\n/** plugin-rsc's reference for a \"use client\" module: its code stays on the client. */\nconst isReference = (code: string) => code.includes(\"registerClientReference\");\n\n/** The client-only APIs a module's own code mentions, outside its comments. */\nfunction clientOnlyIn(code: string | null): string[] {\n if (!code || isReference(code)) return [];\n\n return [...new Set([...code.replace(COMMENT, \"$1\").matchAll(CLIENT_ONLY)].map((m) => m[1]!))];\n}\n\nconst PACKAGE = /\\/node_modules\\/(@[^/]+\\/[^/]+|[^/@][^/]*)/;\n\n/** The package a node_modules id belongs to, or null for anything else. */\nexport function packageOf(id: string): string | null {\n const match = PACKAGE.exec(id.split(\"?\")[0] ?? id);\n\n return match ? match[1]! : null;\n}\n\nexport function serverImportsOfClientPackages(\n graph: ModuleGraph,\n options: {\n sourceDir: string;\n clientPackages: Iterable<string>;\n ignore?: Iterable<string>;\n },\n): ClientLibraryImport[] {\n const root = options.sourceDir.replace(/\\/+$/, \"\") + \"/\";\n const client = new Set(options.clientPackages);\n const ignore = new Set(options.ignore ?? []);\n const isApp = (id: string) =>\n id.startsWith(root) &&\n !id.includes(\"/node_modules/\") &&\n !id.startsWith(\"\\0\");\n const relative = (id: string) => (id.split(\"?\")[0] ?? id).slice(root.length);\n const out: ClientLibraryImport[] = [];\n const inClientPackage = (id: string) => {\n const name = packageOf(id);\n return name !== null && client.has(name) && !ignore.has(name);\n };\n\n // What a package module and everything it runs on the server reach,\n // memoised: one barrel is imported by many files. A cycle reads as nothing\n // more on its second visit, which is all a union needs.\n const reached = new Map<string, Set<string>>();\n const reach = (id: string): Set<string> => {\n const known = reached.get(id);\n if (known) return known;\n\n const apis = new Set<string>();\n reached.set(id, apis);\n\n const code = graph.code(id);\n if (code !== null && isReference(code)) return apis;\n\n for (const api of clientOnlyIn(code)) apis.add(api);\n\n for (const next of graph.importedIds(id)) {\n if (inClientPackage(next)) for (const api of reach(next)) apis.add(api);\n }\n\n return apis;\n };\n\n for (const id of graph.moduleIds()) {\n if (!isApp(id)) continue;\n\n const calls = new Set(clientOnlyIn(graph.code(id)));\n const packages = new Set<string>();\n\n for (const imported of graph.importedIds(id)) {\n if (!inClientPackage(imported)) continue;\n\n const apis = reach(imported);\n if (apis.size === 0) continue;\n\n packages.add(packageOf(imported)!);\n for (const api of apis) calls.add(api);\n }\n\n if (calls.size === 0) continue;\n\n const from = graph.importers(id).find(isApp);\n\n out.push({\n file: relative(id),\n packages: [...packages].sort(),\n calls: [...calls].sort(),\n from: from ? relative(from) : null,\n });\n }\n\n return out.sort((a, b) => a.file.localeCompare(b.file));\n}\n"]}
package/dist/commands.js CHANGED
@@ -184,7 +184,7 @@ export async function runCommand(argv, options) {
184
184
  return exitCodeOf(await module.default(args, context), name);
185
185
  }
186
186
  catch (error) {
187
- err(`[rsc-kit] the command "${name}" failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`);
187
+ err(`[rsc-kit] the command "${name}" failed: ${describeError(error, true)}\n`);
188
188
  return 1;
189
189
  }
190
190
  })();
@@ -209,7 +209,7 @@ export async function runCommand(argv, options) {
209
209
  await Promise.race([
210
210
  Promise.resolve()
211
211
  .then(() => options.shutdown?.())
212
- .catch((error) => err(`[rsc-kit] instrumentation.ts shutdown() failed: ${error instanceof Error ? error.message : String(error)}\n`)),
212
+ .catch((error) => err(`[rsc-kit] instrumentation.ts shutdown() failed: ${describeError(error, false)}\n`)),
213
213
  new Promise((resolve) => {
214
214
  timer = setTimeout(resolve, limit);
215
215
  unref(timer);
@@ -219,4 +219,24 @@ export async function runCommand(argv, options) {
219
219
  }
220
220
  return code;
221
221
  }
222
+ /**
223
+ * An error and every cause under it, one line of `[cause]:` each.
224
+ *
225
+ * A library that wraps an error keeps the reason in `cause`, and a stack does
226
+ * not print it: Drizzle's DrizzleQueryError carries the SQL as its message and
227
+ * the database's refusal - a timeout, a wrong password - as its cause, so a
228
+ * failed migration said what it tried and never why. A cause that is not an
229
+ * Error is printed as it is, and a chain that loops back stops there.
230
+ */
231
+ function describeError(error, stack) {
232
+ const seen = new Set();
233
+ const parts = [];
234
+ let current = error;
235
+ while (current !== undefined && current !== null && !seen.has(current)) {
236
+ seen.add(current);
237
+ parts.push(current instanceof Error ? (stack ? (current.stack ?? `${current.name}: ${current.message}`) : current.message) : String(current));
238
+ current = current instanceof Error ? current.cause : undefined;
239
+ }
240
+ return parts.join('\n[cause]: ');
241
+ }
222
242
  //# sourceMappingURL=commands.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"commands.js","sourceRoot":"","sources":["../src/commands.ts"],"names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,CAAC,CAAC;SACH,CAAC,CAAA;QAEF,YAAY,CAAC,KAA2C,CAAC,CAAA;IAC3D,CAAC;IAED,OAAO,IAAI,CAAA;AACb,CAAC","sourcesContent":["/**\n * App commands: the files in `src/commands`, run as `./app <name>`.\n *\n * A compiled app is one binary that starts a server, and a release step or a\n * queue worker is the same code started differently - `./app migrate`,\n * `./app work`. The same entry also runs from a plain build, as\n * `node .output/server/commands.mjs <name>`, so nothing about a command\n * depends on Bun, on a platform, or on the binary.\n *\n * Each command is a file with a default export, `(args, context) => number\n * | void`, where `context` is `{ signal, deadline }`. It shares the build's code and dependencies, so the database\n * package and the logger the pages use are the ones it uses, in the same\n * bundle. It is loaded only when it is named: the server never evaluates one.\n *\n * `register()` from instrumentation.ts is skipped unless the command says\n * `export const register = true`. Importing instrumentation.ts is not\n * skipped - a bad environment fails there, at import, for a command as for a\n * server - but a command that only needs the schema should not pay for, or\n * fail on, a connection it never uses.\n *\n * Nothing here imports `node:` anything: the runner is bundled into the\n * server's entry for every host, and a host without those modules must still\n * load it. `process` is reached lazily, inside the functions that need it.\n */\n\n/**\n * Set on `globalThis` before the server's entry is imported, by whatever runs\n * a command. The entry would otherwise call register() the moment it loads, as\n * a server does at startup, which a command has not asked for.\n */\nexport const COMMAND_MODE = Symbol.for('rsc-kit.command')\n\n/** What a command receives beside its arguments. */\nexport interface CommandContext {\n /** Aborted by SIGTERM or SIGINT: a long-running command stops when it is. */\n signal: AbortSignal\n /**\n * When the runner stops waiting for the command, as a time in milliseconds\n * (`Date.now()`'s), once it has been told to stop; undefined until then.\n * A worker finishing its job reads `deadline - Date.now()` rather than\n * RSC_SHUTDOWN_TIMEOUT and its default.\n *\n * A getter, because what it answers changes: read `context.deadline` when\n * you need it. `({ deadline }) => ...` reads it once, as the command\n * starts, when it is always undefined, and keeps that.\n */\n readonly deadline: number | undefined\n}\n\n/** A command's default export. */\nexport type CommandFunction = (args: string[], context: CommandContext) => number | void | Promise<number | void>\n\n/**\n * Types a command's default export, so its arguments and context are known\n * without annotating them: `export default defineCommand(async (args, context) => {})`.\n * It returns what it is given.\n */\nexport function defineCommand(command: CommandFunction): CommandFunction {\n return command\n}\n\n/** Resolves after the event loop has taken a turn, which is when it hands out the signals that arrived while it was busy. */\nconst nextTurn = () => new Promise<void>((resolve) => (typeof setImmediate === 'function' ? setImmediate(resolve) : setTimeout(resolve, 0)))\n\n/**\n * The entry that loads the app owns the process's SIGTERM and SIGINT, and\n * leaves this on `globalThis` for the runner.\n *\n * Loading can take a while, and a signal before the runner exists finds only\n * the default action, which ends the process with 143. So the entry holds\n * them, and the runner is handed over to: the count of those that came first,\n * and every later one. The entry's listener is never taken off. A signal is\n * delivered on the event loop's next turn, not when it arrives, and a listener\n * removed in between has the signal taken from it without anyone getting it.\n */\nexport const EARLY_SIGNALS = Symbol.for('rsc-kit.command.signals')\n\ninterface EarlySignals {\n /** Stops that arrived before there was a runner to give them to. */\n count: number\n /** From now on, the entry gives each signal to this, and stops holding the process to its own timeout. */\n handoff: (listener: (() => void) | undefined) => void\n}\n\n/** What the build knows of one command file: how to load it, and a line to list it by. */\nexport interface CommandEntry {\n load: () => Promise<{ default?: unknown; register?: unknown }>\n description?: string\n}\n\nexport interface RunCommandOptions {\n commands: Record<string, CommandEntry>\n /** instrumentation.ts's register(), once. Awaited only for a command that exports `register = true`. */\n ready: () => Promise<unknown>\n /** instrumentation.ts's shutdown(), called after a command that was given `register()`. */\n shutdown?: () => unknown\n /** How the usage line names this program: `./app`, `node .output/server/commands.mjs`. */\n program?: string\n out?: (text: string) => void\n err?: (text: string) => void\n /** SIGTERM and SIGINT. The process, unless a test brings its own. */\n signals?: {\n on: (signal: 'SIGTERM' | 'SIGINT', listener: () => void) => unknown\n off: (signal: 'SIGTERM' | 'SIGINT', listener: () => void) => unknown\n }\n /** Milliseconds a command gets to stop once told to, and shutdown() after it. RSC_SHUTDOWN_TIMEOUT seconds (10) by default. */\n limit?: number\n}\n\n/** Whether this process was started to run a command rather than to serve. */\nexport function inCommandMode(): boolean {\n return Boolean((globalThis as Record<symbol, unknown>)[COMMAND_MODE])\n}\n\n/** The list `--help` prints, and what an unknown name is answered with. */\nexport function commandHelp(commands: Record<string, { description?: string }>, program = 'app'): string {\n const names = Object.keys(commands).sort()\n const width = Math.max(0, ...names.map((name) => name.length))\n const rows = names.map((name) => {\n const description = commands[name]?.description\n\n return description ? ` ${name.padEnd(width)} ${description}` : ` ${name}`\n })\n\n return (\n `Usage: ${program} <command> [args]\\n\\n` +\n (rows.length ? `Commands:\\n${rows.join('\\n')}\\n` : 'There are no commands: add a file to src/commands.\\n')\n )\n}\n\n/**\n * An exit code from what a command returned. Nothing is success; a number is\n * the code. Anything else is the command's mistake, and said so, because the\n * alternative is a process that exits 0 after returning a string.\n */\nfunction exitCodeOf(result: unknown, name: string): number {\n if (result === undefined) return 0\n\n if (typeof result === 'number' && Number.isInteger(result) && result >= 0 && result <= 255) return result\n\n throw new TypeError(\n `the command \"${name}\" returned ${JSON.stringify(result)}. A command returns an exit code from 0 to 255, or nothing.`,\n )\n}\n\nfunction unref(timer: unknown): void {\n const handle = timer as { unref?: () => void } | undefined\n\n if (handle && typeof handle.unref === 'function') handle.unref()\n}\n\n/** The seconds a command and its shutdown() get after a signal, in milliseconds. */\nfunction defaultLimit(): number {\n const seconds = Number(typeof process !== 'undefined' ? process.env.RSC_SHUTDOWN_TIMEOUT : undefined)\n\n return (Number.isFinite(seconds) && seconds > 0 ? seconds : 10) * 1000\n}\n\n/**\n * Run the command `argv` names and say how it ended.\n *\n * Resolves to the exit code and leaves exiting to the caller, so a test sees\n * the code and an entry decides when the process stops. 0 is success and 1 is\n * a command that threw or would not stop; 2 is a name that is not a command,\n * as it is for a tool that was misused.\n */\nexport async function runCommand(argv: readonly string[], options: RunCommandOptions): Promise<number> {\n const out = options.out ?? ((text: string) => void process.stdout.write(text))\n const err = options.err ?? ((text: string) => void process.stderr.write(text))\n const [name, ...args] = argv\n\n if (name === '--help' || name === '-h') {\n out(commandHelp(options.commands, options.program))\n\n return 0\n }\n\n if (name === undefined) {\n err(commandHelp(options.commands, options.program))\n\n return 2\n }\n\n const command = Object.hasOwn(options.commands, name) ? options.commands[name] : undefined\n\n if (!command) {\n err(`Not a command: ${name}\\n\\n${commandHelp(options.commands, options.program)}`)\n\n return 2\n }\n\n const limit = options.limit ?? defaultLimit()\n const signals = options.signals ?? (typeof process !== 'undefined' ? process : undefined)\n const controller = new AbortController()\n\n let registered = false\n let stop: ((code: number) => void) | undefined\n let stopTimer: unknown\n let deadline: number | undefined\n let signalled = 0\n const context: CommandContext = {\n signal: controller.signal,\n get deadline() {\n return deadline\n },\n }\n\n // The first signal asks the command to stop and gives it `limit` to do so,\n // as the server gives in-flight requests theirs. The second is a person who\n // meant it, and nothing waits.\n const onSignal = () => {\n signalled += 1\n\n if (signalled === 1) {\n deadline = Date.now() + limit\n controller.abort()\n\n stopTimer = setTimeout(() => {\n err(`[rsc-kit] the command \"${name}\" did not stop within ${limit / 1000} seconds.\\n`)\n stop?.(1)\n }, limit)\n\n unref(stopTimer)\n\n return\n }\n\n stop?.(1)\n }\n\n const stopped = new Promise<number>((resolve) => {\n stop = resolve\n })\n\n // Behind an entry that loaded the app, the process's signals are the\n // entry's: it hands each one over, and what came while the app was loading\n // is counted here. Told to stop while loading is told to stop.\n const early = (globalThis as Record<symbol, EarlySignals | undefined>)[EARLY_SIGNALS]\n\n if (early) {\n early.handoff(onSignal)\n\n for (let caught = 0; caught < early.count; caught++) onSignal()\n } else {\n signals?.on('SIGTERM', onSignal)\n signals?.on('SIGINT', onSignal)\n }\n\n // A command that is only waiting - for its signal, for a message that has\n // not come - holds nothing open, and Node answers an event loop with nothing\n // in it by exiting 13 with a warning about an unsettled await, where Bun\n // simply waits. A command that is running is running until it returns.\n const alive = setInterval(() => {}, 2 ** 30)\n\n const ran = (async (): Promise<number> => {\n try {\n const module = await command.load()\n\n if (typeof module.default !== 'function') {\n throw new TypeError(`src/commands/${name} has no default export. Export a function: export default async (args) => {}`)\n }\n\n // Opted in, and only then: a migration that needs the schema should not\n // fail because the queue it never touches is not up.\n if (module.register === true) {\n await options.ready()\n registered = true\n }\n\n // A stop that arrived while the loop was busy with a synchronous load has\n // not been delivered: a signal is delivered on the loop's next turn. One\n // turn here, so that the command is told before it starts rather than a\n // moment after - the same on Node, on Bun and in a binary.\n await nextTurn()\n\n return exitCodeOf(await (module.default as (...a: unknown[]) => unknown)(args, context), name)\n } catch (error) {\n err(`[rsc-kit] the command \"${name}\" failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}\\n`)\n\n return 1\n }\n })()\n\n let code: number\n\n try {\n code = await Promise.race([ran, stopped])\n } finally {\n clearInterval(alive)\n clearTimeout(stopTimer as Parameters<typeof clearTimeout>[0])\n\n if (early) early.handoff(undefined)\n else {\n signals?.off('SIGTERM', onSignal)\n signals?.off('SIGINT', onSignal)\n }\n }\n\n // What register() opened is closed here, bounded like the server's: a\n // close that hangs must not hold a release step open.\n if (registered && options.shutdown) {\n let timer: unknown\n\n await Promise.race([\n Promise.resolve()\n .then(() => options.shutdown?.())\n .catch((error) => err(`[rsc-kit] instrumentation.ts shutdown() failed: ${error instanceof Error ? error.message : String(error)}\\n`)),\n new Promise((resolve) => {\n timer = setTimeout(resolve, limit)\n unref(timer)\n }),\n ])\n\n clearTimeout(timer as Parameters<typeof clearTimeout>[0])\n }\n\n return code\n}\n"]}
1
+ {"version":3,"file":"commands.js","sourceRoot":"","sources":["../src/commands.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH;;;;GAIG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAA;AAsBzD;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,OAAwB;IACpD,OAAO,OAAO,CAAA;AAChB,CAAC;AAED,6HAA6H;AAC7H,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,IAAI,OAAO,CAAO,CAAC,OAAO,EAA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I,CACR,OAAO,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,KAAK,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAClI,CAAA;QACD,OAAO,GAAG,OAAO,YAAY,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAA;IAChE,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,aAAa,CAAC,CAAA;AAClC,CAAC","sourcesContent":["/**\n * App commands: the files in `src/commands`, run as `./app <name>`.\n *\n * A compiled app is one binary that starts a server, and a release step or a\n * queue worker is the same code started differently - `./app migrate`,\n * `./app work`. The same entry also runs from a plain build, as\n * `node .output/server/commands.mjs <name>`, so nothing about a command\n * depends on Bun, on a platform, or on the binary.\n *\n * Each command is a file with a default export, `(args, context) => number\n * | void`, where `context` is `{ signal, deadline }`. It shares the build's code and dependencies, so the database\n * package and the logger the pages use are the ones it uses, in the same\n * bundle. It is loaded only when it is named: the server never evaluates one.\n *\n * `register()` from instrumentation.ts is skipped unless the command says\n * `export const register = true`. Importing instrumentation.ts is not\n * skipped - a bad environment fails there, at import, for a command as for a\n * server - but a command that only needs the schema should not pay for, or\n * fail on, a connection it never uses.\n *\n * Nothing here imports `node:` anything: the runner is bundled into the\n * server's entry for every host, and a host without those modules must still\n * load it. `process` is reached lazily, inside the functions that need it.\n */\n\n/**\n * Set on `globalThis` before the server's entry is imported, by whatever runs\n * a command. The entry would otherwise call register() the moment it loads, as\n * a server does at startup, which a command has not asked for.\n */\nexport const COMMAND_MODE = Symbol.for('rsc-kit.command')\n\n/** What a command receives beside its arguments. */\nexport interface CommandContext {\n /** Aborted by SIGTERM or SIGINT: a long-running command stops when it is. */\n signal: AbortSignal\n /**\n * When the runner stops waiting for the command, as a time in milliseconds\n * (`Date.now()`'s), once it has been told to stop; undefined until then.\n * A worker finishing its job reads `deadline - Date.now()` rather than\n * RSC_SHUTDOWN_TIMEOUT and its default.\n *\n * A getter, because what it answers changes: read `context.deadline` when\n * you need it. `({ deadline }) => ...` reads it once, as the command\n * starts, when it is always undefined, and keeps that.\n */\n readonly deadline: number | undefined\n}\n\n/** A command's default export. */\nexport type CommandFunction = (args: string[], context: CommandContext) => number | void | Promise<number | void>\n\n/**\n * Types a command's default export, so its arguments and context are known\n * without annotating them: `export default defineCommand(async (args, context) => {})`.\n * It returns what it is given.\n */\nexport function defineCommand(command: CommandFunction): CommandFunction {\n return command\n}\n\n/** Resolves after the event loop has taken a turn, which is when it hands out the signals that arrived while it was busy. */\nconst nextTurn = () => new Promise<void>((resolve) => (typeof setImmediate === 'function' ? setImmediate(resolve) : setTimeout(resolve, 0)))\n\n/**\n * The entry that loads the app owns the process's SIGTERM and SIGINT, and\n * leaves this on `globalThis` for the runner.\n *\n * Loading can take a while, and a signal before the runner exists finds only\n * the default action, which ends the process with 143. So the entry holds\n * them, and the runner is handed over to: the count of those that came first,\n * and every later one. The entry's listener is never taken off. A signal is\n * delivered on the event loop's next turn, not when it arrives, and a listener\n * removed in between has the signal taken from it without anyone getting it.\n */\nexport const EARLY_SIGNALS = Symbol.for('rsc-kit.command.signals')\n\ninterface EarlySignals {\n /** Stops that arrived before there was a runner to give them to. */\n count: number\n /** From now on, the entry gives each signal to this, and stops holding the process to its own timeout. */\n handoff: (listener: (() => void) | undefined) => void\n}\n\n/** What the build knows of one command file: how to load it, and a line to list it by. */\nexport interface CommandEntry {\n load: () => Promise<{ default?: unknown; register?: unknown }>\n description?: string\n}\n\nexport interface RunCommandOptions {\n commands: Record<string, CommandEntry>\n /** instrumentation.ts's register(), once. Awaited only for a command that exports `register = true`. */\n ready: () => Promise<unknown>\n /** instrumentation.ts's shutdown(), called after a command that was given `register()`. */\n shutdown?: () => unknown\n /** How the usage line names this program: `./app`, `node .output/server/commands.mjs`. */\n program?: string\n out?: (text: string) => void\n err?: (text: string) => void\n /** SIGTERM and SIGINT. The process, unless a test brings its own. */\n signals?: {\n on: (signal: 'SIGTERM' | 'SIGINT', listener: () => void) => unknown\n off: (signal: 'SIGTERM' | 'SIGINT', listener: () => void) => unknown\n }\n /** Milliseconds a command gets to stop once told to, and shutdown() after it. RSC_SHUTDOWN_TIMEOUT seconds (10) by default. */\n limit?: number\n}\n\n/** Whether this process was started to run a command rather than to serve. */\nexport function inCommandMode(): boolean {\n return Boolean((globalThis as Record<symbol, unknown>)[COMMAND_MODE])\n}\n\n/** The list `--help` prints, and what an unknown name is answered with. */\nexport function commandHelp(commands: Record<string, { description?: string }>, program = 'app'): string {\n const names = Object.keys(commands).sort()\n const width = Math.max(0, ...names.map((name) => name.length))\n const rows = names.map((name) => {\n const description = commands[name]?.description\n\n return description ? ` ${name.padEnd(width)} ${description}` : ` ${name}`\n })\n\n return (\n `Usage: ${program} <command> [args]\\n\\n` +\n (rows.length ? `Commands:\\n${rows.join('\\n')}\\n` : 'There are no commands: add a file to src/commands.\\n')\n )\n}\n\n/**\n * An exit code from what a command returned. Nothing is success; a number is\n * the code. Anything else is the command's mistake, and said so, because the\n * alternative is a process that exits 0 after returning a string.\n */\nfunction exitCodeOf(result: unknown, name: string): number {\n if (result === undefined) return 0\n\n if (typeof result === 'number' && Number.isInteger(result) && result >= 0 && result <= 255) return result\n\n throw new TypeError(\n `the command \"${name}\" returned ${JSON.stringify(result)}. A command returns an exit code from 0 to 255, or nothing.`,\n )\n}\n\nfunction unref(timer: unknown): void {\n const handle = timer as { unref?: () => void } | undefined\n\n if (handle && typeof handle.unref === 'function') handle.unref()\n}\n\n/** The seconds a command and its shutdown() get after a signal, in milliseconds. */\nfunction defaultLimit(): number {\n const seconds = Number(typeof process !== 'undefined' ? process.env.RSC_SHUTDOWN_TIMEOUT : undefined)\n\n return (Number.isFinite(seconds) && seconds > 0 ? seconds : 10) * 1000\n}\n\n/**\n * Run the command `argv` names and say how it ended.\n *\n * Resolves to the exit code and leaves exiting to the caller, so a test sees\n * the code and an entry decides when the process stops. 0 is success and 1 is\n * a command that threw or would not stop; 2 is a name that is not a command,\n * as it is for a tool that was misused.\n */\nexport async function runCommand(argv: readonly string[], options: RunCommandOptions): Promise<number> {\n const out = options.out ?? ((text: string) => void process.stdout.write(text))\n const err = options.err ?? ((text: string) => void process.stderr.write(text))\n const [name, ...args] = argv\n\n if (name === '--help' || name === '-h') {\n out(commandHelp(options.commands, options.program))\n\n return 0\n }\n\n if (name === undefined) {\n err(commandHelp(options.commands, options.program))\n\n return 2\n }\n\n const command = Object.hasOwn(options.commands, name) ? options.commands[name] : undefined\n\n if (!command) {\n err(`Not a command: ${name}\\n\\n${commandHelp(options.commands, options.program)}`)\n\n return 2\n }\n\n const limit = options.limit ?? defaultLimit()\n const signals = options.signals ?? (typeof process !== 'undefined' ? process : undefined)\n const controller = new AbortController()\n\n let registered = false\n let stop: ((code: number) => void) | undefined\n let stopTimer: unknown\n let deadline: number | undefined\n let signalled = 0\n const context: CommandContext = {\n signal: controller.signal,\n get deadline() {\n return deadline\n },\n }\n\n // The first signal asks the command to stop and gives it `limit` to do so,\n // as the server gives in-flight requests theirs. The second is a person who\n // meant it, and nothing waits.\n const onSignal = () => {\n signalled += 1\n\n if (signalled === 1) {\n deadline = Date.now() + limit\n controller.abort()\n\n stopTimer = setTimeout(() => {\n err(`[rsc-kit] the command \"${name}\" did not stop within ${limit / 1000} seconds.\\n`)\n stop?.(1)\n }, limit)\n\n unref(stopTimer)\n\n return\n }\n\n stop?.(1)\n }\n\n const stopped = new Promise<number>((resolve) => {\n stop = resolve\n })\n\n // Behind an entry that loaded the app, the process's signals are the\n // entry's: it hands each one over, and what came while the app was loading\n // is counted here. Told to stop while loading is told to stop.\n const early = (globalThis as Record<symbol, EarlySignals | undefined>)[EARLY_SIGNALS]\n\n if (early) {\n early.handoff(onSignal)\n\n for (let caught = 0; caught < early.count; caught++) onSignal()\n } else {\n signals?.on('SIGTERM', onSignal)\n signals?.on('SIGINT', onSignal)\n }\n\n // A command that is only waiting - for its signal, for a message that has\n // not come - holds nothing open, and Node answers an event loop with nothing\n // in it by exiting 13 with a warning about an unsettled await, where Bun\n // simply waits. A command that is running is running until it returns.\n const alive = setInterval(() => {}, 2 ** 30)\n\n const ran = (async (): Promise<number> => {\n try {\n const module = await command.load()\n\n if (typeof module.default !== 'function') {\n throw new TypeError(`src/commands/${name} has no default export. Export a function: export default async (args) => {}`)\n }\n\n // Opted in, and only then: a migration that needs the schema should not\n // fail because the queue it never touches is not up.\n if (module.register === true) {\n await options.ready()\n registered = true\n }\n\n // A stop that arrived while the loop was busy with a synchronous load has\n // not been delivered: a signal is delivered on the loop's next turn. One\n // turn here, so that the command is told before it starts rather than a\n // moment after - the same on Node, on Bun and in a binary.\n await nextTurn()\n\n return exitCodeOf(await (module.default as (...a: unknown[]) => unknown)(args, context), name)\n } catch (error) {\n err(`[rsc-kit] the command \"${name}\" failed: ${describeError(error, true)}\\n`)\n\n return 1\n }\n })()\n\n let code: number\n\n try {\n code = await Promise.race([ran, stopped])\n } finally {\n clearInterval(alive)\n clearTimeout(stopTimer as Parameters<typeof clearTimeout>[0])\n\n if (early) early.handoff(undefined)\n else {\n signals?.off('SIGTERM', onSignal)\n signals?.off('SIGINT', onSignal)\n }\n }\n\n // What register() opened is closed here, bounded like the server's: a\n // close that hangs must not hold a release step open.\n if (registered && options.shutdown) {\n let timer: unknown\n\n await Promise.race([\n Promise.resolve()\n .then(() => options.shutdown?.())\n .catch((error) => err(`[rsc-kit] instrumentation.ts shutdown() failed: ${describeError(error, false)}\\n`)),\n new Promise((resolve) => {\n timer = setTimeout(resolve, limit)\n unref(timer)\n }),\n ])\n\n clearTimeout(timer as Parameters<typeof clearTimeout>[0])\n }\n\n return code\n}\n\n/**\n * An error and every cause under it, one line of `[cause]:` each.\n *\n * A library that wraps an error keeps the reason in `cause`, and a stack does\n * not print it: Drizzle's DrizzleQueryError carries the SQL as its message and\n * the database's refusal - a timeout, a wrong password - as its cause, so a\n * failed migration said what it tried and never why. A cause that is not an\n * Error is printed as it is, and a chain that loops back stops there.\n */\nfunction describeError(error: unknown, stack: boolean): string {\n const seen = new Set<unknown>()\n const parts: string[] = []\n let current: unknown = error\n\n while (current !== undefined && current !== null && !seen.has(current)) {\n seen.add(current)\n parts.push(\n current instanceof Error ? (stack ? (current.stack ?? `${current.name}: ${current.message}`) : current.message) : String(current),\n )\n current = current instanceof Error ? current.cause : undefined\n }\n\n return parts.join('\\n[cause]: ')\n}\n"]}
package/dist/vite.js CHANGED
@@ -1907,18 +1907,17 @@ async function prerenderAfterBundles(bundle, staticDir, assetsDir, knownActions
1907
1907
  console.log(" React's cache() dedupes only inside a component render; in a guard, an action or\n" +
1908
1908
  " an api route it calls straight through. Import it from @rsc-kit/core/cache instead.");
1909
1909
  }
1910
- // Server files importing a client library. Legal - a server component may
1911
- // render a client component from a package - but the shape that costs an
1912
- // afternoon is a file with no "use client" that only wraps them, so the
1913
- // library's internals run on the server. Said, with the packages and the
1914
- // importer, so the person reading can tell which it is.
1910
+ // Server files whose code, or a library's under them, reaches a hook on the
1911
+ // server (clientImports.ts). The render that calls one fails naming React,
1912
+ // not the file; this names the file, the package and the hook.
1915
1913
  if (clientLibraryImports.length > 0) {
1916
- console.log(`\n \u2139 ${clientLibraryImports.length} server ${clientLibraryImports.length === 1 ? "file imports" : "files import"} a client library: ` +
1914
+ console.log(`\n \u2139 ${clientLibraryImports.length} server ${clientLibraryImports.length === 1 ? "file reaches" : "files reach"} client-only React: ` +
1917
1915
  clientLibraryImports
1918
- .map((c) => `${c.file} (${c.packages.join(", ")}${c.from ? `; imported by ${c.from}` : ""})`)
1916
+ .map((c) => `${c.file} (${c.packages.length > 0 ? `${c.packages.join(", ")}: ` : ""}${c.calls.join(", ")}${c.from ? `; imported by ${c.from}` : ""})`)
1919
1917
  .join("; "));
1920
- console.log(' Legal for a server component. A file that only wraps client components wants "use client" -\n' +
1921
- " as shadcn ships it - so the server stops at the boundary.");
1918
+ console.log(' The server has none of these, so a render that calls one fails with "... is not a function".\n' +
1919
+ ' A file that only wraps client components wants "use client" - as shadcn ships it. A library\n' +
1920
+ " export holding a hook the page never renders is fine.");
1922
1921
  }
1923
1922
  // Written from the rows that were just printed rather than recomputed: the
1924
1923
  // report and the terminal must not be able to disagree about what happened.
@@ -7128,6 +7127,7 @@ function clientImportsAudit() {
7128
7127
  moduleIds: () => this.getModuleIds(),
7129
7128
  importedIds: (id) => this.getModuleInfo(id)?.importedIds ?? [],
7130
7129
  importers: (id) => this.getModuleInfo(id)?.importers ?? [],
7130
+ code: (id) => this.getModuleInfo(id)?.code ?? null,
7131
7131
  }, {
7132
7132
  sourceDir,
7133
7133
  clientPackages,