@rsc-kit/core 0.39.0 → 0.41.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/typegen.js CHANGED
@@ -12,7 +12,7 @@
12
12
  // builds with. Only the plugin's config step runs, which is what writes them.
13
13
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
14
14
  import { createRequire } from "node:module";
15
- import { basename, join, relative } from "node:path";
15
+ import { join, relative } from "node:path";
16
16
  import { cwd, exit, stderr, stdout } from "node:process";
17
17
  import { pathToFileURL } from "node:url";
18
18
  async function flatten(option) {
@@ -123,7 +123,7 @@ export async function appInfo(root = cwd()) {
123
123
  }
124
124
  /** A form's name from its action's: contactSend is contact-send. */
125
125
  function formName(action) {
126
- return action.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
126
+ return action.replace(/\./g, "-").replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
127
127
  }
128
128
  /**
129
129
  * Write `<sourceDir>/forms/<name>.ts`: a public form drawn from a backend
@@ -141,36 +141,56 @@ export async function makeForm(root, action, options = {}) {
141
141
  const plugin = (await flatten(loaded?.config.plugins ?? [])).find((p) => p.name === "rsc-kit");
142
142
  const files = plugin?.api?.generatedFiles?.() ?? [];
143
143
  const manifestFile = files.find((f) => f.endsWith("rsc-host.json"));
144
- const actionsFile = files.find((f) => f.endsWith("server-actions.generated.ts"));
145
- if (!manifestFile || !actionsFile || !existsSync(manifestFile)) {
144
+ if (!manifestFile || !existsSync(manifestFile)) {
146
145
  throw new Error("No rsc-host.json: this app has no backend that describes its actions (rscKit({ hostManifest }) or a Go registry).");
147
146
  }
148
147
  const manifest = JSON.parse(readFileSync(manifestFile, "utf-8"));
149
- const actions = manifest.actions ?? {};
150
- const target = actions[action];
151
- if (!target) {
152
- const known = Object.keys(actions);
148
+ // Named as rpc() names it - Contact.send - and found in whichever module
149
+ // the backend put it.
150
+ const all = Object.entries(manifest.actions ?? {}).flatMap(([module, exports]) => Object.entries(exports).map(([name, target]) => ({ module, name, target })));
151
+ const found = all.find((a) => a.target === action);
152
+ const target = found?.target;
153
+ if (!found || !target) {
154
+ const known = all.map((a) => a.target);
153
155
  throw new Error(`The backend has no action named ${action}.` +
154
156
  (known.length ? ` It has: ${known.join(", ")}.` : " It has none: a form posts to an action, which is a class in app/Rsc/Actions in Laravel, or reg.HandleAction in Go."));
155
157
  }
156
158
  const name = options.name ?? formName(action).replace(/-(send|submit|store|create)$/, "");
159
+ const from = "../server-actions/" + found.module;
157
160
  if (!/^[a-z0-9-]+$/.test(name))
158
161
  throw new Error(`A form's name is lowercase letters, digits and dashes: ${name}`);
159
- const sourceDir = join(actionsFile, "..");
162
+ const sourceDir = plugin?.api?.sourceDir?.() ?? join(root, "src");
160
163
  const file = join(sourceDir, "forms", name + ".ts");
161
164
  if (existsSync(file) && !options.force)
162
165
  throw new Error(`${relative(root, file)} is already there. Pass --force to write over it.`);
163
166
  const exported = name.replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase());
167
+ // The action under its own name - send - unless that is the form's, or a
168
+ // word JavaScript keeps (delete): then send + Action. A default is named
169
+ // after its module.
170
+ const own = found.name === "default" ? found.module.split("/").pop().replace(/-([a-z0-9])/g, (_, c) => c.toUpperCase()) : found.name;
171
+ const usable = (id) => {
172
+ try {
173
+ new Function(`let ${id}`);
174
+ return id !== exported;
175
+ }
176
+ catch {
177
+ return false;
178
+ }
179
+ };
180
+ const reference = usable(own) ? own : own + "Action";
181
+ const imported = found.name === "default"
182
+ ? `import ${reference} from '${from}'`
183
+ : `import { ${reference === found.name ? reference : `${found.name} as ${reference}`} } from '${from}'`;
164
184
  const text = `import { defineBlueprint } from '@rsc-kit/press/forms'
165
185
  import { shadcn } from '@rsc-kit/press/shadcn'
166
- import { ${action} } from '../${basename(actionsFile, ".ts")}'
186
+ ${imported}
167
187
 
168
188
  // The fields and every check are ${target}'s: the backend says what it takes,
169
189
  // and its refusals land under the fields. Place it in any page: <${exported}.Form />.
170
190
  // Add actions.update to edit a record with it too: <${exported}.Form id={...} values={...} />.
171
191
  export const ${exported} = defineBlueprint({
172
192
  name: '${name}',
173
- actions: { create: ${action} },
193
+ actions: { create: ${reference} },
174
194
  theme: shadcn,
175
195
  })
176
196
  `;
@@ -1 +1 @@
1
- {"version":3,"file":"typegen.js","sourceRoot":"","sources":["../src/typegen.ts"],"names":[],"mappings":";AACA,gEAAgE;AAChE,EAAE;AACF,0EAA0E;AAC1E,6EAA6E;AAC7E,0EAA0E;AAC1E,sEAAsE;AACtE,2EAA2E;AAC3E,EAAE;AACF,0EAA0E;AAC1E,8EAA8E;AAC9E,8EAA8E;AAE9E,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AACrD,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAQzC,KAAK,UAAU,OAAO,CAAC,MAAe;IACpC,MAAM,KAAK,GAAG,MAAM,MAAM,CAAC;IAE3B,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,CAAC,MAAM,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAEhF,OAAO,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAmB,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AACzE,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAAC,IAAI,GAAG,GAAG,EAAE,EAAE,KAAK,GAAG,KAAK;IACvD,MAAM,K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AE,SAAS,EAAE,GAAG,MAAM,MAAM,CAAC,SAAS,CAAC,CAAC;IAE9C,SAAS,CAAC,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IACzD,aAAa,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAE1B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["#!/usr/bin/env node\n// rsc-kit-typegen: write the route types without starting Vite.\n//\n// The types - every url the app has, for <Link href> and redirect() - are\n// written when the dev server or a build starts, and again when a dev server\n// sees a route added. A typecheck run with neither, by an agent or in CI,\n// read the types from the last start: a route added since failed with\n// '\"/admin\"' is not assignable to type Route until something started Vite.\n//\n// The app's own vite.config is loaded, through the app's own Vite, so the\n// plugin's options - sourceDir, outDir, a host's route file - are the ones it\n// builds with. Only the plugin's config step runs, which is what writes them.\n\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { basename, join, relative } from \"node:path\";\nimport { cwd, exit, stderr, stdout } from \"node:process\";\nimport { pathToFileURL } from \"node:url\";\n\ninterface PluginLike {\n name?: string;\n config?: (config: object, env: { command: string; mode: string }) => unknown;\n api?: { generatedFiles?: () => string[]; info?: () => Record<string, unknown> };\n}\n\nasync function flatten(option: unknown): Promise<PluginLike[]> {\n const value = await option;\n\n if (Array.isArray(value)) return (await Promise.all(value.map(flatten))).flat();\n\n return value && typeof value === \"object\" ? [value as PluginLike] : [];\n}\n\n/**\n * Write the types; or, with `check`, say which committed generated files are\n * not what the backend and the route tree produce now, and change nothing.\n *\n * For CI: `rsc-kit-typegen --check` fails when rsc-host.json or the types were\n * committed and the backend has moved on since. Only files that were already\n * there are compared - one that is not committed is written fresh by every\n * build and cannot be stale - and every one is put back as it was.\n */\nexport async function typegen(root = cwd(), check = false): Promise<string[]> {\n const local = createRequire(join(root, \"package.json\"));\n let vitePath: string;\n\n try {\n vitePath = local.resolve(\"vite\");\n } catch {\n throw new Error(\"No vite installed in \" + root + \". Run this from the app's directory.\");\n }\n\n const vite = (await import(pathToFileURL(vitePath).href)) as {\n loadConfigFromFile: (\n env: { command: string; mode: string },\n file?: string,\n root?: string,\n ) => Promise<{ config: { plugins?: unknown[] } } | null>;\n };\n\n // As a build would: a manifest command that fails is a failure, not a\n // warning, when the question is whether what is committed is current.\n const env = check ? { command: \"build\", mode: \"production\" } : { command: \"serve\", mode: \"development\" };\n const loaded = await vite.loadConfigFromFile(env, undefined, root);\n\n if (!loaded) throw new Error(\"No vite.config found in \" + root + \".\");\n\n const plugin = (await flatten(loaded.config.plugins ?? [])).find((p) => p.name === \"rsc-kit\");\n\n if (!plugin?.config) throw new Error(\"The vite.config in \" + root + \" does not use rscKit().\");\n\n if (!check) {\n await plugin.config({}, env);\n\n return [];\n }\n\n const files = plugin.api?.generatedFiles?.() ?? [];\n const before = new Map(files.filter((f) => existsSync(f)).map((f) => [f, readFileSync(f, \"utf-8\")]));\n\n try {\n await plugin.config({}, env);\n\n return [...before].filter(([f, text]) => !existsSync(f) || readFileSync(f, \"utf-8\") !== text).map(([f]) => f);\n } finally {\n for (const [f, text] of before) writeFileSync(f, text);\n }\n}\n\n// Run as a command, not when imported.\nif (import.meta.url === pathToFileURL(process.argv[1] ?? \"\").href || process.argv[1]?.endsWith(\"rsc-kit-typegen\")) {\n const check = process.argv.includes(\"--check\");\n\n typegen(cwd(), check)\n .then((stale) => {\n if (!check) {\n stdout.write(\"rsc-kit: route types written\\n\");\n\n return;\n }\n\n if (stale.length === 0) {\n stdout.write(\"rsc-kit: generated files are current\\n\");\n\n return;\n }\n\n stderr.write(\n \"rsc-kit-typegen --check: these are committed and no longer what the backend and the routes produce:\\n\" +\n stale.map((f) => \" \" + relative(cwd(), f)).join(\"\\n\") +\n \"\\nRun rsc-kit-typegen and commit the result.\\n\",\n );\n exit(1);\n })\n .catch((error: unknown) => {\n stderr.write(\"rsc-kit-typegen: \" + (error instanceof Error ? error.message : String(error)) + \"\\n\");\n exit(1);\n });\n}\n\n/**\n * What a build of the app in `root` will produce - `{ output: \"server\", ... }`\n * or `{ output: \"export\", dir }` - read before building, from the app's own\n * Vite config, evaluated the way a build evaluates it. A value computed in\n * the config, or RSC_OUTPUT in the environment, resolves exactly as the build\n * resolves it, because it is the same code deciding.\n */\nexport async function appInfo(root = cwd()): Promise<Record<string, unknown>> {\n const local = createRequire(join(root, \"package.json\"));\n let vitePath: string;\n\n try {\n vitePath = local.resolve(\"vite\");\n } catch {\n throw new Error(\"No vite installed in \" + root + \". Run this from the app's directory.\");\n }\n\n const vite = (await import(pathToFileURL(vitePath).href)) as {\n loadConfigFromFile: (\n env: { command: string; mode: string },\n file?: string,\n root?: string,\n ) => Promise<{ config: { plugins?: unknown[] } } | null>;\n };\n // From inside the app, as a build runs: rscKit() takes its project root\n // from the working directory when the config creates it.\n const from = cwd();\n\n process.chdir(root);\n\n try {\n const loaded = await vite.loadConfigFromFile({ command: \"build\", mode: \"production\" }, undefined, root);\n\n if (!loaded) throw new Error(\"No vite.config found in \" + root + \".\");\n\n const plugin = (await flatten(loaded.config.plugins ?? [])).find((p) => p.name === \"rsc-kit\");\n\n if (!plugin?.api?.info) throw new Error(\"The vite.config in \" + root + \" does not use rscKit().\");\n\n return plugin.api.info();\n } finally {\n process.chdir(from);\n }\n}\n\n\n/** A form's name from its action's: contactSend is contact-send. */\nfunction formName(action: string): string {\n return action.replace(/([a-z0-9])([A-Z])/g, \"$1-$2\").toLowerCase();\n}\n\n/**\n * Write `<sourceDir>/forms/<name>.ts`: a public form drawn from a backend\n * action, the way the docs write it by hand. The backend is asked first, as a\n * dev server start asks it, so an action added a moment ago is there.\n *\n * The file is the app's to edit afterwards - a theme, labels, `done` - and is\n * never overwritten unless `force` says so.\n */\nexport async function makeForm(\n root: string,\n action: string,\n options: { name?: string; force?: boolean } = {},\n): Promise<string> {\n await typegen(root);\n\n const local = createRequire(join(root, \"package.json\"));\n const vite = (await import(pathToFileURL(local.resolve(\"vite\")).href)) as {\n loadConfigFromFile: (env: { command: string; mode: string }, file?: string, root?: string) => Promise<{ config: { plugins?: unknown[] } } | null>;\n };\n const loaded = await vite.loadConfigFromFile({ command: \"serve\", mode: \"development\" }, undefined, root);\n const plugin = (await flatten(loaded?.config.plugins ?? [])).find((p) => p.name === \"rsc-kit\");\n const files = plugin?.api?.generatedFiles?.() ?? [];\n const manifestFile = files.find((f) => f.endsWith(\"rsc-host.json\"));\n const actionsFile = files.find((f) => f.endsWith(\"server-actions.generated.ts\"));\n\n if (!manifestFile || !actionsFile || !existsSync(manifestFile)) {\n throw new Error(\"No rsc-host.json: this app has no backend that describes its actions (rscKit({ hostManifest }) or a Go registry).\");\n }\n\n const manifest = JSON.parse(readFileSync(manifestFile, \"utf-8\")) as {\n actions?: Record<string, string>;\n types?: Record<string, { params?: unknown[] }>;\n };\n const actions = manifest.actions ?? {};\n const target = actions[action];\n\n if (!target) {\n const known = Object.keys(actions);\n\n throw new Error(\n `The backend has no action named ${action}.` +\n (known.length ? ` It has: ${known.join(\", \")}.` : \" It has none: a form posts to an action, which is a class in app/Rsc/Actions in Laravel, or reg.HandleAction in Go.\"),\n );\n }\n\n const name = options.name ?? formName(action).replace(/-(send|submit|store|create)$/, \"\");\n\n if (!/^[a-z0-9-]+$/.test(name)) throw new Error(`A form's name is lowercase letters, digits and dashes: ${name}`);\n\n const sourceDir = join(actionsFile, \"..\");\n const file = join(sourceDir, \"forms\", name + \".ts\");\n\n if (existsSync(file) && !options.force) throw new Error(`${relative(root, file)} is already there. Pass --force to write over it.`);\n\n const exported = name.replace(/-([a-z0-9])/g, (_, c: string) => c.toUpperCase());\n const text = `import { defineBlueprint } from '@rsc-kit/press/forms'\nimport { shadcn } from '@rsc-kit/press/shadcn'\nimport { ${action} } from '../${basename(actionsFile, \".ts\")}'\n\n// The fields and every check are ${target}'s: the backend says what it takes,\n// and its refusals land under the fields. Place it in any page: <${exported}.Form />.\n// Add actions.update to edit a record with it too: <${exported}.Form id={...} values={...} />.\nexport const ${exported} = defineBlueprint({\n name: '${name}',\n actions: { create: ${action} },\n theme: shadcn,\n})\n`;\n\n const { mkdirSync } = await import(\"node:fs\");\n\n mkdirSync(join(sourceDir, \"forms\"), { recursive: true });\n writeFileSync(file, text);\n\n return file;\n}\n"]}
1
+ {"version":3,"file":"typegen.js","sourceRoot":"","sources":["../src/typegen.ts"],"names":[],"mappings":";AACA,gEAAgE;AAChE,EAAE;AACF,0EAA0E;AAC1E,6EAA6E;AAC7E,0EAA0E;AAC1E,sEAAsE;AACtE,2EAA2E;AAC3E,EAAE;AACF,0EAA0E;AAC1E,8EAA8E;AAC9E,8EAA8E;AAE9E,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAQzC,KAAK,UAAU,OAAO,CAAC,MAAe;IACpC,MAAM,KAAK,GAAG,MAAM,MAAM,CAAC;IAE3B,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,CAAC,MAAM,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAEhF,OAAO,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAmB,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AACzE,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAAC,IAAI,GAAG,GAAG,EAAE,EAAE,KAAK,GAAG,KAAK;IACvD,MAAM,KAAK,GAAG,aAAa,C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M,IAAI,GAAG;;EAEb,QAAQ;;oCAE0B,MAAM;oEAC0B,QAAQ;uDACrB,QAAQ;eAChD,QAAQ;WACZ,IAAI;uBACQ,SAAS;;;CAG/B,CAAC;IAEA,MAAM,EAAE,SAAS,EAAE,GAAG,MAAM,MAAM,CAAC,SAAS,CAAC,CAAC;IAE9C,SAAS,CAAC,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IACzD,aAAa,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IAE1B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["#!/usr/bin/env node\n// rsc-kit-typegen: write the route types without starting Vite.\n//\n// The types - every url the app has, for <Link href> and redirect() - are\n// written when the dev server or a build starts, and again when a dev server\n// sees a route added. A typecheck run with neither, by an agent or in CI,\n// read the types from the last start: a route added since failed with\n// '\"/admin\"' is not assignable to type Route until something started Vite.\n//\n// The app's own vite.config is loaded, through the app's own Vite, so the\n// plugin's options - sourceDir, outDir, a host's route file - are the ones it\n// builds with. Only the plugin's config step runs, which is what writes them.\n\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join, relative } from \"node:path\";\nimport { cwd, exit, stderr, stdout } from \"node:process\";\nimport { pathToFileURL } from \"node:url\";\n\ninterface PluginLike {\n name?: string;\n config?: (config: object, env: { command: string; mode: string }) => unknown;\n api?: { generatedFiles?: () => string[]; info?: () => Record<string, unknown>; sourceDir?: () => string };\n}\n\nasync function flatten(option: unknown): Promise<PluginLike[]> {\n const value = await option;\n\n if (Array.isArray(value)) return (await Promise.all(value.map(flatten))).flat();\n\n return value && typeof value === \"object\" ? [value as PluginLike] : [];\n}\n\n/**\n * Write the types; or, with `check`, say which committed generated files are\n * not what the backend and the route tree produce now, and change nothing.\n *\n * For CI: `rsc-kit-typegen --check` fails when rsc-host.json or the types were\n * committed and the backend has moved on since. Only files that were already\n * there are compared - one that is not committed is written fresh by every\n * build and cannot be stale - and every one is put back as it was.\n */\nexport async function typegen(root = cwd(), check = false): Promise<string[]> {\n const local = createRequire(join(root, \"package.json\"));\n let vitePath: string;\n\n try {\n vitePath = local.resolve(\"vite\");\n } catch {\n throw new Error(\"No vite installed in \" + root + \". Run this from the app's directory.\");\n }\n\n const vite = (await import(pathToFileURL(vitePath).href)) as {\n loadConfigFromFile: (\n env: { command: string; mode: string },\n file?: string,\n root?: string,\n ) => Promise<{ config: { plugins?: unknown[] } } | null>;\n };\n\n // As a build would: a manifest command that fails is a failure, not a\n // warning, when the question is whether what is committed is current.\n const env = check ? { command: \"build\", mode: \"production\" } : { command: \"serve\", mode: \"development\" };\n const loaded = await vite.loadConfigFromFile(env, undefined, root);\n\n if (!loaded) throw new Error(\"No vite.config found in \" + root + \".\");\n\n const plugin = (await flatten(loaded.config.plugins ?? [])).find((p) => p.name === \"rsc-kit\");\n\n if (!plugin?.config) throw new Error(\"The vite.config in \" + root + \" does not use rscKit().\");\n\n if (!check) {\n await plugin.config({}, env);\n\n return [];\n }\n\n const files = plugin.api?.generatedFiles?.() ?? [];\n const before = new Map(files.filter((f) => existsSync(f)).map((f) => [f, readFileSync(f, \"utf-8\")]));\n\n try {\n await plugin.config({}, env);\n\n return [...before].filter(([f, text]) => !existsSync(f) || readFileSync(f, \"utf-8\") !== text).map(([f]) => f);\n } finally {\n for (const [f, text] of before) writeFileSync(f, text);\n }\n}\n\n// Run as a command, not when imported.\nif (import.meta.url === pathToFileURL(process.argv[1] ?? \"\").href || process.argv[1]?.endsWith(\"rsc-kit-typegen\")) {\n const check = process.argv.includes(\"--check\");\n\n typegen(cwd(), check)\n .then((stale) => {\n if (!check) {\n stdout.write(\"rsc-kit: route types written\\n\");\n\n return;\n }\n\n if (stale.length === 0) {\n stdout.write(\"rsc-kit: generated files are current\\n\");\n\n return;\n }\n\n stderr.write(\n \"rsc-kit-typegen --check: these are committed and no longer what the backend and the routes produce:\\n\" +\n stale.map((f) => \" \" + relative(cwd(), f)).join(\"\\n\") +\n \"\\nRun rsc-kit-typegen and commit the result.\\n\",\n );\n exit(1);\n })\n .catch((error: unknown) => {\n stderr.write(\"rsc-kit-typegen: \" + (error instanceof Error ? error.message : String(error)) + \"\\n\");\n exit(1);\n });\n}\n\n/**\n * What a build of the app in `root` will produce - `{ output: \"server\", ... }`\n * or `{ output: \"export\", dir }` - read before building, from the app's own\n * Vite config, evaluated the way a build evaluates it. A value computed in\n * the config, or RSC_OUTPUT in the environment, resolves exactly as the build\n * resolves it, because it is the same code deciding.\n */\nexport async function appInfo(root = cwd()): Promise<Record<string, unknown>> {\n const local = createRequire(join(root, \"package.json\"));\n let vitePath: string;\n\n try {\n vitePath = local.resolve(\"vite\");\n } catch {\n throw new Error(\"No vite installed in \" + root + \". Run this from the app's directory.\");\n }\n\n const vite = (await import(pathToFileURL(vitePath).href)) as {\n loadConfigFromFile: (\n env: { command: string; mode: string },\n file?: string,\n root?: string,\n ) => Promise<{ config: { plugins?: unknown[] } } | null>;\n };\n // From inside the app, as a build runs: rscKit() takes its project root\n // from the working directory when the config creates it.\n const from = cwd();\n\n process.chdir(root);\n\n try {\n const loaded = await vite.loadConfigFromFile({ command: \"build\", mode: \"production\" }, undefined, root);\n\n if (!loaded) throw new Error(\"No vite.config found in \" + root + \".\");\n\n const plugin = (await flatten(loaded.config.plugins ?? [])).find((p) => p.name === \"rsc-kit\");\n\n if (!plugin?.api?.info) throw new Error(\"The vite.config in \" + root + \" does not use rscKit().\");\n\n return plugin.api.info();\n } finally {\n process.chdir(from);\n }\n}\n\n\n/** A form's name from its action's: contactSend is contact-send. */\nfunction formName(action: string): string {\n return action.replace(/\\./g, \"-\").replace(/([a-z0-9])([A-Z])/g, \"$1-$2\").toLowerCase();\n}\n\n/**\n * Write `<sourceDir>/forms/<name>.ts`: a public form drawn from a backend\n * action, the way the docs write it by hand. The backend is asked first, as a\n * dev server start asks it, so an action added a moment ago is there.\n *\n * The file is the app's to edit afterwards - a theme, labels, `done` - and is\n * never overwritten unless `force` says so.\n */\nexport async function makeForm(\n root: string,\n action: string,\n options: { name?: string; force?: boolean } = {},\n): Promise<string> {\n await typegen(root);\n\n const local = createRequire(join(root, \"package.json\"));\n const vite = (await import(pathToFileURL(local.resolve(\"vite\")).href)) as {\n loadConfigFromFile: (env: { command: string; mode: string }, file?: string, root?: string) => Promise<{ config: { plugins?: unknown[] } } | null>;\n };\n const loaded = await vite.loadConfigFromFile({ command: \"serve\", mode: \"development\" }, undefined, root);\n const plugin = (await flatten(loaded?.config.plugins ?? [])).find((p) => p.name === \"rsc-kit\");\n const files = plugin?.api?.generatedFiles?.() ?? [];\n const manifestFile = files.find((f) => f.endsWith(\"rsc-host.json\"));\n\n if (!manifestFile || !existsSync(manifestFile)) {\n throw new Error(\"No rsc-host.json: this app has no backend that describes its actions (rscKit({ hostManifest }) or a Go registry).\");\n }\n\n const manifest = JSON.parse(readFileSync(manifestFile, \"utf-8\")) as {\n actions?: Record<string, Record<string, string>>;\n types?: Record<string, { params?: unknown[] }>;\n };\n // Named as rpc() names it - Contact.send - and found in whichever module\n // the backend put it.\n const all = Object.entries(manifest.actions ?? {}).flatMap(([module, exports]) =>\n Object.entries(exports).map(([name, target]) => ({ module, name, target })),\n );\n const found = all.find((a) => a.target === action);\n const target = found?.target;\n\n if (!found || !target) {\n const known = all.map((a) => a.target);\n\n throw new Error(\n `The backend has no action named ${action}.` +\n (known.length ? ` It has: ${known.join(\", \")}.` : \" It has none: a form posts to an action, which is a class in app/Rsc/Actions in Laravel, or reg.HandleAction in Go.\"),\n );\n }\n\n const name = options.name ?? formName(action).replace(/-(send|submit|store|create)$/, \"\");\n const from = \"../server-actions/\" + found.module;\n\n if (!/^[a-z0-9-]+$/.test(name)) throw new Error(`A form's name is lowercase letters, digits and dashes: ${name}`);\n\n const sourceDir = plugin?.api?.sourceDir?.() ?? join(root, \"src\");\n const file = join(sourceDir, \"forms\", name + \".ts\");\n\n if (existsSync(file) && !options.force) throw new Error(`${relative(root, file)} is already there. Pass --force to write over it.`);\n\n const exported = name.replace(/-([a-z0-9])/g, (_, c: string) => c.toUpperCase());\n // The action under its own name - send - unless that is the form's, or a\n // word JavaScript keeps (delete): then send + Action. A default is named\n // after its module.\n const own = found.name === \"default\" ? found.module.split(\"/\").pop()!.replace(/-([a-z0-9])/g, (_, c: string) => c.toUpperCase()) : found.name;\n const usable = (id: string) => {\n try {\n new Function(`let ${id}`);\n return id !== exported;\n } catch {\n return false;\n }\n };\n const reference = usable(own) ? own : own + \"Action\";\n const imported =\n found.name === \"default\"\n ? `import ${reference} from '${from}'`\n : `import { ${reference === found.name ? reference : `${found.name} as ${reference}`} } from '${from}'`;\n const text = `import { defineBlueprint } from '@rsc-kit/press/forms'\nimport { shadcn } from '@rsc-kit/press/shadcn'\n${imported}\n\n// The fields and every check are ${target}'s: the backend says what it takes,\n// and its refusals land under the fields. Place it in any page: <${exported}.Form />.\n// Add actions.update to edit a record with it too: <${exported}.Form id={...} values={...} />.\nexport const ${exported} = defineBlueprint({\n name: '${name}',\n actions: { create: ${reference} },\n theme: shadcn,\n})\n`;\n\n const { mkdirSync } = await import(\"node:fs\");\n\n mkdirSync(join(sourceDir, \"forms\"), { recursive: true });\n writeFileSync(file, text);\n\n return file;\n}\n"]}
package/dist/vite.d.ts CHANGED
@@ -336,17 +336,22 @@ export interface RscKitOptions {
336
336
  dynamicPattern: RegExp;
337
337
  };
338
338
  /**
339
- * Functions the host exposes to the app, as `{ exportedName: target }`.
340
- *
341
- * The build writes a "use server" module of stubs for these, each one
342
- * calling the host global with its target — so app code imports an ordinary
343
- * async function and never names the transport. Discovery belongs to the
344
- * host, whose functions these are; only the rendering is here, because the
345
- * module has to land beside the app's source and that path is the build's.
339
+ * Functions the host exposes to the app as server actions, by module and
340
+ * then by export: `{ "orders": { "create": "Orders.create" },
341
+ * "send-invite": { "default": "SendInvite" } }`.
342
+ *
343
+ * The build writes a "use server" module for each under `server-actions/`
344
+ * in the source directory - `server-actions/orders.ts` exporting `create` -
345
+ * each export calling the host global with its target, so app code imports
346
+ * an ordinary async function and never names the transport:
347
+ * `import * as orders from './server-actions/orders'`, then `orders.create`.
348
+ * Discovery belongs to the host, whose functions these are; only the
349
+ * rendering is here, because the modules land beside the app's source and
350
+ * that path is the build's.
346
351
  *
347
352
  * A host whose functions are already JavaScript passes nothing.
348
353
  */
349
- hostActions?: Record<string, string>;
354
+ hostActions?: HostActions;
350
355
  /**
351
356
  * The backend's command that writes its manifest, run as dev or a build
352
357
  * starts so the manifest cannot go stale:
@@ -371,6 +376,8 @@ export interface RscKitOptions {
371
376
  watch?: string[];
372
377
  };
373
378
  }
379
+ /** The backend's actions by module - its path under server-actions/ - and then by export. */
380
+ export type HostActions = Record<string, Record<string, string>>;
374
381
  /**
375
382
  * rscKit({ headers }), in the case the contract spells each name. Refused at
376
383
  * build, never trimmed at runtime: a header that was asked for and quietly not
@@ -778,6 +785,14 @@ export declare function serverOnlyEntry(id: string, root: string): string | null
778
785
  */
779
786
  export declare function nodeEnvPlugin(mode: "development" | "production"): string;
780
787
  export declare const SHUTDOWN_PLUGIN = "export default function rscKitShutdown() {\n if (typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers') return\n if (typeof process === 'undefined' || typeof process.once !== 'function') return\n\n const unref = (timer) => (timer && typeof timer.unref === 'function' ? timer.unref() : timer)\n let stopping = false\n\n const stop = () => {\n if (stopping) return\n stopping = true\n\n const drain = (Number(process.env.SERVER_SHUTDOWN_TIMEOUT) || 5) * 1000\n const limit = (Number(process.env.RSC_SHUTDOWN_TIMEOUT) || 10) * 1000\n\n unref(setTimeout(() => {\n const hook = globalThis.__rscKitShutdown\n\n Promise.race([\n Promise.resolve().then(() => (typeof hook === 'function' ? hook() : undefined)),\n new Promise((resolve) => unref(setTimeout(resolve, limit))),\n ])\n .catch((error) => console.error('[rsc-kit] instrumentation.ts shutdown() failed:', error))\n .finally(() => process.exit(0))\n }, drain + 250))\n }\n\n process.once('SIGTERM', stop)\n process.once('SIGINT', stop)\n}\n";
788
+ /**
789
+ * The Nitro rsc-kit is built against, and the oldest it runs on. Nitro 3
790
+ * numbers its prereleases by date (3.0.YYMMDD-tag), and a semver peer range
791
+ * cannot hold that: `>=3.0.261103-rc` refuses every later rc as a mismatch.
792
+ */
793
+ export declare const NITRO_VERSION = "3.0.261103-rc";
794
+ /** What to say when an app's Nitro is older than NITRO_VERSION, or null. */
795
+ export declare function nitroVersionProblem(version: string | undefined): string | null;
781
796
  /**
782
797
  * The PUBLIC_ variables an app still sets, and where each one is set.
783
798
  *