@vite-hub/codemods 0.5.1 → 0.6.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.
@@ -204,6 +204,10 @@ const codemodsErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
204
204
  why: ({ problem }) => problem,
205
205
  fix: "Change the file, the option, or the argument that the message names, then run the codemod again. Add `--dry-run` to see the edits before it writes them."
206
206
  },
207
+ CODEMODS_NITRO_UNSUPPORTED: {
208
+ why: ({ codemod, reason }) => `${reason} ViteHub supports Nitro 3 only. ${codemod} made no edits.`,
209
+ fix: ({ mixed }) => mixed ? "Keep only the Nitro package the app uses. If it uses Nitro 2, keep nuxt-safe-runtime-config/nitro until you upgrade to Nitro 3. Run the codemod again once the app uses Nitro 3." : "Keep nuxt-safe-runtime-config/nitro while the app runs on Nitro 2. To move to ViteHub Env, upgrade the app to Nitro 3 (the `nitro` package) first, then run the codemod again."
210
+ },
207
211
  CODEMODS_NUXT_UNSUPPORTED: {
208
212
  why: ({ codemods, nuxt, source }) => `${codemods.join(", ")} add${codemods.length === 1 ? "s" : ""} vite-hub/nuxt, which needs Nitro 3. Nitro 3 runs on Nuxt 4.7 with the nitro package, or on Nuxt 5. package.json requires nuxt "${nuxt}"${source}, which allows a Nuxt version before 4.7, so the build of the migrated app would fail. No file was written.`,
209
213
  fix: "Upgrade to Nuxt 4.7 and add Nitro 3 with `pnpm add nuxt@^4.7.0 nitro`, then run the command again. Or run the command again with `--nuxt-nightly`: it sets `\"nuxt\": \"npm:nuxt-nightly@5x\"` in package.json and migrates the app."
@@ -222,10 +226,10 @@ function codemodError(problem) {
222
226
  function isCodemodError(error) {
223
227
  if (!(error instanceof Error)) return false;
224
228
  const code = Reflect.get(error, "code");
225
- return code === "CODEMODS_BLOCKED" || code === "CODEMODS_NUXT_UNSUPPORTED" || code === "CODEMODS_UNKNOWN";
229
+ return code === "CODEMODS_BLOCKED" || code === "CODEMODS_NITRO_UNSUPPORTED" || code === "CODEMODS_NUXT_UNSUPPORTED" || code === "CODEMODS_UNKNOWN";
226
230
  }
227
231
  // src/shared/nuxt-config.ts
228
- const configNames = [
232
+ const configNames$1 = [
229
233
  "nuxt.config.ts",
230
234
  "nuxt.config.mts",
231
235
  "nuxt.config.js",
@@ -234,7 +238,7 @@ const configNames = [
234
238
  ];
235
239
  /** The file name of the project's nuxt.config, or `undefined` when it has none. */
236
240
  function findNuxtConfigName(cwd) {
237
- return configNames.find((name) => existsSync(join(cwd, name)));
241
+ return configNames$1.find((name) => existsSync(join(cwd, name)));
238
242
  }
239
243
  async function readNuxtConfig(cwd) {
240
244
  const fileName = findNuxtConfigName(cwd);
@@ -382,8 +386,8 @@ const defines = new Map([["defineRealtime", {
382
386
  }])]);
383
387
  /** Files whose default export is a definition, also as a plain object. */
384
388
  const definitionFiles = [[/(?:^|\/)server\/realtime\/.+$/, "realtime"], [/(?:^|\/)server\/mcp\/(?:tools|prompts|resources)\/.+$/, "mcp"]];
385
- const sourcePatterns$19 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}"];
386
- const ignoredPatterns$21 = [
389
+ const sourcePatterns$20 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}"];
390
+ const ignoredPatterns$22 = [
387
391
  "**/node_modules/**",
388
392
  "**/.nuxt/**",
389
393
  "**/.output/**",
@@ -482,10 +486,10 @@ function rewrite$4(context, kind, node) {
482
486
  if (kind === "realtime") rewriteRealtime(context, object);
483
487
  else rewriteMcp(context, object);
484
488
  }
485
- async function migrate$33({ cwd }) {
486
- const files = (await glob(sourcePatterns$19, {
489
+ async function migrate$34({ cwd }) {
490
+ const files = (await glob(sourcePatterns$20, {
487
491
  cwd,
488
- ignore: ignoredPatterns$21,
492
+ ignore: ignoredPatterns$22,
489
493
  dot: false
490
494
  })).sort();
491
495
  const edits = [];
@@ -544,13 +548,13 @@ const accessSpellings = {
544
548
  description: "Rename Realtime `auth: true` to `authorize: true`, and MCP `public: true` to `access: \"public\"`",
545
549
  usage: "[dir]",
546
550
  async detect({ cwd }) {
547
- const result = await migrate$33({ cwd });
551
+ const result = await migrate$34({ cwd });
548
552
  const [edit] = result.edits;
549
553
  if (edit) return { reason: `${edit.path} sets Realtime \`auth\` or MCP \`public\`` };
550
554
  const [followUp] = result.followUps;
551
555
  return followUp ? { reason: `${followUp.file} needs the Realtime \`authorize\` or MCP \`access\` change` } : void 0;
552
556
  },
553
- run: migrate$33
557
+ run: migrate$34
554
558
  };
555
559
  // src/shared/bindings.ts
556
560
  /** Collect declarations conservatively across the block, including nested patterns. */
@@ -685,8 +689,8 @@ const providerKinds = /* @__PURE__ */ new Set([
685
689
  "scheduler",
686
690
  "sandbox"
687
691
  ]);
688
- const sourcePatterns$18 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,vue}"];
689
- const ignoredPatterns$20 = [
692
+ const sourcePatterns$19 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,vue}"];
693
+ const ignoredPatterns$21 = [
690
694
  "**/node_modules/**",
691
695
  "**/.nuxt/**",
692
696
  "**/.output/**",
@@ -1047,13 +1051,13 @@ function rewriteBlock$4(context) {
1047
1051
  return context.output.toString() !== before;
1048
1052
  }
1049
1053
  async function sourceFiles$1(cwd) {
1050
- return (await glob(sourcePatterns$18, {
1054
+ return (await glob(sourcePatterns$19, {
1051
1055
  cwd,
1052
- ignore: ignoredPatterns$20,
1056
+ ignore: ignoredPatterns$21,
1053
1057
  dot: false
1054
1058
  })).sort();
1055
1059
  }
1056
- async function migrate$32({ cwd }) {
1060
+ async function migrate$33({ cwd }) {
1057
1061
  const edits = [];
1058
1062
  const followUps = [];
1059
1063
  for (const file of await sourceFiles$1(cwd)) {
@@ -1129,7 +1133,7 @@ const agentSurface = {
1129
1133
  if (/\b(?:state|scheduler|sandbox)\s*:\s*\{\s*provider\s*:/.test(source)) return { reason: `${file} selects an Agent provider with \`provider\`` };
1130
1134
  }
1131
1135
  },
1132
- run: migrate$32
1136
+ run: migrate$33
1133
1137
  };
1134
1138
  // src/auth-accessors/index.ts
1135
1139
  /** The modules that exported `auth` and `getAuth`. */
@@ -1142,8 +1146,8 @@ const serverModules = /* @__PURE__ */ new Set([
1142
1146
  const rootModules$1 = /* @__PURE__ */ new Set(["vite-hub/auth", "@vite-hub/auth"]);
1143
1147
  /** The modules that exported `useSession`. */
1144
1148
  const vueModules = /* @__PURE__ */ new Set(["vite-hub/auth/vue", "@vite-hub/auth/vue"]);
1145
- const sourcePatterns$17 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,vue}"];
1146
- const ignoredPatterns$19 = [
1149
+ const sourcePatterns$18 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,vue}"];
1150
+ const ignoredPatterns$20 = [
1147
1151
  "**/node_modules/**",
1148
1152
  "**/.nuxt/**",
1149
1153
  "**/.output/**",
@@ -1343,10 +1347,10 @@ function reportSession(context) {
1343
1347
  const [free] = references(context, void 0, "useSession").filter(({ node, parent }) => parent?.type === "CallExpression" && parent.callee === node);
1344
1348
  if (free) followUp$7(context, free.node, useSessionMessage);
1345
1349
  }
1346
- async function migrate$31({ cwd }) {
1347
- const files = (await glob(sourcePatterns$17, {
1350
+ async function migrate$32({ cwd }) {
1351
+ const files = (await glob(sourcePatterns$18, {
1348
1352
  cwd,
1349
- ignore: ignoredPatterns$19,
1353
+ ignore: ignoredPatterns$20,
1350
1354
  dot: false
1351
1355
  })).sort();
1352
1356
  const edits = [];
@@ -1408,13 +1412,13 @@ const authAccessors = {
1408
1412
  description: "Replace Auth's `auth` and `getAuth()` with `useAuth()`, `isGitHubOrgMember()` with `checkGitHubOrgMember()`, and list `useSession()` calls",
1409
1413
  usage: "[dir]",
1410
1414
  async detect({ cwd }) {
1411
- const result = await migrate$31({ cwd });
1415
+ const result = await migrate$32({ cwd });
1412
1416
  const [edit] = result.edits;
1413
1417
  if (edit) return { reason: `${edit.path} uses a removed Auth accessor` };
1414
1418
  const [followUp] = result.followUps;
1415
1419
  return followUp ? { reason: `${followUp.file} uses a removed Auth accessor` } : void 0;
1416
1420
  },
1417
- run: migrate$31
1421
+ run: migrate$32
1418
1422
  };
1419
1423
  // src/auth-sign-in/index.ts
1420
1424
  const configPatterns$2 = ["{vite,nuxt}.config.{ts,mts,cts,js,mjs,cjs}"];
@@ -1591,7 +1595,7 @@ function editDefinition(file, parsed, moved, followUps) {
1591
1595
  else if (moved.signIn !== void 0 || afterSignIn !== void 0) appendProperties(output, code, object, [`access: { ${[...moved.signIn === void 0 ? [] : [`signIn: ${quoteString(moved.signIn, style)}`], ...afterSignIn === void 0 ? [] : [`afterSignIn: ${quoteString(afterSignIn, style)}`]].join(", ")} }`]);
1592
1596
  return output.hasChanged() ? output.toString() : void 0;
1593
1597
  }
1594
- async function migrate$30({ cwd }) {
1598
+ async function migrate$31({ cwd }) {
1595
1599
  const edits = [];
1596
1600
  const followUps = [];
1597
1601
  const redirects = [];
@@ -1702,13 +1706,13 @@ const authSignIn = {
1702
1706
  description: "Move `vitehub({ auth: { redirects } })` and `access.signIn.callbackURL` to `access: { signIn, afterSignIn }` in server/auth.ts",
1703
1707
  usage: "[dir]",
1704
1708
  async detect({ cwd }) {
1705
- const result = await migrate$30({ cwd });
1709
+ const result = await migrate$31({ cwd });
1706
1710
  const [edit] = result.edits;
1707
1711
  if (edit) return { reason: `${edit.path} sets an Auth sign-in page in the old place` };
1708
1712
  const [followUp] = result.followUps;
1709
1713
  return followUp ? { reason: `${followUp.file} sets an Auth sign-in page in the old place` } : void 0;
1710
1714
  },
1711
- run: migrate$30
1715
+ run: migrate$31
1712
1716
  };
1713
1717
  // src/shared/module-source.ts
1714
1718
  /** The literal module reference in ESM, CommonJS, and TypeScript imports. */
@@ -1748,8 +1752,8 @@ const moduleCalls$4 = /* @__PURE__ */ new Set([
1748
1752
  "importActual",
1749
1753
  "importMock"
1750
1754
  ]);
1751
- const sourcePatterns$16 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,vue}"];
1752
- const ignoredPatterns$18 = [
1755
+ const sourcePatterns$17 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,vue}"];
1756
+ const ignoredPatterns$19 = [
1753
1757
  "**/node_modules/**",
1754
1758
  "**/.nuxt/**",
1755
1759
  "**/.output/**",
@@ -1908,7 +1912,7 @@ function replaceHttp(context) {
1908
1912
  }
1909
1913
  }
1910
1914
  }
1911
- function property$2(object, name) {
1915
+ function property$3(object, name) {
1912
1916
  const found = object.properties.find((entry) => entry.type === "ObjectProperty" && !entry.computed && keyName(entry.key) === name);
1913
1917
  return found?.type === "ObjectProperty" ? found : void 0;
1914
1918
  }
@@ -1936,9 +1940,9 @@ function rewriteSignature(context, entry) {
1936
1940
  return renamed !== void 0;
1937
1941
  }
1938
1942
  if (value.type !== "ObjectExpression") return false;
1939
- const tolerance = property$2(value, "toleranceSeconds");
1943
+ const tolerance = property$3(value, "toleranceSeconds");
1940
1944
  if (tolerance) renameTolerance(context, tolerance);
1941
- const preset = property$2(value, "preset");
1945
+ const preset = property$3(value, "preset");
1942
1946
  if (!preset) return tolerance !== void 0;
1943
1947
  const name = unwrap$2(preset.value);
1944
1948
  if (name.type !== "StringLiteral") {
@@ -2001,9 +2005,9 @@ function processEnvName$2(node) {
2001
2005
  * `secret` string names a variable.
2002
2006
  */
2003
2007
  function rewriteRegistration(context, registration) {
2004
- const signature = property$2(registration, "signature");
2008
+ const signature = property$3(registration, "signature");
2005
2009
  if (signature) rewriteSignature(context, signature);
2006
- const token = property$2(registration, "secretToken");
2010
+ const token = property$3(registration, "secretToken");
2007
2011
  if (!token) return;
2008
2012
  const value = unwrap$2(token.value);
2009
2013
  const { style } = context;
@@ -2071,11 +2075,11 @@ function rewriteWebhookOptions(context) {
2071
2075
  const adapter = binding && adapters.get(binding);
2072
2076
  const options = adapter && node.arguments[0] && unwrap$2(node.arguments[0]);
2073
2077
  if (options?.type !== "ObjectExpression") return;
2074
- const signature = property$2(options, "signature");
2078
+ const signature = property$3(options, "signature");
2075
2079
  const legacySignature = signature && rewriteSignature(context, signature);
2076
- const secret = property$2(options, "secret");
2080
+ const secret = property$3(options, "secret");
2077
2081
  if (secret) rewriteSecret(context, secret, adapter === "stripe" || legacySignature === true);
2078
- const tolerance = adapter === "stripe" ? property$2(options, "toleranceSeconds") : void 0;
2082
+ const tolerance = adapter === "stripe" ? property$3(options, "toleranceSeconds") : void 0;
2079
2083
  if (tolerance) renameTolerance(context, tolerance);
2080
2084
  });
2081
2085
  }
@@ -2214,10 +2218,10 @@ function moveImports(context, changed) {
2214
2218
  else if (usage === "unknown") reportAdapterSplit(context, node, source.value);
2215
2219
  });
2216
2220
  }
2217
- async function migrate$29({ cwd }) {
2218
- const files = (await glob(sourcePatterns$16, {
2221
+ async function migrate$30({ cwd }) {
2222
+ const files = (await glob(sourcePatterns$17, {
2219
2223
  cwd,
2220
- ignore: ignoredPatterns$18,
2224
+ ignore: ignoredPatterns$19,
2221
2225
  dot: false
2222
2226
  })).sort();
2223
2227
  const edits = [];
@@ -2276,17 +2280,17 @@ const channels = {
2276
2280
  description: "Move `vite-hub/agent/channels` imports to `vite-hub/channels/adapters` and `vite-hub/channels`, replace the Agent `http()` adapter with `channelAdapter(\"http\")`, and move `webhook()`, `stripe()`, and Agent webhook registrations to `secret` names and Webhooks signature names",
2277
2281
  usage: "[dir]",
2278
2282
  async detect({ cwd }) {
2279
- const result = await migrate$29({ cwd });
2283
+ const result = await migrate$30({ cwd });
2280
2284
  const [edit] = result.edits;
2281
2285
  if (edit) return { reason: `${edit.path} imports an old Channel path, calls the Agent \`http()\` adapter, or sets an old webhook option` };
2282
2286
  const [followUp] = result.followUps;
2283
2287
  return followUp ? { reason: `${followUp.file} needs a manual Agent Channel migration` } : void 0;
2284
2288
  },
2285
- run: migrate$29
2289
+ run: migrate$30
2286
2290
  };
2287
2291
  // src/choices-package/index.ts
2288
- const sourcePatterns$15 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,vue}", "**/package.json"];
2289
- const ignoredPatterns$17 = [
2292
+ const sourcePatterns$16 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,vue}", "**/package.json"];
2293
+ const ignoredPatterns$18 = [
2290
2294
  "**/node_modules/**",
2291
2295
  "**/.nuxt/**",
2292
2296
  "**/.output/**",
@@ -2431,13 +2435,13 @@ function migrateSource(file, code, followUps) {
2431
2435
  }
2432
2436
  return output.toString();
2433
2437
  }
2434
- async function migrate$28({ cwd }) {
2438
+ async function migrate$29({ cwd }) {
2435
2439
  const edits = [];
2436
2440
  const followUps = [];
2437
2441
  const changedDependencies = /* @__PURE__ */ new Set();
2438
- for (const file of (await glob(sourcePatterns$15, {
2442
+ for (const file of (await glob(sourcePatterns$16, {
2439
2443
  cwd,
2440
- ignore: ignoredPatterns$17
2444
+ ignore: ignoredPatterns$18
2441
2445
  })).sort()) {
2442
2446
  const code = await readFile(join(cwd, file), "utf8");
2443
2447
  if (!code.includes("decisions")) continue;
@@ -2461,11 +2465,11 @@ const choicesPackage = {
2461
2465
  description: "Rename `@vite-hub/decisions` to `@vite-hub/choices`, `vite-hub/decisions` to `vite-hub/choices`, and `vitehub decisions` to `vitehub choices`",
2462
2466
  usage: "[dir]",
2463
2467
  async detect({ cwd }) {
2464
- const { edits, followUps } = await migrate$28({ cwd });
2468
+ const { edits, followUps } = await migrate$29({ cwd });
2465
2469
  const file = edits[0]?.path ?? followUps[0]?.file;
2466
2470
  return file ? { reason: `Found a Decisions reference in ${file}` } : void 0;
2467
2471
  },
2468
- run: migrate$28
2472
+ run: migrate$29
2469
2473
  };
2470
2474
  // src/shared/cli-calls.ts
2471
2475
  /** Files that call the `vitehub` CLI: package scripts, CI workflows, and shell scripts. */
@@ -2474,7 +2478,7 @@ const callerPatterns$1 = [
2474
2478
  ".github/workflows/*.{yml,yaml}",
2475
2479
  "**/*.sh"
2476
2480
  ];
2477
- const ignoredPatterns$16 = [
2481
+ const ignoredPatterns$17 = [
2478
2482
  "**/node_modules/**",
2479
2483
  "**/.nuxt/**",
2480
2484
  "**/.output/**",
@@ -2579,7 +2583,7 @@ async function rewriteCliCalls$1(cwd, rewrite, manual) {
2579
2583
  const files = (await glob(callerPatterns$1, {
2580
2584
  cwd,
2581
2585
  dot: true,
2582
- ignore: ignoredPatterns$16
2586
+ ignore: ignoredPatterns$17
2583
2587
  })).sort();
2584
2588
  const edits = [];
2585
2589
  const followUps = [];
@@ -2730,7 +2734,7 @@ function manual$2(line) {
2730
2734
  if (/\bvitehub\s+invocations\s+(?:cancel|undo|capabilities|workspace)\b.*--input\b/.test(line)) return "Move this Invocation operation under `vitehub agent invocations` by hand: replace --input with the positional ID and supported options, or call the Console RPC directly.";
2731
2735
  if (/\bvitehub\s+invocations\s+(?:cancel|undo)\b/.test(line)) return "Move this Invocation operation under `vitehub agent invocations` by hand and pass --url with the same Console app.";
2732
2736
  }
2733
- async function migrate$27({ cwd }) {
2737
+ async function migrate$28({ cwd }) {
2734
2738
  const { calls, edits, followUps } = await rewriteCliCalls$1(cwd, rewrite$3, manual$2);
2735
2739
  return {
2736
2740
  summary: edits.length ? `moved ${calls} vitehub call(s) into the vitehub agent commands` : followUps.length ? "found Agent commands that need manual migration" : "found no vitehub agents, invocations, or conversations call",
@@ -2746,11 +2750,11 @@ const cliAgentTree = {
2746
2750
  detectAfterEdits: true,
2747
2751
  usage: "[dir]",
2748
2752
  async detect({ cwd }) {
2749
- const { edits, followUps } = await migrate$27({ cwd });
2753
+ const { edits, followUps } = await migrate$28({ cwd });
2750
2754
  const file = edits[0]?.path ?? followUps[0]?.file;
2751
2755
  return file ? { reason: `${file} calls a vitehub Agent command that moved` } : void 0;
2752
2756
  },
2753
- run: migrate$27
2757
+ run: migrate$28
2754
2758
  };
2755
2759
  // src/cli-get-list/cli-calls.ts
2756
2760
  const callerPatterns = [
@@ -2758,7 +2762,7 @@ const callerPatterns = [
2758
2762
  ".github/workflows/*.{yml,yaml}",
2759
2763
  "**/*.sh"
2760
2764
  ];
2761
- const ignoredPatterns$15 = [
2765
+ const ignoredPatterns$16 = [
2762
2766
  "**/node_modules/**",
2763
2767
  "**/.nuxt/**",
2764
2768
  "**/.output/**",
@@ -2834,7 +2838,7 @@ async function rewriteCliCalls(cwd, rewrite) {
2834
2838
  const files = (await glob(callerPatterns, {
2835
2839
  cwd,
2836
2840
  dot: true,
2837
- ignore: ignoredPatterns$15
2841
+ ignore: ignoredPatterns$16
2838
2842
  })).sort();
2839
2843
  const edits = [];
2840
2844
  const followUps = [];
@@ -2992,7 +2996,7 @@ function rewrite$2(args, words) {
2992
2996
  for (const [pattern, now] of renames) if (pattern.test(args)) return args.replace(pattern, now);
2993
2997
  return args;
2994
2998
  }
2995
- async function migrate$26({ cwd }) {
2999
+ async function migrate$27({ cwd }) {
2996
3000
  const { calls, edits, followUps } = await rewriteCliCalls(cwd, rewrite$2);
2997
3001
  return {
2998
3002
  summary: edits.length ? `renamed ${calls} vitehub call(s) to get and list` : followUps.length ? "found renamed read commands that need manual migration" : "found no vitehub call with a renamed read command",
@@ -3007,11 +3011,11 @@ const cliGetList = {
3007
3011
  description: "Rename vitehub read commands in scripts and CI: show and info to get, env inspect and env status to env list, schedule runs to runs list, and more",
3008
3012
  usage: "[dir]",
3009
3013
  async detect({ cwd }) {
3010
- const { edits, followUps } = await migrate$26({ cwd });
3014
+ const { edits, followUps } = await migrate$27({ cwd });
3011
3015
  const file = edits[0]?.path ?? followUps[0]?.file;
3012
3016
  return file ? { reason: `${file} calls a renamed vitehub read command` } : void 0;
3013
3017
  },
3014
- run: migrate$26
3018
+ run: migrate$27
3015
3019
  };
3016
3020
  // src/cli-url-flag/index.ts
3017
3021
  function serverOptions({ words }) {
@@ -3089,7 +3093,7 @@ function manual$1(command) {
3089
3093
  const calls = findCliCalls(command, true);
3090
3094
  if (calls ? calls.some(({ call }) => serverOptions(call).offsets.length) : /^\s*(?:(?:pnpm|npm|yarn) exec |(?:pnpm|npx|bunx) )?vitehub (?:agent|workspace|channels|connections)\b.*--server\b/.test(command)) return "Check whether --server belongs to vitehub in this command and change it to --url if it does.";
3091
3095
  }
3092
- async function migrate$25({ cwd }) {
3096
+ async function migrate$26({ cwd }) {
3093
3097
  const { edits, followUps } = await rewriteCliCalls$1(cwd, rewrite$1, manual$1);
3094
3098
  return {
3095
3099
  summary: edits.length ? `moved vitehub calls from --server to --url in ${edits.length} file(s)` : "no vitehub calls migrated",
@@ -3104,11 +3108,11 @@ const cliUrlFlag = {
3104
3108
  description: "Use --url, the app URL, in vitehub calls of scripts and CI instead of --server",
3105
3109
  usage: "[dir]",
3106
3110
  async detect({ cwd }) {
3107
- const { edits, followUps } = await migrate$25({ cwd });
3111
+ const { edits, followUps } = await migrate$26({ cwd });
3108
3112
  const file = edits[0]?.path ?? followUps[0]?.file;
3109
3113
  return file ? { reason: `${file} may pass --server to vitehub` } : void 0;
3110
3114
  },
3111
- run: migrate$25
3115
+ run: migrate$26
3112
3116
  };
3113
3117
  // src/cli-yes-flag/index.ts
3114
3118
  function literal$1(text) {
@@ -3153,7 +3157,7 @@ function manual(command) {
3153
3157
  if (/\bvitehub\s+database\s+generate\b.*--non-interactive\b/.test(command)) return "Set CI=1 in the command's environment before removing --non-interactive so generation still cannot prompt.";
3154
3158
  if (/\bvitehub\s+database\s+(?:drop|reset)\b.*--force\b/.test(command)) return "Change --force to --yes if it is a flag of database drop or reset.";
3155
3159
  }
3156
- async function migrate$24({ cwd }) {
3160
+ async function migrate$25({ cwd }) {
3157
3161
  const { calls, edits, followUps } = await rewriteCliCalls$1(cwd, rewrite, manual);
3158
3162
  return {
3159
3163
  summary: calls || followUps.length ? `updated ${calls} vitehub call(s); ${followUps.length} need manual review` : "found no vitehub call that skips a question with another flag",
@@ -3168,15 +3172,15 @@ const cliYesFlag = {
3168
3172
  description: "Use --yes in vitehub calls of scripts and CI: database drop|reset --force, connections revoke --confirm, database generate --non-interactive",
3169
3173
  usage: "[dir]",
3170
3174
  async detect({ cwd }) {
3171
- const { edits, followUps } = await migrate$24({ cwd });
3175
+ const { edits, followUps } = await migrate$25({ cwd });
3172
3176
  const file = edits[0]?.path ?? followUps[0]?.file;
3173
3177
  return file ? { reason: `${file} may use a removed vitehub prompt flag` } : void 0;
3174
3178
  },
3175
- run: migrate$24
3179
+ run: migrate$25
3176
3180
  };
3177
3181
  // src/cms-roles/index.ts
3178
- const sourcePatterns$14 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}"];
3179
- const ignoredPatterns$14 = [
3182
+ const sourcePatterns$15 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}"];
3183
+ const ignoredPatterns$15 = [
3180
3184
  "**/node_modules/**",
3181
3185
  "**/.nuxt/**",
3182
3186
  "**/.output/**",
@@ -3221,12 +3225,12 @@ function isCmsPreset(node, bindings, resolve) {
3221
3225
  if (value.type === "Identifier") return resolvesTo(value, bindings.presets, resolve);
3222
3226
  return value.type === "MemberExpression" && !value.computed && value.property.type === "Identifier" && (value.property.name === "cms" || value.property.name === "default") && resolvesTo(value.object, bindings.namespaces, resolve);
3223
3227
  }
3224
- async function migrate$23({ cwd }) {
3228
+ async function migrate$24({ cwd }) {
3225
3229
  const edits = [];
3226
3230
  const followUps = [];
3227
- for (const file of (await glob(sourcePatterns$14, {
3231
+ for (const file of (await glob(sourcePatterns$15, {
3228
3232
  cwd,
3229
- ignore: ignoredPatterns$14
3233
+ ignore: ignoredPatterns$15
3230
3234
  })).sort()) {
3231
3235
  const code = await readFile(join(cwd, file), "utf8");
3232
3236
  if (!code.includes("cms") || !/\baccess\b/.test(code)) continue;
@@ -3289,12 +3293,253 @@ const cmsRoles = {
3289
3293
  description: "Rename the cms preset option `access: \"roles\"` to `roles: true`",
3290
3294
  usage: "[dir]",
3291
3295
  async detect({ cwd }) {
3292
- const result = await migrate$23({ cwd });
3296
+ const result = await migrate$24({ cwd });
3293
3297
  const [edit] = result.edits;
3294
3298
  if (edit) return { reason: `${edit.path} sets the cms preset option \`access\`` };
3295
3299
  const [followUp] = result.followUps;
3296
3300
  return followUp ? { reason: `${followUp.file} sets the cms preset option \`access\`` } : void 0;
3297
3301
  },
3302
+ run: migrate$24
3303
+ };
3304
+ // src/console-out-of-app/index.ts
3305
+ const authModule = "vite-hub/console/auth";
3306
+ const pageContextType = "ConsolePageAuthorizeContext";
3307
+ const authorizeFile = /(?:^|\/)server\/console-authorize\.[cm]?[jt]s$/;
3308
+ const sourcePatterns$14 = ["**/*.{ts,mts,cts,js,mjs,cjs}"];
3309
+ const envPatterns$1 = [
3310
+ ".env",
3311
+ ".env.*",
3312
+ ".dev.vars",
3313
+ "wrangler.*",
3314
+ "**/.env",
3315
+ "**/.env.*",
3316
+ "**/.dev.vars",
3317
+ "**/wrangler.*"
3318
+ ];
3319
+ const ignoredPatterns$14 = [
3320
+ "**/node_modules/**",
3321
+ "**/.nuxt/**",
3322
+ "**/.output/**",
3323
+ "**/.data/**",
3324
+ "**/.vitehub/**",
3325
+ "**/dist/**",
3326
+ "**/coverage/**"
3327
+ ];
3328
+ const pageBranch = "`console.authorize` no longer gets `via: \"page\"`: the Comments pill loads the Console segment from the ViteHub Console, which checks the person and the team. Remove the code that handles `\"page\"`.";
3329
+ const pageType = "`ConsolePageAuthorizeContext` was removed with `via: \"page\"`. Remove the type and the code that handles `\"page\"`.";
3330
+ const mcpKey = "`VITEHUB_CONSOLE_MCP_KEY` is not read anymore: the MCP client section of the ViteHub Console connects to MCP servers from the Console server. Remove this line, and remove the secret from each deployment.";
3331
+ function isFunction$3(node) {
3332
+ return node?.type === "ArrowFunctionExpression" || node?.type === "FunctionDeclaration" || node?.type === "FunctionExpression";
3333
+ }
3334
+ function declaresHoistedBinding(branch) {
3335
+ let found = false;
3336
+ walk(branch, (node, ancestors) => {
3337
+ if (found || ancestors.some(isNestedScope)) return;
3338
+ if (node.type === "FunctionDeclaration" || node.type === "VariableDeclaration" && node.kind === "var") found = true;
3339
+ });
3340
+ return found;
3341
+ }
3342
+ function isNestedScope(node) {
3343
+ return isFunction$3(node) || node.type === "ObjectMethod" || node.type === "ClassMethod" || node.type === "ClassPrivateMethod";
3344
+ }
3345
+ function viaMatcher(fn, resolve) {
3346
+ const first = fn.params[0];
3347
+ const param = first?.type === "AssignmentPattern" ? first.left : first;
3348
+ const context = param?.type === "Identifier" ? param : void 0;
3349
+ let via;
3350
+ if (param?.type === "ObjectPattern") for (const item of param.properties) {
3351
+ if (item.type !== "ObjectProperty" || keyName(item.key, item.computed) !== "via") continue;
3352
+ const value = item.value.type === "AssignmentPattern" ? item.value.left : item.value;
3353
+ if (value.type === "Identifier") via = value;
3354
+ }
3355
+ return (node, nested) => {
3356
+ const value = unwrapExpression(node);
3357
+ if (value.type === "Identifier") {
3358
+ if (via !== void 0 && resolve(value) === via) return nested ? "report" : "remove";
3359
+ return value.name === "via" ? "report" : void 0;
3360
+ }
3361
+ if (value.type !== "MemberExpression" && value.type !== "OptionalMemberExpression") return void 0;
3362
+ if (keyName(value.property, value.computed) !== "via" || value.object.type !== "Identifier" || !context) return void 0;
3363
+ if (resolve(value.object) === context) return nested ? "report" : "remove";
3364
+ return nested && value.object.name === context.name ? "report" : void 0;
3365
+ };
3366
+ }
3367
+ function isPage(node) {
3368
+ const value = unwrapExpression(node);
3369
+ return value.type === "StringLiteral" && value.value === "page";
3370
+ }
3371
+ function authorizeFunctions(file, program, resolve) {
3372
+ const defines = /* @__PURE__ */ new Set();
3373
+ for (const statement of program.program.body) {
3374
+ if (statement.type !== "ImportDeclaration" || statement.source.value !== authModule) continue;
3375
+ for (const specifier of statement.specifiers) if (specifier.type === "ImportSpecifier" && keyName(specifier.imported) === "defineConsoleAuthorize") defines.add(specifier.local);
3376
+ }
3377
+ const declarations = /* @__PURE__ */ new Map();
3378
+ walk(program, (node) => {
3379
+ if (node.type === "FunctionDeclaration" && node.id) declarations.set(node.id, node);
3380
+ if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.init) {
3381
+ const init = unwrapExpression(node.init);
3382
+ if (isFunction$3(init)) declarations.set(node.id, init);
3383
+ }
3384
+ });
3385
+ const functionOf = (node) => {
3386
+ if (!node) return void 0;
3387
+ const value = unwrapExpression(node);
3388
+ if (isFunction$3(value)) return value;
3389
+ if (value.type !== "Identifier") return void 0;
3390
+ const binding = resolve(value);
3391
+ return binding ? declarations.get(binding) : void 0;
3392
+ };
3393
+ const found = /* @__PURE__ */ new Set();
3394
+ walk(program, (node) => {
3395
+ if (node.type === "CallExpression" && node.callee.type === "Identifier") {
3396
+ const binding = resolve(node.callee);
3397
+ const argument = node.arguments[0];
3398
+ const fn = binding && defines.has(binding) && argument?.type !== "SpreadElement" ? functionOf(argument) : void 0;
3399
+ if (fn) found.add(fn);
3400
+ }
3401
+ if (node.type === "ExportDefaultDeclaration" && authorizeFile.test(file)) {
3402
+ const fn = functionOf(node.declaration);
3403
+ if (fn) found.add(fn);
3404
+ }
3405
+ });
3406
+ return [...found];
3407
+ }
3408
+ /** Removes the `via === "page"` branch of `console.authorize` and the `ConsolePageAuthorizeContext` import from one file. */
3409
+ function migrateConsoleAuthorize(file, code) {
3410
+ const followUps = [];
3411
+ const unchanged = {
3412
+ code,
3413
+ changed: false,
3414
+ followUps
3415
+ };
3416
+ if (!code.includes(authModule) && !authorizeFile.test(file)) return unchanged;
3417
+ let program;
3418
+ try {
3419
+ program = parseProgram(code, {
3420
+ jsx: false,
3421
+ typescript: !/\.(?:c|m)?js$/.test(file)
3422
+ });
3423
+ } catch {
3424
+ return unchanged;
3425
+ }
3426
+ const output = new MagicString(code);
3427
+ let changed = false;
3428
+ const removedRanges = [];
3429
+ const removeRange = (range, replacement = "") => {
3430
+ output.update(range[0], range[1], replacement);
3431
+ removedRanges.push(range);
3432
+ changed = true;
3433
+ };
3434
+ const inRemoved = (node) => removedRanges.some(([from, to]) => start(node) >= from && end(node) <= to);
3435
+ const follow = (node, message) => followUps.push({
3436
+ file,
3437
+ line: line(node),
3438
+ message
3439
+ });
3440
+ const resolve = bindingResolver(program);
3441
+ for (const fn of authorizeFunctions(file, program, resolve)) {
3442
+ const matchVia = viaMatcher(fn, resolve);
3443
+ walk(fn, (node, ancestors) => {
3444
+ if (inRemoved(node)) return;
3445
+ const nested = ancestors.slice(1).some(isNestedScope);
3446
+ if (node.type === "SwitchCase" && node.test && isPage(node.test)) {
3447
+ const parent = ancestors.at(-1);
3448
+ if (parent?.type === "SwitchStatement" && matchVia(parent.discriminant, nested)) follow(node, pageBranch);
3449
+ return;
3450
+ }
3451
+ if (node.type !== "BinaryExpression" || ![
3452
+ "===",
3453
+ "==",
3454
+ "!==",
3455
+ "!="
3456
+ ].includes(node.operator)) return;
3457
+ if (node.left.type === "PrivateName") return;
3458
+ const match = isPage(node.right) ? matchVia(node.left, nested) : isPage(node.left) ? matchVia(node.right, nested) : void 0;
3459
+ if (!match) return;
3460
+ const parent = ancestors.at(-1);
3461
+ const block = ancestors.at(-2);
3462
+ if (match === "remove" && (node.operator === "===" || node.operator === "==") && parent?.type === "IfStatement" && parent.test === node && !parent.alternate && (block?.type === "BlockStatement" || block?.type === "Program") && !declaresHoistedBinding(parent.consequent)) {
3463
+ const statements = block.body;
3464
+ if (statements[statements.indexOf(parent) + 1]?.type === "ExpressionStatement") removeRange([start(parent), end(parent)], ";");
3465
+ else removeRange(listItemRemoval(code, parent));
3466
+ } else follow(node, pageBranch);
3467
+ });
3468
+ }
3469
+ for (const statement of program.program.body) {
3470
+ if (statement.type !== "ImportDeclaration" || statement.source.value !== authModule) continue;
3471
+ const unused = statement.specifiers.filter((specifier) => specifier.type === "ImportSpecifier" && keyName(specifier.imported) === pageContextType).filter((specifier) => {
3472
+ const local = specifier.local.name;
3473
+ let used = false;
3474
+ walk(program, (node, ancestors) => {
3475
+ if (used || node.type !== "Identifier" || node.name !== local || inRemoved(node)) return;
3476
+ if (ancestors.at(-1)?.type === "ImportSpecifier") return;
3477
+ used = true;
3478
+ });
3479
+ if (used) follow(specifier, pageType);
3480
+ return !used;
3481
+ });
3482
+ if (unused.length && unused.length === statement.specifiers.length) removeRange(listItemRemoval(code, statement));
3483
+ else for (const specifier of unused) removeRange(listItemRemoval(code, specifier));
3484
+ }
3485
+ return changed ? {
3486
+ code: output.toString(),
3487
+ changed,
3488
+ followUps
3489
+ } : unchanged;
3490
+ }
3491
+ async function mcpKeyFollowUps(cwd) {
3492
+ const followUps = [];
3493
+ for (const file of (await glob(envPatterns$1, {
3494
+ cwd,
3495
+ ignore: ignoredPatterns$14,
3496
+ dot: true
3497
+ })).sort()) (await readFile(join(cwd, file), "utf8").catch(() => "")).split("\n").forEach((value, index) => {
3498
+ if (/\bVITEHUB_CONSOLE_MCP_KEY\b/.test(value)) followUps.push({
3499
+ file,
3500
+ line: index + 1,
3501
+ message: mcpKey
3502
+ });
3503
+ });
3504
+ return followUps;
3505
+ }
3506
+ async function migrate$23({ cwd }) {
3507
+ const edits = [];
3508
+ const followUps = [];
3509
+ for (const file of (await glob(sourcePatterns$14, {
3510
+ cwd,
3511
+ ignore: ignoredPatterns$14,
3512
+ dot: false
3513
+ })).sort()) {
3514
+ const before = await readFile(join(cwd, file), "utf8");
3515
+ const result = migrateConsoleAuthorize(file, before);
3516
+ followUps.push(...result.followUps);
3517
+ if (result.changed) edits.push({
3518
+ path: file,
3519
+ before,
3520
+ after: result.code
3521
+ });
3522
+ }
3523
+ followUps.push(...await mcpKeyFollowUps(cwd));
3524
+ return {
3525
+ summary: edits.length ? `removed the Console page check from ${edits.length} file(s)` : "found no Console page check to remove",
3526
+ edits,
3527
+ followUps,
3528
+ notes: [],
3529
+ nextSteps: edits.length || followUps.length ? ["Run your typecheck."] : []
3530
+ };
3531
+ }
3532
+ const consoleOutOfApp = {
3533
+ name: "console-out-of-app",
3534
+ description: "Remove the `via: \"page\"` branch of `console.authorize` and `ConsolePageAuthorizeContext`, and report `VITEHUB_CONSOLE_MCP_KEY`",
3535
+ usage: "[dir]",
3536
+ async detect({ cwd }) {
3537
+ const result = await migrate$23({ cwd });
3538
+ const [edit] = result.edits;
3539
+ if (edit) return { reason: `${edit.path} checks the Console link of the page tools pill` };
3540
+ const [followUp] = result.followUps;
3541
+ return followUp ? { reason: `${followUp.file} uses a Console option that left the app` } : void 0;
3542
+ },
3298
3543
  run: migrate$23
3299
3544
  };
3300
3545
  // src/define-forms/shared.ts
@@ -3611,7 +3856,7 @@ function moveIndex(plan) {
3611
3856
  }
3612
3857
  return byPath;
3613
3858
  }
3614
- function relativeSpecifier$1(fromFolder, target) {
3859
+ function relativeSpecifier$2(fromFolder, target) {
3615
3860
  const path = posix.relative(fromFolder, target) || ".";
3616
3861
  return path.startsWith(".") ? path : `./${path}`;
3617
3862
  }
@@ -3628,7 +3873,7 @@ function rewriteSpecifier(file, newFile, specifier, moves, folderImport) {
3628
3873
  return `${resolved.alias}/${resolved.alias === "#server" ? posix.relative("server", target) : target}`;
3629
3874
  }
3630
3875
  if (target === resolved.path && file === newFile) return void 0;
3631
- const next = relativeSpecifier$1(folderOf(newFile), target);
3876
+ const next = relativeSpecifier$2(folderOf(newFile), target);
3632
3877
  return next === specifier ? void 0 : next;
3633
3878
  }
3634
3879
  /** Rewrites the import paths and path strings of one file for the planned moves. */
@@ -3796,7 +4041,7 @@ function rewriteSandboxTasks(file, parsed, output, followUps) {
3796
4041
  // src/define-forms/schedule.ts
3797
4042
  const scheduleModules$1 = /* @__PURE__ */ new Set(["vite-hub/schedule", "@vite-hub/schedule"]);
3798
4043
  /** The text of a property: `cron` for `cron: cron`, else `cron: <value>`. */
3799
- function property$1(key, value) {
4044
+ function property$2(key, value) {
3800
4045
  return value === key ? key : `${key}: ${value}`;
3801
4046
  }
3802
4047
  /**
@@ -3817,13 +4062,13 @@ function rewriteSchedules(file, parsed, output, followUps) {
3817
4062
  followUps.push(followUpAt(file.path, node, "`defineSchedule(cron, handler)` was removed. Rewrite this call as `defineSchedule({ cron, handler })` by hand."));
3818
4063
  return;
3819
4064
  }
3820
- const fields = [property$1("cron", text(cron))];
4065
+ const fields = [property$2("cron", text(cron))];
3821
4066
  if (options?.type === "ObjectExpression") fields.push(...options.properties.map(text));
3822
4067
  else if (options) {
3823
4068
  fields.push(`...${text(options)}`);
3824
4069
  followUps.push(followUpAt(file.path, node, "The options of this Schedule are not an object literal, so the codemod spread them. The build reads `manual` and `timeZone` only from literal properties: write them in the object."));
3825
4070
  }
3826
- fields.push(property$1("handler", text(handler)));
4071
+ fields.push(property$2("handler", text(handler)));
3827
4072
  output.overwrite(start(cron), end(options ?? handler), `{ ${fields.join(", ")} }`);
3828
4073
  count++;
3829
4074
  });
@@ -4204,7 +4449,7 @@ const defineForms = {
4204
4449
  run: migrate$22
4205
4450
  };
4206
4451
  // package.json
4207
- var version = "0.5.1";
4452
+ var version = "0.6.0";
4208
4453
  // src/shared/config-editor.ts
4209
4454
  const vitehubModule = "vite-hub/nuxt";
4210
4455
  const nitroPresetHosts = {
@@ -5054,6 +5299,21 @@ export default defineWorkflow<{ id: string }>({
5054
5299
  title: "Workspace"
5055
5300
  })
5056
5301
  };
5302
+ // src/shared/pnpm-catalog.ts
5303
+ function catalogEntry(value, key) {
5304
+ return value instanceof Map ? value.get(key) : void 0;
5305
+ }
5306
+ async function readPnpmCatalogVersion(cwd, name, catalog) {
5307
+ let directory = cwd;
5308
+ while (!existsSync(join(directory, "pnpm-workspace.yaml"))) {
5309
+ if (dirname(directory) === directory) return;
5310
+ directory = dirname(directory);
5311
+ }
5312
+ const workspace = parseDocument(await readFile(join(directory, "pnpm-workspace.yaml"), "utf8")).toJS({ mapAsMap: true });
5313
+ const fallback = catalog === "default" ? catalogEntry(catalogEntry(workspace, "catalog"), name) : void 0;
5314
+ const version = catalogEntry(catalogEntry(catalogEntry(workspace, "catalogs"), catalog), name) ?? fallback;
5315
+ if (typeof version === "string") return version;
5316
+ }
5057
5317
  // src/shared/package-json.ts
5058
5318
  const sections$1 = ["dependencies", "devDependencies"];
5059
5319
  function isRecord$6(value) {
@@ -5083,6 +5343,15 @@ function featurePackageSpecifier(name, viteHub) {
5083
5343
  function outside(range, supported) {
5084
5344
  return validRange(range) !== null && !subset(range, supported, { includePrerelease: true });
5085
5345
  }
5346
+ async function resolveDeclaredRange(cwd, name, declared) {
5347
+ const catalog = /^catalog:(.*)$/.exec(declared)?.[1];
5348
+ const range = catalog === void 0 ? declared : await readPnpmCatalogVersion(cwd, name, catalog.trim() || "default");
5349
+ if (range === void 0) return;
5350
+ return {
5351
+ range: range.startsWith(`npm:${name}@`) ? range.slice(`npm:${name}@`.length) : range,
5352
+ catalog: catalog !== void 0
5353
+ };
5354
+ }
5086
5355
  /**
5087
5356
  * Removes `change.remove` and adds `change.add`. Added packages go to the section that held a removed package,
5088
5357
  * or to `dependencies`.
@@ -5090,14 +5359,19 @@ function outside(range, supported) {
5090
5359
  async function editPackageJson(cwd, version, change) {
5091
5360
  const path = join(cwd, "package.json");
5092
5361
  const command = detectInstallCommand(cwd);
5362
+ const required = change.require;
5093
5363
  const owners = new Set((change.features ?? []).flatMap((id) => features[id].packages).filter((name) => name.startsWith("@vite-hub/")));
5094
5364
  const add = /* @__PURE__ */ new Set([...change.add, ...owners]);
5095
5365
  const names = new Set(add);
5096
5366
  const installList = new Intl.ListFormat("en", { type: "conjunction" });
5097
- if (!existsSync(path)) return {
5098
- installCommand: command,
5099
- installs: installList.format(names)
5100
- };
5367
+ if (!existsSync(path)) {
5368
+ if (required) throw codemodError(`Create a package.json for this app before migrating to ${required.feature}.`);
5369
+ return {
5370
+ installCommand: command,
5371
+ installs: installList.format(names),
5372
+ followUps: []
5373
+ };
5374
+ }
5101
5375
  const before = await readFile(path, "utf8");
5102
5376
  let manifest;
5103
5377
  try {
@@ -5124,6 +5398,33 @@ async function editPackageJson(cwd, version, change) {
5124
5398
  const map = manifest[section];
5125
5399
  return isDependencyMap(map) && name in map;
5126
5400
  });
5401
+ const followUps = [];
5402
+ if (required) {
5403
+ for (const section of [
5404
+ ...sections$1,
5405
+ "optionalDependencies",
5406
+ "peerDependencies"
5407
+ ]) {
5408
+ const map = manifest[section];
5409
+ if (!isRecord$6(map) || !(required.name in map)) continue;
5410
+ const declared = map[required.name];
5411
+ const resolved = typeof declared === "string" ? await resolveDeclaredRange(cwd, required.name, declared) : void 0;
5412
+ const needs = `${required.feature} needs ${required.name} ${required.range}`;
5413
+ if (resolved === void 0 || validRange(resolved.range) === null) {
5414
+ const source = resolved?.catalog ? `, which pnpm-workspace.yaml sets to ${JSON.stringify(resolved.range)}` : "";
5415
+ followUps.push({
5416
+ file: "package.json",
5417
+ message: `package.json ${section} declares ${required.name} ${JSON.stringify(declared)}${source}. The codemod cannot read it as a version range, so it kept it. ${needs}. Check that it installs such a version.`
5418
+ });
5419
+ continue;
5420
+ }
5421
+ if (outside(resolved.range, required.range)) throw codemodError(`Migration to ${needs}. Update its range in package.json ${section}${resolved.catalog ? ` (pnpm-workspace.yaml sets ${JSON.stringify(declared)} to ${JSON.stringify(resolved.range)})` : ""}, then run the codemod again.`);
5422
+ }
5423
+ if (!installed(required.name)) {
5424
+ dependencies[required.name] = required.range;
5425
+ names.add(required.name);
5426
+ }
5427
+ }
5127
5428
  for (const name of add) if (!installed(name)) dependencies[name] = owners.has(name) && viteHub !== void 0 ? featurePackageSpecifier(name, viteHub) : range;
5128
5429
  for (const [name, supported] of Object.entries(change.within ?? {})) {
5129
5430
  if (!installed(name)) {
@@ -5149,7 +5450,8 @@ async function editPackageJson(cwd, version, change) {
5149
5450
  after
5150
5451
  },
5151
5452
  installCommand: command,
5152
- installs: installList.format(names)
5453
+ installs: installList.format(names),
5454
+ followUps
5153
5455
  };
5154
5456
  }
5155
5457
  // src/shared/removed-module.ts
@@ -6009,7 +6311,6 @@ function optionsAt(program, positions) {
6009
6311
  return options;
6010
6312
  }
6011
6313
  // src/vitehub-options/transform.ts
6012
- /** Top-level Vite keys that owner plugins read before `vitehub()` became the only config place. */
6013
6314
  const removedViteKeys = [
6014
6315
  "agent",
6015
6316
  "auth",
@@ -6024,7 +6325,6 @@ const removedViteKeys = [
6024
6325
  "workflow",
6025
6326
  "workspace"
6026
6327
  ];
6027
- /** The standalone plugin that takes the options of each key as its argument. */
6028
6328
  const ownerPlugins = {
6029
6329
  agent: {
6030
6330
  name: "hubAgent",
@@ -6073,6 +6373,20 @@ const ownerPlugins = {
6073
6373
  package: "workspace"
6074
6374
  }
6075
6375
  };
6376
+ const removedConsoleOptions = {
6377
+ embed: "Apps do not serve the Console page. Open the app in the ViteHub Console at https://console.vitehub.dev.",
6378
+ mcp: "Apps do not serve a Console MCP. Link the app in the ViteHub Console and connect agents to https://console.vitehub.dev/mcp/account.",
6379
+ mcpClient: "The MCP client section of the ViteHub Console connects to MCP servers from the Console server. Remove @modelcontextprotocol/sdk if nothing else imports it, and remove VITEHUB_CONSOLE_MCP_KEY.",
6380
+ origins: "The ViteHub Console signs calls on its server, so apps take no Console calls from browsers.",
6381
+ pill: "The Comments pill loads the Console segment from the ViteHub Console. An app without Comments opens through https://console.vitehub.dev.",
6382
+ signInPage: "People sign in to the ViteHub Console at https://console.vitehub.dev."
6383
+ };
6384
+ const invocationKeys = /* @__PURE__ */ new Set([
6385
+ "databaseUrl",
6386
+ "observations",
6387
+ "retention"
6388
+ ]);
6389
+ const removedConsoleAuth = "console.auth was removed: apps do not sign people in to the Console. Set console: true, link the app in the ViteHub Console at https://console.vitehub.dev, and set the VITEHUB_CONSOLE_KEY_<NAME> line that it shows. Move a check of the person to console.authorize. See https://vitehub.dev/docs/console/migrate";
6076
6390
  const configFunctions = /* @__PURE__ */ new Set([
6077
6391
  "defineConfig",
6078
6392
  "defineNuxtConfig",
@@ -6117,13 +6431,53 @@ function findConfigRoot(program, followUps, file) {
6117
6431
  }
6118
6432
  return value.type === "ObjectExpression" ? value : void 0;
6119
6433
  }
6120
- function property(object, name) {
6434
+ function property$1(object, name) {
6121
6435
  return findProperty(object, name);
6122
6436
  }
6123
6437
  function objectValue$1(node) {
6124
6438
  const value = node ? unwrapExpression(node) : void 0;
6125
6439
  return value?.type === "ObjectExpression" ? value : void 0;
6126
6440
  }
6441
+ function hasOpaqueKeys(object) {
6442
+ return object.properties.some((item) => item.type === "SpreadElement" || keyName(item.key, item.computed) === void 0);
6443
+ }
6444
+ function hasProperty(object, name) {
6445
+ return object.properties.some((item) => item.type !== "SpreadElement" && keyName(item.key, item.computed) === name);
6446
+ }
6447
+ function hasAmbiguousProperty(object, name) {
6448
+ const matches = object.properties.filter((item) => item.type !== "SpreadElement" && keyName(item.key, item.computed) === name);
6449
+ return matches.length > 1 || matches.some((item) => item.type !== "ObjectProperty");
6450
+ }
6451
+ function hasStaticNuxtScopes(root) {
6452
+ if (hasOpaqueKeys(root) || hasProperty(root, "extends") || hasProperty(root, "_extends")) return false;
6453
+ return root.properties.every((item) => {
6454
+ if (item.type === "SpreadElement") return false;
6455
+ const name = keyName(item.key, item.computed);
6456
+ if (!name?.startsWith("$")) return true;
6457
+ const scope = item.type === "ObjectProperty" && objectValue$1(item.value);
6458
+ if (!scope || hasOpaqueKeys(scope) || hasAmbiguousProperty(root, name)) return false;
6459
+ if (name !== "$env") return true;
6460
+ return scope.properties.every((entry) => entry.type === "ObjectProperty" && objectValue$1(entry.value));
6461
+ });
6462
+ }
6463
+ function hasStaticNuxtOptions(scope, entry) {
6464
+ if (hasOpaqueKeys(scope) || hasProperty(scope, "extends") || hasProperty(scope, "_extends")) return false;
6465
+ if (hasAmbiguousProperty(scope, "vitehub") || hasAmbiguousProperty(scope, "modules")) return false;
6466
+ if (hasProperty(scope, "vitehub") && !objectValue$1(property$1(scope, "vitehub")?.value)) return false;
6467
+ const modulesValue = property$1(scope, "modules")?.value;
6468
+ if (!modulesValue) return true;
6469
+ const modules = unwrapExpression(modulesValue);
6470
+ if (modules.type !== "ArrayExpression") return false;
6471
+ return modules.elements.every((element) => {
6472
+ if (!element) return true;
6473
+ const module = unwrapExpression(element);
6474
+ if (module === entry) return module.type !== "ArrayExpression" || !module.elements[1] || Boolean(objectValue$1(module.elements[1]));
6475
+ if (module.type === "StringLiteral") return module.value !== "vite-hub/nuxt";
6476
+ if (module.type !== "ArrayExpression" || !module.elements[0]) return false;
6477
+ const head = unwrapExpression(module.elements[0]);
6478
+ return head.type === "StringLiteral" && head.value !== "vite-hub/nuxt";
6479
+ });
6480
+ }
6127
6481
  function nuxtEnvironmentOverrides(root) {
6128
6482
  return root.properties.flatMap((item) => {
6129
6483
  if (item.type !== "ObjectProperty") return [];
@@ -6152,7 +6506,6 @@ function logsMode(node) {
6152
6506
  if (left && right && left !== "source" && right !== "source") return "possibly-disabled";
6153
6507
  }
6154
6508
  }
6155
- /** Value imports of the expected API, checked against each call's lexical binding. */
6156
6509
  function importedNames(program, sources, imported) {
6157
6510
  const names = /* @__PURE__ */ new Map();
6158
6511
  const imports = typeof imported === "string" ? [imported] : imported;
@@ -6169,7 +6522,6 @@ function callsOf(scope, names, resolveBinding) {
6169
6522
  });
6170
6523
  return calls;
6171
6524
  }
6172
- /** Moves the lines of `text` after the first from the indentation `from` to `to`. */
6173
6525
  function reindent(text, from, to) {
6174
6526
  if (from === to) return text;
6175
6527
  return text.split("\n").map((value, index) => {
@@ -6179,13 +6531,9 @@ function reindent(text, from, to) {
6179
6531
  }).join("\n");
6180
6532
  }
6181
6533
  /**
6182
- * Moves the vite-hub options of a config file. `findRoots` selects other config objects, such as the inline configs of
6183
- * a test file. Without it, the file's default export is the config.
6184
- */
6185
- /**
6186
6534
  * `findOptions` selects the options objects traced from a config that imports this file.
6187
6535
  */
6188
- function migrateViteHubOptions(file, code, findOptions) {
6536
+ function migrateViteHubOptions(file, code, { findOptions, hasLocalNuxtLayers } = {}) {
6189
6537
  const followUps = [];
6190
6538
  const notes = [];
6191
6539
  const unchanged = {
@@ -6233,11 +6581,10 @@ function migrateViteHubOptions(file, code, findOptions) {
6233
6581
  removed.add(node);
6234
6582
  changed = true;
6235
6583
  };
6236
- /** Renames the `from` key of a vite-hub options object to `to`, and keeps its value. */
6237
6584
  const renameKey = (options, from, to, conflict) => {
6238
- const item = property(options, from);
6585
+ const item = property$1(options, from);
6239
6586
  if (!item) return;
6240
- if (property(options, to)) {
6587
+ if (property$1(options, to)) {
6241
6588
  follow(item, conflict);
6242
6589
  return;
6243
6590
  }
@@ -6245,24 +6592,80 @@ function migrateViteHubOptions(file, code, findOptions) {
6245
6592
  else editor.output.overwrite(start(item.key), end(item.key), to);
6246
6593
  changed = true;
6247
6594
  };
6595
+ const moveToInvocations = (options, items) => {
6596
+ const entries = items.map(text);
6597
+ if (importedOptions || !staticNuxtOptions || hasLocalNuxtLayers || options === legacyAgentTarget) return false;
6598
+ if (nuxt && allOptions.some((other) => other !== options && (hasOpaqueKeys(other) || hasProperty(other, "agent") || hasProperty(other, "console")))) return false;
6599
+ if (hasOpaqueKeys(options) || hasAmbiguousProperty(options, "agent") || hasAmbiguousProperty(options, "console")) return false;
6600
+ const consoleOptions = objectValue$1(property$1(options, "console")?.value);
6601
+ if (!consoleOptions || hasOpaqueKeys(consoleOptions) || items.some((item) => hasAmbiguousProperty(consoleOptions, keyName(item.key)))) return false;
6602
+ const agent = property$1(options, "agent");
6603
+ if (!agent) {
6604
+ insertProperties(options, [`agent: { invocations: { ${entries.join(", ")} } }`]);
6605
+ return true;
6606
+ }
6607
+ const agentObject = objectValue$1(agent.value);
6608
+ if (!agentObject || hasOpaqueKeys(agentObject) || hasAmbiguousProperty(agentObject, "invocations")) return false;
6609
+ const invocations = property$1(agentObject, "invocations");
6610
+ if (!invocations) {
6611
+ insertProperties(agentObject, [`invocations: { ${entries.join(", ")} }`]);
6612
+ return true;
6613
+ }
6614
+ const invocationsObject = objectValue$1(invocations.value);
6615
+ if (!invocationsObject || hasOpaqueKeys(invocationsObject)) return false;
6616
+ if (items.some((item) => hasProperty(invocationsObject, keyName(item.key)) || keyName(item.key) === "databaseUrl" && hasProperty(invocationsObject, "store"))) return false;
6617
+ insertProperties(invocationsObject, entries);
6618
+ return true;
6619
+ };
6620
+ const migrateConsoleOptions = (options, consoleOptions) => {
6621
+ const removable = [];
6622
+ const moved = [];
6623
+ let kept = 0;
6624
+ for (const item of consoleOptions.properties) {
6625
+ const key = item.type === "ObjectProperty" ? keyName(item.key, item.computed) : void 0;
6626
+ if (item.type !== "ObjectProperty" || !key) {
6627
+ kept++;
6628
+ continue;
6629
+ }
6630
+ const reason = removedConsoleOptions[key];
6631
+ const authValue = key === "auth" ? unwrapExpression(item.value) : void 0;
6632
+ if (reason || authValue?.type === "StringLiteral" && authValue.value === "token") {
6633
+ removable.push(item);
6634
+ notes.push(`${file}: removed console.${key}. ${reason ?? "Signed calls are the default."}`);
6635
+ } else if (invocationKeys.has(key) && !item.computed && !item.shorthand) moved.push(item);
6636
+ else {
6637
+ kept++;
6638
+ if (invocationKeys.has(key)) follow(item, `console.${key} was removed. Move it to agent: { invocations: { ${key} } } in the vite-hub options by hand.`);
6639
+ else if (authValue && !(authValue.type === "BooleanLiteral" && !authValue.value)) follow(item, removedConsoleAuth);
6640
+ }
6641
+ }
6642
+ if (moved.length) {
6643
+ if (moveToInvocations(options, moved)) {
6644
+ removable.push(...moved);
6645
+ notes.push(`${file}: moved ${moved.map((item) => `console.${keyName(item.key)}`).join(", ")} to agent.invocations.`);
6646
+ } else {
6647
+ kept += moved.length;
6648
+ for (const item of moved) follow(item, `console.${keyName(item.key)} was removed. Move it to agent: { invocations: { ${keyName(item.key)} } } in the vite-hub options by hand.`);
6649
+ }
6650
+ }
6651
+ if (!removable.length) return;
6652
+ if (kept) for (const item of removable) remove(item);
6653
+ else {
6654
+ editor.output.overwrite(start(consoleOptions), end(consoleOptions), environmentOptions.includes(options) ? "{}" : "true");
6655
+ for (const item of removable) removed.add(item);
6656
+ changed = true;
6657
+ }
6658
+ };
6248
6659
  const optionObjects = importedOptions ?? [];
6249
6660
  const environmentOptions = [];
6250
6661
  const emptyCalls = [];
6662
+ let staticNuxtOptions = true;
6251
6663
  if (!importedOptions && nuxt) {
6252
- const key = objectValue$1(property(root, "vitehub")?.value);
6253
- if (key) optionObjects.push(key);
6254
- const entry = findViteHubEntry({
6255
- code,
6256
- fileName: file,
6257
- path: file,
6258
- program,
6259
- root
6260
- });
6261
- const inline = entry?.type === "ArrayExpression" ? objectValue$1(entry.elements[1] ?? void 0) : void 0;
6262
- if (inline) optionObjects.push(inline);
6263
- for (const scope of nuxtEnvironmentOverrides(root)) {
6264
- const options = objectValue$1(property(scope, "vitehub")?.value);
6265
- if (options) environmentOptions.push(options);
6664
+ staticNuxtOptions = hasStaticNuxtScopes(root);
6665
+ for (const scope of [root, ...nuxtEnvironmentOverrides(root)]) {
6666
+ const target = scope === root ? optionObjects : environmentOptions;
6667
+ const options = objectValue$1(property$1(scope, "vitehub")?.value);
6668
+ if (options) target.push(options);
6266
6669
  const entry = findViteHubEntry({
6267
6670
  code,
6268
6671
  fileName: file,
@@ -6271,7 +6674,8 @@ function migrateViteHubOptions(file, code, findOptions) {
6271
6674
  root: scope
6272
6675
  });
6273
6676
  const inline = entry?.type === "ArrayExpression" ? objectValue$1(entry.elements[1] ?? void 0) : void 0;
6274
- if (inline) environmentOptions.push(inline);
6677
+ if (inline) target.push(inline);
6678
+ staticNuxtOptions &&= hasStaticNuxtOptions(scope, entry);
6275
6679
  }
6276
6680
  } else if (!importedOptions) {
6277
6681
  const names = importedNames(program, ["vite-hub"], "vitehub");
@@ -6283,31 +6687,36 @@ function migrateViteHubOptions(file, code, findOptions) {
6283
6687
  else if (!argument) emptyCalls.push(call);
6284
6688
  }
6285
6689
  }
6286
- for (const options of /* @__PURE__ */ new Set([...optionObjects, ...environmentOptions])) {
6690
+ const viteObject = importedOptions ? void 0 : nuxt ? objectValue$1(property$1(root, "vite")?.value) : root;
6691
+ const legacyAgentTarget = viteObject && property$1(viteObject, "agent") && optionObjects.length === 1 && !emptyCalls.length ? optionObjects[0] : void 0;
6692
+ const allOptions = [.../* @__PURE__ */ new Set([...optionObjects, ...environmentOptions])];
6693
+ for (const options of allOptions) {
6287
6694
  renameKey(options, "preset", "host", "Both preset and host are set. Remove preset: host picks the deployment target.");
6288
- const sandbox = property(options, "sandbox");
6695
+ const sandbox = property$1(options, "sandbox");
6289
6696
  const sandboxValue = sandbox ? unwrapExpression(sandbox.value) : void 0;
6290
6697
  if (sandbox && sandboxValue?.type === "BooleanLiteral") {
6291
6698
  if (!sandboxValue.value) remove(sandbox);
6292
6699
  else renameKey(options, "sandbox", "sandboxTask", "Both sandbox and sandboxTask are set. Remove sandbox.");
6293
6700
  } else if (sandbox) follow(sandbox, "sandbox is now sandboxTask. Move these options into sandboxTask by hand.");
6294
- const devtools = property(options, "devtools");
6701
+ const devtools = property$1(options, "devtools");
6295
6702
  if (devtools) {
6296
6703
  remove(devtools);
6297
6704
  notes.push(`${file}: removed devtools. Use the ViteHub Console with console: true.`);
6298
6705
  }
6299
- const cloudflare = property(options, "cloudflare");
6706
+ const cloudflare = property$1(options, "cloudflare");
6300
6707
  if (cloudflare) follow(cloudflare, "cloudflare.secretsFile was removed: `vitehub deploy` uploads the Worker secrets that the app reads. Keep the values in the shell or in .env.production, then remove cloudflare.");
6301
- const contentImportBase = property(options, "contentImportBase");
6708
+ const consoleOptions = objectValue$1(property$1(options, "console")?.value);
6709
+ if (consoleOptions) migrateConsoleOptions(options, consoleOptions);
6710
+ const contentImportBase = property$1(options, "contentImportBase");
6302
6711
  if (contentImportBase) {
6303
6712
  remove(contentImportBase);
6304
6713
  notes.push(`${file}: removed contentImportBase. ViteHub always imports Content from vite-hub/content.`);
6305
6714
  }
6306
- const observability = property(options, "observability");
6715
+ const observability = property$1(options, "observability");
6307
6716
  const observabilityValue = observability ? unwrapExpression(observability.value) : void 0;
6308
6717
  const observabilityObject = objectValue$1(observability?.value);
6309
- const logs = property(options, "logs");
6310
- const nestedLogs = observabilityObject ? property(observabilityObject, "logs") : void 0;
6718
+ const logs = property$1(options, "logs");
6719
+ const nestedLogs = observabilityObject ? property$1(observabilityObject, "logs") : void 0;
6311
6720
  if (observability && observabilityObject && nestedLogs) {
6312
6721
  if (logs) {
6313
6722
  follow(nestedLogs, "Both logs and observability.logs are set. Merge observability.logs into logs by hand.");
@@ -6315,7 +6724,7 @@ function migrateViteHubOptions(file, code, findOptions) {
6315
6724
  }
6316
6725
  const mode = logsMode(nestedLogs.value);
6317
6726
  const onlyLogs = observabilityObject.properties.length === 1;
6318
- const service = property(observabilityObject, "service");
6727
+ const service = property$1(observabilityObject, "service");
6319
6728
  const serviceValue = service && unwrapExpression(service.value);
6320
6729
  const hasService = serviceValue?.type === "StringLiteral" && Boolean(serviceValue.value);
6321
6730
  if (!mode || observabilityObject.properties.some((item) => item.type === "SpreadElement") || mode === "source" && !onlyLogs && !hasService) {
@@ -6337,9 +6746,9 @@ function migrateViteHubOptions(file, code, findOptions) {
6337
6746
  }
6338
6747
  if (observability && !observabilityObject && /\blogs\s*:/u.test(text(observability.value))) follow(observability, "observability is an expression, so the codemod cannot move its logs. Move observability.logs to the top-level logs key by hand.");
6339
6748
  const logsObject = objectValue$1(logs?.value);
6340
- const evlog = logsObject ? property(logsObject, "evlog") : void 0;
6749
+ const evlog = logsObject ? property$1(logsObject, "evlog") : void 0;
6341
6750
  if (!logs || !logsObject || !evlog) continue;
6342
- if (observabilityObject && property(observabilityObject, "evlog")) {
6751
+ if (observabilityObject && property$1(observabilityObject, "evlog")) {
6343
6752
  follow(logs, "Both logs.evlog and observability.evlog are set. Merge logs.evlog into observability.evlog by hand.");
6344
6753
  continue;
6345
6754
  }
@@ -6355,8 +6764,7 @@ function migrateViteHubOptions(file, code, findOptions) {
6355
6764
  changed = true;
6356
6765
  } else remove(evlog);
6357
6766
  }
6358
- const viteObject = importedOptions ? void 0 : nuxt ? objectValue$1(property(root, "vite")?.value) : root;
6359
- const envProperty = viteObject ? property(viteObject, "env") : void 0;
6767
+ const envProperty = viteObject ? property$1(viteObject, "env") : void 0;
6360
6768
  if (envProperty && viteObject) {
6361
6769
  const envValue = unwrapExpression(envProperty.value);
6362
6770
  const envText = text(envValue);
@@ -6366,7 +6774,7 @@ function migrateViteHubOptions(file, code, findOptions) {
6366
6774
  const hubEnvCalls = nuxt ? [] : localHubEnvCalls.length ? localHubEnvCalls : callsOf(program, hubEnvNames, resolveBinding);
6367
6775
  const viteHubTargets = optionObjects.length + emptyCalls.length;
6368
6776
  const moveInto = (target, nested) => {
6369
- const targetEnv = nested ? property(target, "env") : void 0;
6777
+ const targetEnv = nested ? property$1(target, "env") : void 0;
6370
6778
  if (nested && !targetEnv) {
6371
6779
  const indent = editor.propertyIndent(target);
6372
6780
  insertProperties(target, [`env: ${reindent(envText, sourceIndent, indent)}`]);
@@ -6382,7 +6790,7 @@ function migrateViteHubOptions(file, code, findOptions) {
6382
6790
  insertProperties(envOptions, [`...${reindent(envText, sourceIndent, indent)}`]);
6383
6791
  return true;
6384
6792
  }
6385
- const conflict = envValue.properties.find((item) => item.type === "ObjectProperty" && property(envOptions, keyName(item.key, item.computed) ?? ""));
6793
+ const conflict = envValue.properties.find((item) => item.type === "ObjectProperty" && property$1(envOptions, keyName(item.key, item.computed) ?? ""));
6386
6794
  if (conflict) {
6387
6795
  follow(envProperty, `env.${keyName(conflict.key) ?? ""} is set in two places. Merge the declarations into one object by hand.`);
6388
6796
  return false;
@@ -6392,7 +6800,7 @@ function migrateViteHubOptions(file, code, findOptions) {
6392
6800
  return true;
6393
6801
  };
6394
6802
  let moved = false;
6395
- const targetEnv = optionObjects[0] ? property(optionObjects[0], "env") : void 0;
6803
+ const targetEnv = optionObjects[0] ? property$1(optionObjects[0], "env") : void 0;
6396
6804
  const targetEnvValue = targetEnv ? unwrapExpression(targetEnv.value) : void 0;
6397
6805
  const envOff = targetEnvValue?.type === "BooleanLiteral" && !targetEnvValue.value;
6398
6806
  if (viteHubTargets > 1) follow(envProperty, "The config has more than one vite-hub options object. Move env into the right one by hand.");
@@ -6414,19 +6822,19 @@ function migrateViteHubOptions(file, code, findOptions) {
6414
6822
  } else follow(envProperty, "hubEnv() options are not an object literal. Move these declarations into hubEnv() by hand.");
6415
6823
  } else follow(envProperty, nuxt ? "vite.env is no longer read. Move these declarations into the vite-hub/nuxt options, under vitehub.env." : "The top-level Vite env key is no longer read. Move these declarations into vitehub({ env }), or into hubEnv() for a standalone Env plugin.");
6416
6824
  if (moved) {
6417
- const viteProperty = nuxt ? property(root, "vite") : void 0;
6825
+ const viteProperty = nuxt ? property$1(root, "vite") : void 0;
6418
6826
  if (viteProperty && viteObject.properties.length === 1) remove(viteProperty);
6419
6827
  else remove(envProperty);
6420
6828
  }
6421
6829
  }
6422
6830
  if (viteObject) for (const key of removedViteKeys) {
6423
- const item = property(viteObject, key);
6831
+ const item = property$1(viteObject, key);
6424
6832
  if (!item || removed.has(item)) continue;
6425
6833
  const value = unwrapExpression(item.value);
6426
6834
  const sourceIndent = indentAt(code, start(item));
6427
6835
  const plugin = ownerPlugins[key];
6428
6836
  const pluginCalls = plugin && !nuxt ? callsOf(root, importedNames(program, [`@vite-hub/${plugin.package}/vite`, `vite-hub/${plugin.package}/vite`], plugin.previousName ? [plugin.name, plugin.previousName] : plugin.name), resolveBinding) : [];
6429
- if (key !== "vitehub" && optionObjects.length === 1 && !emptyCalls.length && !property(optionObjects[0], key)) {
6837
+ if (key !== "vitehub" && optionObjects.length === 1 && !emptyCalls.length && !property$1(optionObjects[0], key)) {
6430
6838
  insertProperties(optionObjects[0], [`${key}: ${reindent(text(value), sourceIndent, editor.propertyIndent(optionObjects[0]))}`]);
6431
6839
  remove(item);
6432
6840
  } else if (!optionObjects.length && !emptyCalls.length && pluginCalls.length === 1 && !pluginCalls[0].arguments.length) {
@@ -8686,6 +9094,10 @@ const nuxtCron = {
8686
9094
  function isRecord$5(value) {
8687
9095
  return typeof value === "object" && value !== null && !Array.isArray(value);
8688
9096
  }
9097
+ /** A non-null object or a function that is not an array. */
9098
+ function isRecordOrFunction(value) {
9099
+ return Object(value) === value && !Array.isArray(value);
9100
+ }
8689
9101
  // src/nuxt-safe-runtime-config/fields.ts
8690
9102
  /** Nuxt's rule: `NUXT_` and the upper snake case path. Public paths start with `PUBLIC`. */
8691
9103
  function nuxtVariableName(section, configPath) {
@@ -9447,6 +9859,21 @@ function processEnvName$1(node) {
9447
9859
  if (keyName(object.property) !== "env") return void 0;
9448
9860
  return keyName(value.property, value.computed);
9449
9861
  }
9862
+ function jsonLiteral(node) {
9863
+ const value = unwrapExpression(node);
9864
+ if (value.type === "NullLiteral") return null;
9865
+ if (value.type === "ArrayExpression") {
9866
+ const items = value.elements.map((element) => element && element.type !== "SpreadElement" ? jsonLiteral(element) : void 0);
9867
+ return items.every((item) => item !== void 0) ? items : void 0;
9868
+ }
9869
+ if (value.type === "ObjectExpression") {
9870
+ const object = staticOptionsObject(value);
9871
+ if (!object) return void 0;
9872
+ const entries = object.properties.map((entry) => entry.type === "ObjectProperty" ? [keyName(entry.key, entry.computed), jsonLiteral(entry.value)] : [void 0, void 0]);
9873
+ return entries.every((entry) => entry[0] !== void 0 && entry[0] !== "__proto__" && entry[1] !== void 0) ? Object.fromEntries(entries) : void 0;
9874
+ }
9875
+ return literalValue(value);
9876
+ }
9450
9877
  function readRuntimeConfigValue(code, property) {
9451
9878
  const node = unwrapExpression(property.value);
9452
9879
  const base = {
@@ -9458,6 +9885,12 @@ function readRuntimeConfigValue(code, property) {
9458
9885
  ...base,
9459
9886
  literal
9460
9887
  };
9888
+ const json = node.type === "ArrayExpression" ? jsonLiteral(node) : void 0;
9889
+ if (Array.isArray(json)) return {
9890
+ ...base,
9891
+ json,
9892
+ expression: code.slice(start(node), end(node))
9893
+ };
9461
9894
  const envName = processEnvName$1(node);
9462
9895
  if (envName) return {
9463
9896
  ...base,
@@ -9492,7 +9925,15 @@ function readRuntimeConfig(config) {
9492
9925
  if (!key) continue;
9493
9926
  const value = unwrapExpression(property.value);
9494
9927
  if (value.type === "ObjectExpression") {
9928
+ const json = jsonLiteral(value);
9929
+ const expression = config.code.slice(start(value), end(value));
9495
9930
  groups.add([...path, key].join("."));
9931
+ values.set([...path, key].join("."), {
9932
+ property,
9933
+ line: line(property),
9934
+ expression,
9935
+ ...json !== null && typeof json === "object" ? { json } : {}
9936
+ });
9496
9937
  visit(value, [...path, key]);
9497
9938
  } else values.set([...path, key].join("."), readRuntimeConfigValue(config.code, property));
9498
9939
  }
@@ -9518,24 +9959,34 @@ async function loadSchemaModule(cwd, specifier) {
9518
9959
  }
9519
9960
  }
9520
9961
  // src/nuxt-safe-runtime-config/config-edit.ts
9521
- function declarationCode(field, envName, style) {
9962
+ function defaultCode(value, style) {
9963
+ if (Array.isArray(value)) return `[${value.map((item) => item === null ? "null" : defaultCode(item, style)).join(", ")}]`;
9964
+ if (typeof value === "object") {
9965
+ const entries = Object.entries(value).map(([key, item]) => `${propertyKey(key, style)}: ${item === null ? "null" : defaultCode(item, style)}`);
9966
+ return entries.length ? `{ ${entries.join(", ")} }` : "{}";
9967
+ }
9968
+ return literal(value, style);
9969
+ }
9970
+ /** Renders one Env declaration. `schema` is the code of the field schema, such as `env.schemaFrom(...)`. */
9971
+ function declarationCode(field, envName, style, schema) {
9522
9972
  const options = [];
9523
- if (field.default !== void 0) options.push(`default: ${literal(field.default, style)}`);
9973
+ if (field.default !== void 0) options.push(`default: ${defaultCode(field.default, style)}`);
9524
9974
  if (field.section === "public") options.push(`mode: ${quoteString("build", style)}`);
9525
9975
  if (!field.required && field.default === void 0) options.push("optional: true");
9976
+ if (schema && field.kind !== "json") options.push(`schema: ${schema}`);
9526
9977
  if (field.secret) options.push("secret: true");
9527
9978
  const names = [.../* @__PURE__ */ new Set([field.variable, ...field.extraVariables ?? []])];
9528
9979
  const source = names.length === 1 ? quoteString(field.variable, style) : `[${names.map((name) => quoteString(name, style)).join(", ")}]`;
9529
9980
  options.push(`source: ${envName}.source(${source})`);
9530
- return `${field.kind === "string" ? envName : `${envName}.${field.kind}`}(${field.kind === "enum" ? `[${(field.values ?? []).map((value) => quoteString(value, style)).join(", ")}], ` : ""}{ ${options.join(", ")} })`;
9981
+ return `${field.kind === "string" ? envName : `${envName}.${field.kind}`}(${field.kind === "enum" ? `[${(field.values ?? []).map((value) => quoteString(value, style)).join(", ")}], ` : ""}${field.kind === "json" && schema ? `${schema}, ` : ""}{ ${options.join(", ")} })`;
9531
9982
  }
9532
- function sectionTree(fields, envName, style) {
9983
+ function sectionTree(fields, envName, style, schemas) {
9533
9984
  const tree = /* @__PURE__ */ new Map();
9534
9985
  for (const field of fields) {
9535
9986
  let node = tree;
9536
9987
  field.envPath.forEach((segment, index) => {
9537
9988
  if (index === field.envPath.length - 1) {
9538
- node.set(segment, declarationCode(field, envName, style));
9989
+ node.set(segment, declarationCode(field, envName, style, schemas.get(field)));
9539
9990
  return;
9540
9991
  }
9541
9992
  const child = node.get(segment);
@@ -9550,7 +10001,7 @@ function renderTree(tree, indent, unit, style) {
9550
10001
  return `{\n${[...tree].map(([key, value]) => typeof value === "string" ? `${indent}${unit}${propertyKey(key, style)}: ${value},` : `${indent}${unit}${propertyKey(key, style)}: ${renderTree(value, `${indent}${unit}`, unit, style)},`).join("\n")}\n${indent}}`;
9551
10002
  }
9552
10003
  /** Renders the value of `vitehub.env`. `indent` is the indentation of the `env` key line. */
9553
- function envExpression(env, envName, indent, style) {
10004
+ function envExpression(env, envName, indent, style, schemas = /* @__PURE__ */ new Map()) {
9554
10005
  if (env.kind === "env-schema") {
9555
10006
  const file = /^\.\.?\//.test(env.file) ? env.file : `./${env.file}`;
9556
10007
  const options = [`prefix: ${quoteString("NUXT_", style)}`];
@@ -9561,8 +10012,8 @@ function envExpression(env, envName, indent, style) {
9561
10012
  const sections = /* @__PURE__ */ new Map();
9562
10013
  const publicFields = env.fields.filter((field) => field.section === "public");
9563
10014
  const serverFields = env.fields.filter((field) => field.section === "server");
9564
- if (publicFields.length) sections.set("public", sectionTree(publicFields, envName, style));
9565
- if (serverFields.length) sections.set("server", sectionTree(serverFields, envName, style));
10015
+ if (publicFields.length) sections.set("public", sectionTree(publicFields, envName, style, schemas));
10016
+ if (serverFields.length) sections.set("server", sectionTree(serverFields, envName, style, schemas));
9566
10017
  return renderTree(sections, indent, style.indent, style);
9567
10018
  }
9568
10019
  /** Edits nuxt.config: swaps the module, removes `safeRuntimeConfig` and migrated keys, and adds `vitehub.env`. */
@@ -9595,26 +10046,44 @@ function editNuxtConfig(input) {
9595
10046
  imports.push(`import { ${specifier} } from ${quoteString("vite-hub/env", style)}${semicolon}`);
9596
10047
  } else {
9597
10048
  if (!bindingFree(config, "envSchema")) throw codemodError(`${config.fileName} already declares envSchema. Rename it, then run the codemod again.`);
9598
- imports.push(`import { envSchema } from ${quoteString("@vite-hub/env/vite", style)}${semicolon}`);
10049
+ imports.push(`import { envSchema } from ${quoteString("vite-hub/env/vite", style)}${semicolon}`);
10050
+ }
10051
+ const schemas = /* @__PURE__ */ new Map();
10052
+ if (input.env.kind === "fields" && input.schemaModule) {
10053
+ const { exports, importPath, runtimePath } = input.schemaModule;
10054
+ const specifiers = [];
10055
+ const taken = /* @__PURE__ */ new Set([envName]);
10056
+ for (const [field, name] of exports) {
10057
+ if (field.section === "server") {
10058
+ schemas.set(field, `${envName}.schemaFrom(${quoteString(runtimePath, style)}, ${quoteString(name, style)})`);
10059
+ continue;
10060
+ }
10061
+ let local = name;
10062
+ for (let index = 2; taken.has(local) || !bindingFree(config, local); index++) local = `${name}${index}`;
10063
+ taken.add(local);
10064
+ schemas.set(field, local);
10065
+ specifiers.push(local === name ? name : `${name} as ${local}`);
10066
+ }
10067
+ if (specifiers.length) imports.push(`import { ${specifiers.join(", ")} } from ${quoteString(importPath, style)}${semicolon}`);
9599
10068
  }
9600
10069
  const env = input.env;
9601
10070
  const { host, hostNote } = addViteHubOptions(editor, config, {
9602
10071
  options: [{
9603
10072
  key: "env",
9604
- value: (indent) => envExpression(env, envName, indent, style),
10073
+ value: (indent) => envExpression(env, envName, indent, style, schemas),
9605
10074
  label: "the Env declarations"
9606
10075
  }],
9607
10076
  rootEntries,
9608
10077
  removedRootProperties
9609
10078
  });
9610
10079
  editor.removeUnusedBindings();
9611
- for (const text of imports) editor.addImport(text);
10080
+ editor.addImport(imports.join("\n"));
9612
10081
  const code = editor.output.toString();
9613
10082
  return {
9614
10083
  code,
9615
10084
  host,
9616
10085
  hostNote,
9617
- imports: input.env.kind === "fields" ? ["vite-hub/env"] : ["@vite-hub/env/vite"],
10086
+ imports: input.env.kind === "fields" ? ["vite-hub/env"] : ["vite-hub/env/vite"],
9618
10087
  removedImports: editor.removedImports,
9619
10088
  lineOf: createLineResolver(code)
9620
10089
  };
@@ -9706,62 +10175,240 @@ function planFromEnvFile(keys, nuxtPaths, file) {
9706
10175
  }
9707
10176
  return plan;
9708
10177
  }
10178
+ // src/nuxt-safe-runtime-config/nitro-config.ts
10179
+ const configNames = [
10180
+ "nitro.config.ts",
10181
+ "nitro.config.mts",
10182
+ "nitro.config.cts",
10183
+ "nitro.config.js",
10184
+ "nitro.config.mjs",
10185
+ "nitro.config.cjs"
10186
+ ];
10187
+ /** The file name of the project's nitro.config, or `undefined` when it has none. */
10188
+ function findNitroConfigName(cwd) {
10189
+ return configNames.find((name) => existsSync(join(cwd, name)));
10190
+ }
10191
+ function packageName$1(name, specifier) {
10192
+ return /^npm:((?:@[^/]+\/)?[^@]+)(?:@|$)/.exec(specifier)?.[1] ?? name;
10193
+ }
10194
+ /** Stops before planning edits for a standalone Nitro app that declares Nitro 2, including mixed manifests. */
10195
+ async function assertNotNitro2(cwd, codemod) {
10196
+ if (findNuxtConfigName(cwd)) return;
10197
+ const config = findNitroConfigName(cwd);
10198
+ if (!config) return;
10199
+ const dependencies = [...await readDependencies(cwd)];
10200
+ const legacy = dependencies.find(([name, version]) => packageName$1(name, version) === "nitropack");
10201
+ if (!legacy) return;
10202
+ const [name, version] = legacy;
10203
+ const mixed = dependencies.some(([name, version]) => packageName$1(name, version) === "nitro");
10204
+ const reason = mixed ? `Cannot determine the Nitro version for ${config}: package.json declares both nitro and nitropack.` : `${config} belongs to a Nitro 2 app: package.json requires ${name} "${version}".`;
10205
+ throw codemodsErrorDiagnostics.CODEMODS_NITRO_UNSUPPORTED({
10206
+ codemod,
10207
+ reason,
10208
+ mixed
10209
+ });
10210
+ }
9709
10211
  // src/nuxt-safe-runtime-config/field-schema.ts
9710
10212
  function isFieldSchema(value) {
9711
- const standard = isRecord$5(value) ? value["~standard"] : void 0;
10213
+ const standard = isRecordOrFunction(value) ? value["~standard"] : void 0;
9712
10214
  return isRecord$5(standard) && typeof standard.vendor === "string" && typeof standard.validate === "function";
9713
10215
  }
9714
- function valibotObject(schema, seen = /* @__PURE__ */ new Set()) {
10216
+ const property = (name) => ({
10217
+ kind: "property",
10218
+ name
10219
+ });
10220
+ const call = (name, ...args) => ({
10221
+ kind: "call",
10222
+ name,
10223
+ args
10224
+ });
10225
+ function runStep(target, step) {
10226
+ if (typeof target !== "object" && typeof target !== "function" || target === null) return void 0;
10227
+ try {
10228
+ const value = Reflect.get(target, step.name);
10229
+ if (step.kind === "property") return value;
10230
+ return typeof value === "function" ? Reflect.apply(value, target, step.args) : void 0;
10231
+ } catch {
10232
+ return;
10233
+ }
10234
+ }
10235
+ /** Runs the steps on `schema` the same way the generated module reads them. */
10236
+ function runSteps(schema, steps) {
10237
+ return steps.reduce((target, step) => runStep(target, step), schema);
10238
+ }
10239
+ function firstMatch(schema, expected, candidates) {
10240
+ const steps = candidates.find((entry) => runSteps(schema, entry) === expected);
10241
+ return steps ? {
10242
+ value: expected,
10243
+ steps
10244
+ } : void 0;
10245
+ }
10246
+ function firstValue(schema, candidates, accept) {
10247
+ for (const steps of candidates) {
10248
+ const value = runSteps(schema, steps);
10249
+ if (accept(value)) return {
10250
+ value,
10251
+ steps
10252
+ };
10253
+ }
10254
+ }
10255
+ function joinHop(hop, child) {
10256
+ const inner = hop && isRecord$5(hop.value) ? child(hop.value) : void 0;
10257
+ return hop && inner && {
10258
+ value: inner.value,
10259
+ steps: [...hop.steps, ...inner.steps]
10260
+ };
10261
+ }
10262
+ function valibotChild(schema, key, seen = /* @__PURE__ */ new Set()) {
9715
10263
  if (seen.has(schema)) return void 0;
9716
10264
  seen.add(schema);
9717
- if (isRecord$5(schema.entries)) return schema.entries;
9718
- const inner = schema.type === "lazy" && typeof schema.getter === "function" ? Reflect.apply(schema.getter, schema, [void 0]) : schema.wrapped;
9719
- return isRecord$5(inner) ? valibotObject(inner, seen) : void 0;
10265
+ if (isRecord$5(schema.entries)) return Object.hasOwn(schema.entries, key) ? {
10266
+ value: schema.entries[key],
10267
+ steps: [property("entries"), property(key)]
10268
+ } : void 0;
10269
+ return joinHop(schema.type === "lazy" && typeof schema.getter === "function" ? firstValue(schema, [[call("getter")]], isRecord$5) : isRecord$5(schema.wrapped) ? {
10270
+ value: schema.wrapped,
10271
+ steps: [property("wrapped")]
10272
+ } : void 0, (inner) => valibotChild(inner, key, seen));
10273
+ }
10274
+ function isZodSchema(value) {
10275
+ return isRecord$5(value) && isRecord$5(value._zod);
9720
10276
  }
9721
- function zodObject(schema, seen = /* @__PURE__ */ new Set()) {
10277
+ function zodChild(schema, key, seen = /* @__PURE__ */ new Set()) {
9722
10278
  if (seen.has(schema)) return void 0;
9723
10279
  seen.add(schema);
9724
10280
  const definition = isRecord$5(schema._zod) && isRecord$5(schema._zod.def) ? schema._zod.def : void 0;
9725
10281
  if (!definition) return void 0;
9726
- if (definition.type === "object" && isRecord$5(definition.shape)) return definition.shape;
9727
- let inner = definition.type === "pipe" ? definition.in : definition.innerType;
9728
- if (definition.type === "lazy" && typeof definition.getter === "function") inner = Reflect.apply(definition.getter, definition, []);
9729
- return isRecord$5(inner) ? zodObject(inner, seen) : void 0;
10282
+ if (definition.type === "object" && isRecord$5(definition.shape)) {
10283
+ if (!Object.hasOwn(definition.shape, key)) return void 0;
10284
+ const shape = firstMatch(schema, definition.shape, [
10285
+ [property("shape")],
10286
+ [property("def"), property("shape")],
10287
+ [
10288
+ property("_zod"),
10289
+ property("def"),
10290
+ property("shape")
10291
+ ]
10292
+ ]);
10293
+ return shape && {
10294
+ value: definition.shape[key],
10295
+ steps: [...shape.steps, property(key)]
10296
+ };
10297
+ }
10298
+ if (definition.type === "lazy" && typeof definition.getter === "function") return joinHop(firstValue(schema, [
10299
+ [call("unwrap")],
10300
+ [property("def"), call("getter")],
10301
+ [
10302
+ property("_zod"),
10303
+ property("def"),
10304
+ call("getter")
10305
+ ]
10306
+ ], isZodSchema), (inner) => zodChild(inner, key, seen));
10307
+ const name = definition.type === "pipe" ? "in" : "innerType";
10308
+ const inner = definition[name];
10309
+ if (!isRecord$5(inner)) return void 0;
10310
+ return joinHop(firstMatch(schema, inner, [
10311
+ ...name === "innerType" ? [[call("unwrap")]] : [[property("in")]],
10312
+ [property("def"), property(name)],
10313
+ [
10314
+ property("_zod"),
10315
+ property("def"),
10316
+ property(name)
10317
+ ]
10318
+ ]), (inner) => zodChild(inner, key, seen));
9730
10319
  }
9731
10320
  const zod3Wrappers = {
9732
- ZodBranded: "type",
9733
- ZodCatch: "innerType",
9734
- ZodDefault: "innerType",
9735
- ZodEffects: "schema",
9736
- ZodNullable: "innerType",
9737
- ZodOptional: "innerType",
9738
- ZodPipeline: "in",
9739
- ZodReadonly: "innerType"
10321
+ ZodBranded: {
10322
+ inner: "type",
10323
+ methods: ["unwrap"]
10324
+ },
10325
+ ZodCatch: {
10326
+ inner: "innerType",
10327
+ methods: ["removeCatch"]
10328
+ },
10329
+ ZodDefault: {
10330
+ inner: "innerType",
10331
+ methods: ["removeDefault"]
10332
+ },
10333
+ ZodEffects: {
10334
+ inner: "schema",
10335
+ methods: ["innerType"]
10336
+ },
10337
+ ZodNullable: {
10338
+ inner: "innerType",
10339
+ methods: ["unwrap"]
10340
+ },
10341
+ ZodOptional: {
10342
+ inner: "innerType",
10343
+ methods: ["unwrap"]
10344
+ },
10345
+ ZodPipeline: {
10346
+ inner: "in",
10347
+ methods: []
10348
+ },
10349
+ ZodReadonly: {
10350
+ inner: "innerType",
10351
+ methods: ["unwrap"]
10352
+ }
9740
10353
  };
9741
- function zod3Object(schema) {
10354
+ function zod3Child(schema, key) {
9742
10355
  const definition = isRecord$5(schema._def) && typeof schema._def.typeName === "string" ? schema._def : void 0;
9743
10356
  if (!definition) return void 0;
9744
10357
  if (definition.typeName === "ZodObject") {
9745
10358
  const shape = typeof definition.shape === "function" ? Reflect.apply(definition.shape, definition, []) : definition.shape;
9746
- return isRecord$5(shape) ? shape : void 0;
10359
+ if (!isRecord$5(shape) || !Object.hasOwn(shape, key)) return void 0;
10360
+ const hop = firstMatch(schema, shape, [[property("shape")], [property("_def"), call("shape")]]);
10361
+ return hop && {
10362
+ value: shape[key],
10363
+ steps: [...hop.steps, property(key)]
10364
+ };
9747
10365
  }
9748
- const inner = zod3Wrappers[String(definition.typeName)];
9749
- const wrapped = inner ? definition[inner] : void 0;
9750
- return isRecord$5(wrapped) ? zod3Object(wrapped) : void 0;
10366
+ const wrapper = zod3Wrappers[String(definition.typeName)];
10367
+ const inner = wrapper ? definition[wrapper.inner] : void 0;
10368
+ if (!wrapper || !isRecord$5(inner)) return void 0;
10369
+ const hop = firstMatch(schema, inner, [...wrapper.methods.map((method) => [call(method)]), [property("_def"), property(wrapper.inner)]]);
10370
+ const child = hop && zod3Child(inner, key);
10371
+ return hop && child && {
10372
+ value: child.value,
10373
+ steps: [...hop.steps, ...child.steps]
10374
+ };
10375
+ }
10376
+ function arktypeChild(schema, key) {
10377
+ const step = call("get", key);
10378
+ const value = runSteps(schema, [step]);
10379
+ return isFieldSchema(value) ? {
10380
+ value,
10381
+ steps: [step]
10382
+ } : void 0;
9751
10383
  }
9752
10384
  function childSchema(schema, key) {
9753
10385
  const vendor = isFieldSchema(schema) ? schema["~standard"].vendor : void 0;
9754
- const entries = vendor === "valibot" ? valibotObject(schema) : vendor === "zod" ? zodObject(schema) ?? zod3Object(schema) : void 0;
9755
- return entries && Object.hasOwn(entries, key) ? entries[key] : void 0;
10386
+ if (vendor === "valibot") return valibotChild(schema, key);
10387
+ if (vendor === "zod") return zodChild(schema, key) ?? zod3Child(schema, key);
10388
+ if (vendor === "arktype") return arktypeChild(schema, key);
9756
10389
  }
9757
10390
  /**
9758
- * The Standard Schema of one `runtimeConfig` field in the `$schema` object, by its path in `runtimeConfig`,
9759
- * such as `["public", "apiBase"]`. Returns `undefined` when the vendor's object shape cannot be read.
10391
+ * The Standard Schema of one `runtimeConfig` field in the `$schema` object, by its path in `runtimeConfig`, such as
10392
+ * `["public", "apiBase"]`, with the property reads and calls that return it. Each step is checked on the schema.
10393
+ * Returns `undefined` when the vendor's object shape cannot be read.
9760
10394
  */
9761
- function fieldSchema(schema, path) {
10395
+ function fieldAccess(schema, path) {
9762
10396
  let current = schema;
9763
- for (const key of path) current = isRecord$5(current) ? childSchema(current, key) : void 0;
9764
- return isFieldSchema(current) ? current : void 0;
10397
+ const steps = [];
10398
+ for (const key of path) {
10399
+ const hop = isRecordOrFunction(current) ? childSchema(current, key) : void 0;
10400
+ if (!hop) return void 0;
10401
+ current = hop.value;
10402
+ steps.push(...hop.steps);
10403
+ }
10404
+ return isFieldSchema(current) ? {
10405
+ schema: current,
10406
+ steps
10407
+ } : void 0;
10408
+ }
10409
+ /** The Standard Schema of one `runtimeConfig` field in the `$schema` object. See `fieldAccess()`. */
10410
+ function fieldSchema(schema, path) {
10411
+ return fieldAccess(schema, path)?.schema;
9765
10412
  }
9766
10413
  async function standardRejection(schema, value) {
9767
10414
  try {
@@ -9811,6 +10458,38 @@ async function defaultRejection(check) {
9811
10458
  if (typeof check.value === "string") return stringRejection(check.node, check.value);
9812
10459
  if (typeof check.value === "number") return numberRejection(check.node, check.value);
9813
10460
  }
10461
+ function isPromiseLike(value) {
10462
+ return isRecordOrFunction(value) && typeof value.then === "function";
10463
+ }
10464
+ function hasAsyncPart(value, seen) {
10465
+ if (seen.has(value) || !Array.isArray(value) && !isRecord$5(value)) return false;
10466
+ seen.add(value);
10467
+ if (isRecord$5(value) && value.async === true && typeof value.kind === "string") return true;
10468
+ return Object.values(value).some((entry) => hasAsyncPart(entry, seen));
10469
+ }
10470
+ function validateSync(schema, input) {
10471
+ let result;
10472
+ try {
10473
+ result = schema["~standard"].validate(input);
10474
+ } catch {
10475
+ return;
10476
+ }
10477
+ if (isPromiseLike(result)) {
10478
+ Promise.resolve(result).catch(() => void 0);
10479
+ return "async";
10480
+ }
10481
+ return isRecord$5(result) && !Array.isArray(result.issues) && "value" in result ? { value: result.value } : void 0;
10482
+ }
10483
+ /** True when the schema has a Valibot async part, or returns a Promise for one of `inputs`. Env runs schemas synchronously. */
10484
+ function isAsyncSchema(schema, inputs) {
10485
+ if (schema["~standard"].vendor === "valibot" && hasAsyncPart(schema, /* @__PURE__ */ new Set())) return true;
10486
+ return inputs.some((input) => validateSync(schema, input) === "async");
10487
+ }
10488
+ /** True when the schema returns a value for missing input, such as `v.optional(schema, default)` or `.default()`. */
10489
+ function hasSchemaDefault(schema) {
10490
+ const result = validateSync(schema, void 0);
10491
+ return typeof result === "object" && result.value !== void 0;
10492
+ }
9814
10493
  // src/nuxt-safe-runtime-config/schema.ts
9815
10494
  function isRecord$4(value) {
9816
10495
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -9923,8 +10602,8 @@ function zodPackageJsonSchema(schema, cwd) {
9923
10602
  * the converter load the app's own Zod for Zod 4 versions before 4.2.
9924
10603
  */
9925
10604
  async function schemaToJsonSchema(schema, cwd) {
9926
- const standard = isRecord$4(schema) ? schema["~standard"] : void 0;
9927
- if (!isRecord$4(schema) || !isRecord$4(standard)) throw codemodError("The $schema is not a Standard Schema. Use a Valibot, Zod, or ArkType schema.");
10605
+ const standard = isRecordOrFunction(schema) ? schema["~standard"] : void 0;
10606
+ if (!isRecordOrFunction(schema) || !isRecord$4(standard)) throw codemodError("The $schema is not a Standard Schema. Use a Valibot, Zod, or ArkType schema.");
9928
10607
  const vendor = typeof standard.vendor === "string" ? standard.vendor : "unknown";
9929
10608
  let nativeError;
9930
10609
  const converter = isRecord$4(standard.jsonSchema) ? standard.jsonSchema.input : void 0;
@@ -10018,7 +10697,7 @@ function valibotIssues(schema, path, issues) {
10018
10697
  if (Array.isArray(schema.pipe)) for (const action of schema.pipe.slice(1)) {
10019
10698
  if (!isRecord$4(action) || typeof action.type !== "string") continue;
10020
10699
  if (action.kind === "transformation") addIssue(issues, path, `the Valibot ${action.type} action`);
10021
- else if (action.kind === "validation" && !valibotJsonValidations.has(action.type)) addIssue(issues, path, `the Valibot ${action.type} check`);
10700
+ else if (action.kind === "validation" && !valibotJsonValidations.has(action.type)) addIssue(issues, path, action.type === "check" ? "a Valibot check" : `the Valibot ${action.type} check`);
10022
10701
  }
10023
10702
  if (isRecord$4(schema.entries) && [
10024
10703
  "object",
@@ -10092,12 +10771,31 @@ function zod3Issues(schema, path, issues) {
10092
10771
  else if (type === "ZodOptional" || type === "ZodNullable" || type === "ZodDefault" || type === "ZodReadonly") zod3Issues(definition.innerType, path, issues);
10093
10772
  else if (type === "ZodCatch") addIssue(issues, path, "a Zod catch fallback, which accepts missing or invalid input");
10094
10773
  }
10774
+ function arktypeNarrows(json) {
10775
+ if (Array.isArray(json)) return json.some(arktypeNarrows);
10776
+ if (!isRecord$4(json)) return false;
10777
+ if (Array.isArray(json.predicate) && json.predicate.some((entry) => typeof entry === "string")) return true;
10778
+ return Object.values(json).some(arktypeNarrows);
10779
+ }
10780
+ function arktypeIssues(schema, path, issues) {
10781
+ if (!isRecordOrFunction(schema) || !isRecordOrFunction(schema.internal)) return;
10782
+ const json = schema.json;
10783
+ if (!(schema.internal.kind !== "morph" && isRecord$4(json) && json.domain === "object" && json.proto === void 0)) {
10784
+ if (schema.internal.includesTransform === true) addIssue(issues, path, "an ArkType morph");
10785
+ if (arktypeNarrows(json)) addIssue(issues, path, "an ArkType narrow");
10786
+ return;
10787
+ }
10788
+ if (Array.isArray(json.predicate) && json.predicate.some((entry) => typeof entry === "string")) addIssue(issues, path, "an ArkType narrow");
10789
+ const props = schema.props;
10790
+ for (const prop of Array.isArray(props) ? props : []) if (isRecordOrFunction(prop) && typeof prop.key === "string") arktypeIssues(prop.value, [...path, prop.key], issues);
10791
+ }
10095
10792
  /** Rules that JSON Schema cannot hold, such as transforms and custom checks, by dotted path. `""` is the schema root. */
10096
10793
  function schemaIssues(schema) {
10097
10794
  const issues = /* @__PURE__ */ new Map();
10098
10795
  if (isValibotSchema(schema)) valibotIssues(schema, [], issues);
10099
10796
  else if (zodDefinition(schema)) zodIssues(schema, [], issues);
10100
10797
  else if (zod3Definition(schema)) zod3Issues(schema, [], issues);
10798
+ else if (isRecordOrFunction(schema) && isRecord$4(schema["~standard"]) && schema["~standard"].vendor === "arktype") arktypeIssues(schema, [], issues);
10101
10799
  return issues;
10102
10800
  }
10103
10801
  function resolveReference(root, node) {
@@ -10222,7 +10920,46 @@ function coerceDefault(value, field) {
10222
10920
  return text;
10223
10921
  }
10224
10922
  function literalText(value) {
10225
- return typeof value === "string" ? JSON.stringify(value) : String(value);
10923
+ return typeof value === "string" || typeof value === "object" ? JSON.stringify(value) : String(value);
10924
+ }
10925
+ const valibotJsonInputs = /* @__PURE__ */ new Set([
10926
+ "array",
10927
+ "bigint",
10928
+ "boolean",
10929
+ "loose_object",
10930
+ "loose_tuple",
10931
+ "number",
10932
+ "object",
10933
+ "object_with_rest",
10934
+ "record",
10935
+ "strict_object",
10936
+ "strict_tuple",
10937
+ "tuple",
10938
+ "tuple_with_rest"
10939
+ ]);
10940
+ function valibotInputType(schema) {
10941
+ let current = schema;
10942
+ while (isRecord$4(current) && isRecord$4(current.wrapped)) current = current.wrapped;
10943
+ return isValibotSchema(schema) && isRecord$4(current) && typeof current.type === "string" ? current.type : void 0;
10944
+ }
10945
+ function plainFieldKind(leaf) {
10946
+ if (leaf.kind === "integer") return "number";
10947
+ return leaf.kind === "boolean" || leaf.kind === "enum" || leaf.kind === "number" || leaf.kind === "string" ? leaf.kind : void 0;
10948
+ }
10949
+ function schemaFieldKind(access, leaf) {
10950
+ const valibot = valibotInputType(access.schema);
10951
+ if (valibot === "string") return "string";
10952
+ if (valibot && valibotJsonInputs.has(valibot)) return "json";
10953
+ if (valibot && ![
10954
+ "enum",
10955
+ "literal",
10956
+ "picklist"
10957
+ ].includes(valibot)) return void 0;
10958
+ if (leaf.kind === "string" || leaf.kind === "enum") return "string";
10959
+ return leaf.kind === "union" || leaf.kind === "unknown" ? void 0 : "json";
10960
+ }
10961
+ function schemaDefault(value, kind) {
10962
+ return kind === "json" ? value : String(value);
10226
10963
  }
10227
10964
  function coerceRuntimeInput(value, leaf) {
10228
10965
  const kind = leaf.kind === "integer" ? "number" : leaf.kind;
@@ -10252,7 +10989,8 @@ async function planFromJsonSchema(input) {
10252
10989
  const plan = {
10253
10990
  fields: [],
10254
10991
  unmigrated: [],
10255
- followUps: []
10992
+ followUps: [],
10993
+ needsSchemaModule: false
10256
10994
  };
10257
10995
  const follow = (message, anchor) => plan.followUps.push({
10258
10996
  message,
@@ -10271,6 +11009,7 @@ async function planFromJsonSchema(input) {
10271
11009
  section,
10272
11010
  configPath
10273
11011
  });
11012
+ const schemaPath = section === "public" ? ["public", ...configPath] : configPath;
10274
11013
  const runtimeValue = input.runtimeConfig.get(label);
10275
11014
  const leaf = describeLeaf(input.jsonSchema, isRecord$4(node) ? node : {});
10276
11015
  const objectProperties = leaf.node.properties;
@@ -10281,70 +11020,112 @@ async function planFromJsonSchema(input) {
10281
11020
  for (const [key, child] of Object.entries(objectProperties)) await visit(section, [...configPath, key], child, required && childRequired.has(key));
10282
11021
  return;
10283
11022
  }
10284
- if (leaf.kind === "array" || leaf.kind === "object" || leaf.kind === "union" || leaf.kind === "unknown") {
11023
+ const issues = input.issues.get(label) ?? [];
11024
+ const constraints = [...constraintNotes(leaf), ...issues];
11025
+ const structured = leaf.kind === "array" || leaf.kind === "object";
11026
+ if (constraints.length || structured) plan.needsSchemaModule = true;
11027
+ const exported = input.schemaExports && (constraints.length || structured) ? fieldAccess(input.schema, schemaPath) : void 0;
11028
+ const publicFunction = section === "public" && typeof exported?.schema === "function";
11029
+ const found = publicFunction ? void 0 : exported;
11030
+ const schemaKind = found && schemaFieldKind(found, leaf);
11031
+ const access = schemaKind ? found : void 0;
11032
+ const kind = schemaKind || plainFieldKind(leaf);
11033
+ const credential = looksSecret(configPath);
11034
+ const variable = nuxtVariableName(section, configPath);
11035
+ const stay = (reason) => {
10285
11036
  plan.unmigrated.push(label);
10286
- const reason = leaf.kind === "union" ? "is a union, which Env cannot declare" : leaf.kind === "unknown" ? "has no JSON Schema type" : `is a JSON ${leaf.kind}, which code-first Env declarations cannot parse`;
10287
- const alternative = leaf.kind === "array" || leaf.kind === "object" ? `, or declare it in a .env.example with @type=${leaf.kind}(...) and use envSchema()` : "";
10288
- const issues = input.issues.get(label) ?? [];
10289
- const detail = issues.length ? ` Env cannot keep ${issues.join(", ")}.` : "";
10290
- follow(`${label} ${reason}.${detail} It stays in runtimeConfig without validation. Read it with useRuntimeConfig()${alternative}.`, { runtimeConfig: label });
11037
+ follow(`${label} ${reason} It stays in runtimeConfig. Read it with useRuntimeConfig(), or move it to Env by hand.`, { runtimeConfig: label });
11038
+ };
11039
+ const configValue = runtimeValue?.json;
11040
+ if (kind && (kind === "json" && leaf.kind === "object" || isRecord$4(configValue))) {
11041
+ stay(`can receive nested overrides such as ${variable}_*, but one Env declaration reads only the whole value.${credential ? " Remove any hardcoded credentials before deploying." : ""}`);
11042
+ return;
11043
+ }
11044
+ const moduleInput = runtimeValue?.literal ?? runtimeValue?.processEnv?.fallback;
11045
+ const jsonDefault = kind === "json" ? configValue : void 0;
11046
+ if (kind && access && isAsyncSchema(access.schema, [void 0, moduleInput ?? jsonDefault])) {
11047
+ stay("has an async validator, and Env runs schemas synchronously.");
11048
+ return;
11049
+ }
11050
+ if (kind && runtimeValue?.expression && jsonDefault === void 0) {
11051
+ stay(`has ${credential ? "a computed credential value" : `the value ${runtimeValue.expression}`} in runtimeConfig, which the codemod cannot keep as an Env default. Use ${variable} for the Env declaration.`);
11052
+ return;
11053
+ }
11054
+ if (kind && access && moduleInput === void 0 && jsonDefault === void 0 && hasSchemaDefault(access.schema)) {
11055
+ stay("gets its default from its $schema, and Env does not run the schema when the variable is not set.");
11056
+ return;
11057
+ }
11058
+ if (!kind) {
11059
+ plan.unmigrated.push(label);
11060
+ const reason = leaf.kind === "union" ? "is a union of input types, which the codemod cannot map to one Env declaration" : leaf.kind === "unknown" ? "has no JSON Schema type" : `is a JSON ${leaf.kind}, and the codemod cannot export its schema`;
11061
+ const detail = issues.length ? ` It has ${issues.join(", ")}.` : "";
11062
+ follow(`${label} ${reason}.${detail} It stays in runtimeConfig without validation. Read it with useRuntimeConfig(), or ${section === "server" ? "export its schema from a server module and declare it with env.schemaFrom()" : "declare it with env.json() and its schema object, with mode: 'build'"}.`, { runtimeConfig: label });
10291
11063
  return;
10292
11064
  }
10293
- const kind = leaf.kind === "integer" ? "number" : leaf.kind;
10294
11065
  const field = {
10295
11066
  section,
10296
11067
  configPath,
10297
11068
  envPath: section === "public" ? [flatPublicName(configPath)] : configPath,
10298
- variable: nuxtVariableName(section, configPath),
11069
+ variable,
10299
11070
  kind,
10300
- ...leaf.kind === "enum" ? { values: leaf.values } : {},
11071
+ ...kind === "enum" && leaf.kind === "enum" ? { values: leaf.values } : {},
10301
11072
  required: required && !leaf.nullable,
10302
- secret: section === "server" && kind !== "enum" && looksSecret(configPath)
11073
+ secret: section === "server" && kind !== "enum" && credential,
11074
+ ...access ? { schema: { steps: access.steps } } : {}
10303
11075
  };
10304
- if (section === "server" && kind === "enum" && looksSecret(configPath)) follow(`${label} looks like a credential, but an enum cannot be a secret because its values are public metadata. Use a string if the value is secret.`, { env: field });
10305
- if (section === "public" && looksSecret(configPath)) follow(`${label} looks like a credential. Public Env is bundled into client code. Move it to the server section if it is secret.`, { env: field });
11076
+ if (section === "server" && kind === "enum" && credential) follow(`${label} looks like a credential, but an enum cannot be a secret because its values are public metadata. Use a string if the value is secret.`, { env: field });
11077
+ if (section === "public" && credential) follow(`${label} looks like a credential. Public Env is bundled into client code. Move it to the server section if it is secret.`, { env: field });
10306
11078
  if (leaf.nullable) follow(`${label} accepts null. Env has no null value, so the field is optional and is undefined when the variable is not set.`, { env: field });
10307
11079
  if (section === "public" && configPath.length > 1) follow(`${label} is nested. Public Env is flat, so read it as usePublicEnv().${field.envPath[0]}.`, { env: field });
10308
- const moduleInput = runtimeValue?.literal ?? runtimeValue?.processEnv?.fallback;
10309
- const schemaPath = section === "public" ? ["public", ...configPath] : configPath;
11080
+ if (kind === "json" && leaf.kind === "boolean") follow(`${label}: Env reads ${field.variable} as JSON before its schema runs. Set it to true or false. Spellings such as 1, 0, or TRUE now fail.`, { env: field });
11081
+ else if (kind === "json" && (leaf.kind === "number" || leaf.kind === "integer")) follow(`${label}: Env reads ${field.variable} as JSON before its schema runs. Set it to a JSON number, such as 3000. Spellings such as 0xBB8, +3000, or .5 now fail.`, { env: field });
11082
+ if (access && section === "server" && validateAtBuild && !validateAtRuntime) follow(`${label}: the module ran its $schema only during the build (validateAtRuntime: false). Env runs it when the server reads ${field.variable}, so a value that the build did not check now stops the request.`, { env: field });
10310
11083
  const runtimeInput = moduleInput !== void 0 && validateAtRuntime ? coerceRuntimeInput(moduleInput, coercionSchema ? leafAtPath(coercionSchema, schemaPath) : leaf) : moduleInput;
10311
- let defaultValue = runtimeInput === void 0 ? void 0 : coerceDefault(runtimeInput, field);
11084
+ const toDefault = (value) => access ? schemaDefault(value, kind) : coerceDefault(value, field);
11085
+ let defaultValue = jsonDefault ?? (runtimeInput === void 0 ? void 0 : toDefault(runtimeInput));
10312
11086
  if (runtimeValue?.literal !== void 0) {
10313
- if (defaultValue === void 0) follow(`runtimeConfig.${label} has the value ${literalText(runtimeValue.literal)}, which is not a valid ${kind}. It was not kept as a default.`, { env: field });
11087
+ if (defaultValue === void 0) {
11088
+ const value = credential ? "a credential value" : `the value ${literalText(runtimeValue.literal)}`;
11089
+ follow(`runtimeConfig.${label} has ${value}, which is not a valid ${kind}. It was not kept as a default.${credential ? ` Set ${variable} instead.` : ""}`, { env: field });
11090
+ }
10314
11091
  } else if (runtimeValue?.processEnv) {
10315
11092
  field.extraVariables = [runtimeValue.processEnv.name];
10316
11093
  follow(`runtimeConfig.${label} read process.env.${runtimeValue.processEnv.name} when Nuxt loaded the config. Env now reads ${field.variable === runtimeValue.processEnv.name ? field.variable : `${field.variable}, then ${runtimeValue.processEnv.name}`}, ${section === "public" ? "during the build" : "when the server runs"}. Env treats an empty variable as unset.`, { env: field });
10317
- } else if (runtimeValue?.expression) follow(`runtimeConfig.${label} is computed (${runtimeValue.expression}). It was not kept as a default. Set ${field.variable} or add a default by hand.`, { env: field });
10318
- if (defaultValue === void 0) {
10319
- const schemaDefault = leaf.node.default;
10320
- if (typeof schemaDefault === "string" || typeof schemaDefault === "number" || typeof schemaDefault === "boolean") defaultValue = coerceDefault(schemaDefault, field);
11094
+ }
11095
+ if (defaultValue === void 0 && !access) {
11096
+ const schemaDefaultValue = leaf.node.default;
11097
+ if (typeof schemaDefaultValue === "string" || typeof schemaDefaultValue === "number" || typeof schemaDefaultValue === "boolean") defaultValue = toDefault(schemaDefaultValue);
10321
11098
  }
10322
11099
  let rejection;
10323
11100
  if (defaultValue !== void 0 && input.rejectInvalidDefaults !== false && (validateAtRuntime || validateAtBuild)) {
10324
11101
  const check = {
10325
- schema: fieldSchema(input.schema, schemaPath),
11102
+ schema: access?.schema ?? fieldSchema(input.schema, schemaPath),
10326
11103
  node: leaf.node,
10327
- input: validateAtBuild ? moduleInput : runtimeInput,
11104
+ input: jsonDefault ?? (validateAtBuild ? moduleInput : runtimeInput),
10328
11105
  value: defaultValue
10329
11106
  };
10330
11107
  rejection = await defaultRejection(check);
10331
- if (rejection === void 0 && validateAtBuild && runtimeInput !== moduleInput) rejection = await defaultRejection({
11108
+ if (rejection === void 0 && validateAtBuild && jsonDefault === void 0 && runtimeInput !== moduleInput) rejection = await defaultRejection({
10332
11109
  ...check,
10333
11110
  input: runtimeInput
10334
11111
  });
10335
11112
  }
10336
11113
  if (defaultValue !== void 0 && rejection !== void 0) {
10337
- follow(`${label} had the value ${literalText(defaultValue)}, which its $schema rejects: ${rejection}. The module treats this validation failure as fatal, so the codemod kept no default and Env requires ${field.variable}.`, { env: field });
11114
+ const value = credential ? "a credential default, which its $schema rejects" : `the value ${literalText(defaultValue)}, which its $schema rejects: ${rejection}`;
11115
+ follow(`${label} had ${value}. The module treats this validation failure as fatal, so the codemod kept no default and Env requires ${field.variable}.`, { env: field });
10338
11116
  field.required = true;
10339
11117
  defaultValue = void 0;
10340
11118
  }
10341
11119
  if (defaultValue !== void 0 && defaultValue !== "" && field.secret) {
10342
- follow(`${label} is secret, so its value ${literalText(defaultValue)} was not kept as a default. Defaults are written into the server build. Set ${field.variable} instead.`, { env: field });
11120
+ follow(`${label} is secret, so its value was not kept as a default. Defaults are written into the server build. Set ${field.variable} instead.`, { env: field });
10343
11121
  defaultValue = void 0;
10344
11122
  }
10345
11123
  if (defaultValue !== void 0) field.default = defaultValue;
10346
- const constraints = [...constraintNotes(leaf), ...input.issues.get(label) ?? []];
10347
- if (constraints.length) follow(`${label}: Env does not keep ${constraints.join(", ")}. Check the value in code, or use envSchema() with a .env.example for length, range, integer, and URL checks.`, { env: field });
11124
+ if (constraints.length && !access && publicFunction) follow(`${label}: the codemod does not move a public schema that is a function, such as an ArkType type, and did not keep ${constraints.join(", ")}. Check the value in code.`, { env: field });
11125
+ else if (constraints.length && !access) {
11126
+ const advice = section === "server" ? "Export the field schema from a server module and declare it with env.schemaFrom()" : "Pass the field schema object as the schema option";
11127
+ follow(`${label}: the codemod did not keep ${constraints.join(", ")}. ${advice}, or check the value in code.`, { env: field });
11128
+ }
10348
11129
  plan.fields.push(field);
10349
11130
  };
10350
11131
  const rootRequired = requiredOf(root);
@@ -10383,6 +11164,252 @@ async function planFromJsonSchema(input) {
10383
11164
  }
10384
11165
  return plan;
10385
11166
  }
11167
+ // src/nuxt-safe-runtime-config/schema-module.ts
11168
+ const reservedWords = /* @__PURE__ */ new Set([
11169
+ "arguments",
11170
+ "await",
11171
+ "break",
11172
+ "case",
11173
+ "catch",
11174
+ "class",
11175
+ "const",
11176
+ "continue",
11177
+ "debugger",
11178
+ "default",
11179
+ "delete",
11180
+ "do",
11181
+ "else",
11182
+ "enum",
11183
+ "eval",
11184
+ "export",
11185
+ "extends",
11186
+ "false",
11187
+ "finally",
11188
+ "for",
11189
+ "function",
11190
+ "if",
11191
+ "implements",
11192
+ "import",
11193
+ "in",
11194
+ "instanceof",
11195
+ "interface",
11196
+ "let",
11197
+ "new",
11198
+ "null",
11199
+ "package",
11200
+ "private",
11201
+ "protected",
11202
+ "public",
11203
+ "return",
11204
+ "static",
11205
+ "super",
11206
+ "switch",
11207
+ "this",
11208
+ "throw",
11209
+ "true",
11210
+ "try",
11211
+ "typeof",
11212
+ "undefined",
11213
+ "var",
11214
+ "void",
11215
+ "while",
11216
+ "with",
11217
+ "yield"
11218
+ ]);
11219
+ function serverDirectory(config) {
11220
+ const property = findProperty(config.root, "serverDir");
11221
+ const value = property ? literalValue(property.value) : void 0;
11222
+ if (typeof value !== "string" || isAbsolute(value)) return "server";
11223
+ const normalized = posix.normalize(value.replaceAll("\\", "/")).replace(/\/+$/, "");
11224
+ return normalized && normalized !== "." && !normalized.startsWith("../") && normalized !== ".." ? normalized : "server";
11225
+ }
11226
+ function relativeSpecifier$1(from, specifier) {
11227
+ if (!specifier.startsWith("./") && !specifier.startsWith("../")) return specifier;
11228
+ const path = posix.relative(from, posix.normalize(specifier));
11229
+ return path.startsWith(".") ? path : `./${path}`;
11230
+ }
11231
+ function findSchemaProperty(options) {
11232
+ for (const option of options) {
11233
+ const object = option ? unwrapExpression(option) : void 0;
11234
+ if (object?.type !== "ObjectExpression") continue;
11235
+ const property = findProperty(object, "$schema");
11236
+ if (property) return property;
11237
+ }
11238
+ }
11239
+ function topLevelBindings(config) {
11240
+ const imports = /* @__PURE__ */ new Map();
11241
+ const locals = /* @__PURE__ */ new Set();
11242
+ const declarators = /* @__PURE__ */ new Map();
11243
+ for (const statement of config.program.program.body) {
11244
+ if (statement.type === "ImportDeclaration") {
11245
+ for (const specifier of statement.specifiers) imports.set(specifier.local.name, statement);
11246
+ continue;
11247
+ }
11248
+ const declaration = statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
11249
+ if (declaration?.type === "VariableDeclaration") for (const declarator of declaration.declarations) {
11250
+ for (const name of patternNames(declarator.id)) locals.add(name);
11251
+ if (declaration.kind === "const" && declarator.id.type === "Identifier" && declarator.init) declarators.set(declarator.id.name, declarator.init);
11252
+ }
11253
+ if ((declaration?.type === "FunctionDeclaration" || declaration?.type === "ClassDeclaration") && declaration.id) locals.add(declaration.id.name);
11254
+ }
11255
+ return {
11256
+ imports,
11257
+ locals,
11258
+ declarators
11259
+ };
11260
+ }
11261
+ function patternNames(node) {
11262
+ if (!node) return [];
11263
+ switch (node.type) {
11264
+ case "Identifier": return [node.name];
11265
+ case "ObjectPattern": return node.properties.flatMap((entry) => patternNames(entry.type === "RestElement" ? entry.argument : entry.value));
11266
+ case "ArrayPattern": return node.elements.flatMap(patternNames);
11267
+ case "AssignmentPattern": return patternNames(node.left);
11268
+ case "RestElement": return patternNames(node.argument);
11269
+ default: return [];
11270
+ }
11271
+ }
11272
+ function dedent(code, indent) {
11273
+ return indent ? code.split("\n").map((text, index) => index && text.startsWith(indent) ? text.slice(indent.length) : text).join("\n") : code;
11274
+ }
11275
+ /**
11276
+ * Chooses the schema module path and reads what it must import. Returns a reason instead when the `$schema` cannot
11277
+ * move to a module: it uses other nuxt.config bindings, or the codemod cannot find its code.
11278
+ */
11279
+ function planSchemaModule(input) {
11280
+ const { config } = input;
11281
+ const directory = serverDirectory(config);
11282
+ const extension = /\.[cm]?ts$/.test(config.fileName) ? ".ts" : ".mjs";
11283
+ const candidates = ["env.schema", "runtime-config.schema"].map((name) => `${directory}/${name}${extension}`);
11284
+ const path = candidates.find((candidate) => !existsSync(join(input.cwd, candidate)));
11285
+ if (!path) return { reason: `${candidates.join(" and ")} already exist, so the codemod wrote no schema module.` };
11286
+ const importPath = `./${extension === ".ts" ? path.slice(0, -extension.length) : path}`;
11287
+ const base = {
11288
+ path,
11289
+ runtimePath: `./${path}`,
11290
+ importPath
11291
+ };
11292
+ const moduleDirectory = posix.dirname(path);
11293
+ if (input.schemaPath !== void 0) return { target: {
11294
+ ...base,
11295
+ source: {
11296
+ kind: "module",
11297
+ specifier: relativeSpecifier$1(moduleDirectory, input.schemaPath)
11298
+ }
11299
+ } };
11300
+ for (const option of input.options) if (option && unwrapExpression(option).type === "ObjectExpression" && !staticOptionsObject(option)) throw codemodError(`The module options in ${config.fileName} have a spread, a computed key, or a repeated key, so the codemod cannot tell which $schema the module used. Write $schema once, without a spread, then run the codemod again.`);
11301
+ const property = findSchemaProperty(input.options);
11302
+ if (!property) return { reason: "The codemod cannot find the code of the inline $schema." };
11303
+ const { imports, locals, declarators } = topLevelBindings(config);
11304
+ let expression = unwrapExpression(property.value);
11305
+ let binding = "runtimeConfigSchema";
11306
+ if (expression.type === "Identifier") {
11307
+ const init = declarators.get(expression.name);
11308
+ if (!init) return { reason: `The inline $schema reads ${expression.name}, which is not a top-level const in ${config.fileName}.` };
11309
+ binding = expression.name;
11310
+ expression = init;
11311
+ }
11312
+ const used = /* @__PURE__ */ new Set();
11313
+ const localNames = /* @__PURE__ */ new Set();
11314
+ const references = /* @__PURE__ */ new Set();
11315
+ walk(expression, (node, ancestors) => {
11316
+ if (!isReference(node, ancestors.at(-1))) return;
11317
+ references.add(node.name);
11318
+ const declaration = imports.get(node.name);
11319
+ if (declaration) used.add(declaration);
11320
+ else if (locals.has(node.name)) localNames.add(node.name);
11321
+ });
11322
+ if (localNames.size) return { reason: `The inline $schema uses ${[...localNames].sort().join(", ")} from ${config.fileName}, so the codemod cannot move it to a schema module.` };
11323
+ const code = config.code.slice(start(expression), end(expression));
11324
+ const declarations = [...used].map((declaration) => ({
11325
+ ...declaration,
11326
+ source: {
11327
+ ...declaration.source,
11328
+ value: relativeSpecifier$1(moduleDirectory, declaration.source.value)
11329
+ }
11330
+ }));
11331
+ const sources = [...used].map((declaration) => declaration.source.value);
11332
+ return { target: {
11333
+ ...base,
11334
+ source: {
11335
+ kind: "inline",
11336
+ binding,
11337
+ expression: dedent(code, indentAt(config.code, start(expression))),
11338
+ imports: declarations,
11339
+ sources,
11340
+ references: [...references]
11341
+ }
11342
+ } };
11343
+ }
11344
+ function identifierName(name) {
11345
+ const cleaned = name.replaceAll(/[^\w$]/g, "_");
11346
+ const identifier = /^\d/.test(cleaned) ? `_${cleaned}` : cleaned;
11347
+ return reservedWords.has(identifier) ? `${identifier}Schema` : identifier;
11348
+ }
11349
+ function exportName(field) {
11350
+ const name = flatPublicName(field.configPath);
11351
+ return identifierName(field.section === "public" ? `public${name.charAt(0).toUpperCase()}${name.slice(1)}` : name);
11352
+ }
11353
+ function renderStep(step, style) {
11354
+ if (step.kind === "call") return `.${step.name}(${step.args.map((arg) => quoteString(arg, style)).join(", ")})`;
11355
+ return /^[A-Za-z_$][\w$]*$/.test(step.name) ? `.${step.name}` : `[${quoteString(step.name, style)}]`;
11356
+ }
11357
+ function renderImport(declaration, style, semicolon) {
11358
+ const clauses = [];
11359
+ const named = [];
11360
+ for (const specifier of declaration.specifiers) if (specifier.type === "ImportDefaultSpecifier") clauses.unshift(specifier.local.name);
11361
+ else if (specifier.type === "ImportNamespaceSpecifier") clauses.push(`* as ${specifier.local.name}`);
11362
+ else {
11363
+ const imported = specifier.imported.type === "Identifier" ? specifier.imported.name : quoteString(specifier.imported.value, style);
11364
+ const kind = specifier.importKind === "type" ? "type " : "";
11365
+ named.push(`${kind}${imported === specifier.local.name ? imported : `${imported} as ${specifier.local.name}`}`);
11366
+ }
11367
+ if (named.length) clauses.push(`{ ${named.join(", ")} }`);
11368
+ return `import ${declaration.importKind === "type" ? "type " : ""}${clauses.join(", ")} from ${quoteString(declaration.source.value, style)}${semicolon}`;
11369
+ }
11370
+ /** Writes the module that exports the schema of each field in `fields`. */
11371
+ function renderSchemaModule(target, fields, style) {
11372
+ const semicolon = style.semicolons ? ";" : "";
11373
+ const source = target.source;
11374
+ const locals = new Set(source.kind === "inline" ? [...source.references, ...source.imports.flatMap((declaration) => declaration.specifiers.map((specifier) => specifier.local.name))] : []);
11375
+ const fresh = (base, taken) => {
11376
+ let name = base;
11377
+ for (let index = 2; taken.has(name); index++) name = `${base}${index}`;
11378
+ taken.add(name);
11379
+ return name;
11380
+ };
11381
+ const binding = fresh(source.kind === "inline" ? source.binding : "runtimeConfigSchema", locals);
11382
+ const exportNames = /* @__PURE__ */ new Set();
11383
+ const exports = /* @__PURE__ */ new Map();
11384
+ const lines = [];
11385
+ const aliases = [];
11386
+ for (const field of fields) {
11387
+ if (!field.schema) continue;
11388
+ const name = fresh(exportName(field), exportNames);
11389
+ const local = fresh(name, locals);
11390
+ exports.set(field, name);
11391
+ const value = `${binding}${field.schema.steps.map((step) => renderStep(step, style)).join("")}${semicolon}`;
11392
+ if (local === name) lines.push(`export const ${name} = ${value}`);
11393
+ else {
11394
+ lines.push(`const ${local} = ${value}`);
11395
+ aliases.push(`${local} as ${name}`);
11396
+ }
11397
+ }
11398
+ if (aliases.length) lines.push(`export { ${aliases.join(", ")} }${semicolon}`);
11399
+ return {
11400
+ code: `${[
11401
+ ...source.kind === "inline" ? [
11402
+ ...source.imports.map((declaration) => renderImport(declaration, style, semicolon)),
11403
+ "",
11404
+ `const ${binding} = ${source.expression}${semicolon}`
11405
+ ] : [`import ${binding} from ${quoteString(source.specifier, style)}${semicolon}`],
11406
+ "",
11407
+ ...lines
11408
+ ].join("\n").replace(/^\n+/, "")}\n`,
11409
+ exports,
11410
+ importedSources: source.kind === "inline" ? source.sources : []
11411
+ };
11412
+ }
10386
11413
  // src/nuxt-safe-runtime-config/index.ts
10387
11414
  function mergeStatic(top, inline) {
10388
11415
  return {
@@ -10436,7 +11463,6 @@ function validationChecks(options, version) {
10436
11463
  validateAtRuntime: options.validateAtRuntime ?? true
10437
11464
  };
10438
11465
  }
10439
- /** Reads the module options statically, and runs nuxt.config only when an inline schema or a dynamic option needs it. */
10440
11466
  async function resolveOptions(config, staticOptions) {
10441
11467
  if (!staticOptions.inlineSchema && !staticOptions.dynamic) return staticOptions;
10442
11468
  const evaluated = await loadNuxtConfig(config.path);
@@ -10455,7 +11481,6 @@ async function resolveOptions(config, staticOptions) {
10455
11481
  validateAtRuntime: typeof options.validateAtRuntime === "boolean" ? options.validateAtRuntime : void 0
10456
11482
  };
10457
11483
  }
10458
- /** Line of each object property in a schema module, by its dotted path of property keys. */
10459
11484
  function schemaLines(code) {
10460
11485
  const lines = /* @__PURE__ */ new Map();
10461
11486
  let program;
@@ -10552,6 +11577,7 @@ async function findOutOfScopeConfigs(cwd, rootConfig) {
10552
11577
  };
10553
11578
  }
10554
11579
  async function migrate$15({ cwd }) {
11580
+ await assertNotNitro2(cwd, moduleName$3);
10555
11581
  const config = await readNuxtConfig(cwd);
10556
11582
  const moduleEntry = findModuleEntry(config, moduleName$3);
10557
11583
  const safeProperty = findProperty(config.root, "safeRuntimeConfig");
@@ -10568,6 +11594,8 @@ async function migrate$15({ cwd }) {
10568
11594
  let schemaFile;
10569
11595
  let lines = /* @__PURE__ */ new Map();
10570
11596
  let sourceLabel;
11597
+ let schemaModule;
11598
+ let generated;
10571
11599
  if (options.envSchema) {
10572
11600
  const file = options.envSchema.file;
10573
11601
  const path = join(cwd, file);
@@ -10600,16 +11628,35 @@ async function migrate$15({ cwd }) {
10600
11628
  }
10601
11629
  const runtime = readRuntimeConfig(config);
10602
11630
  if (findProperty(config.root, "runtimeConfig") && !runtime.object) planned.push({ message: "runtimeConfig is not an object literal, so the codemod kept its values and removed no keys. Move the migrated values to Env defaults by hand." });
11631
+ const { validateAtBuild, validateAtRuntime } = validationChecks(options, await moduleVersion(cwd));
11632
+ const onError = options.onError ?? "throw";
11633
+ const enforced = onError === "throw" && (validateAtBuild || validateAtRuntime);
11634
+ const moduleTarget = enforced ? planSchemaModule({
11635
+ cwd,
11636
+ config,
11637
+ schemaPath: options.schemaPath,
11638
+ options: [moduleEntry?.inlineOptions, safeProperty?.value]
11639
+ }) : { reason: onError === "throw" ? "The module did not validate runtimeConfig, so the codemod wrote no schema module." : `The module only reported validation failures (onError: '${onError}'), but Env stops the app when a schema fails, so the codemod wrote no schema module.` };
11640
+ const target = "target" in moduleTarget ? moduleTarget.target : void 0;
10603
11641
  const plan = await planFromJsonSchema({
10604
11642
  schema,
11643
+ schemaExports: Boolean(target),
10605
11644
  jsonSchema: await schemaToJsonSchema(schema, cwd),
10606
11645
  issues: schemaIssues(schema),
10607
11646
  runtimeConfig: runtime.values,
10608
- ...validationChecks(options, await moduleVersion(cwd)),
10609
- rejectInvalidDefaults: (options.onError ?? "throw") === "throw"
11647
+ validateAtBuild,
11648
+ validateAtRuntime,
11649
+ rejectInvalidDefaults: onError === "throw"
10610
11650
  });
10611
11651
  fields = plan.fields;
10612
11652
  unmigrated = plan.unmigrated;
11653
+ if ("reason" in moduleTarget && plan.needsSchemaModule) {
11654
+ const retry = enforced ? " Move the $schema to its own module, then run the codemod again." : "";
11655
+ planned.push({
11656
+ message: `${moduleTarget.reason} The fields below that have rules keep follow-ups.${retry}`,
11657
+ anchor: { schema: "" }
11658
+ });
11659
+ }
10613
11660
  planned.push(...plan.followUps);
10614
11661
  env = {
10615
11662
  kind: "fields",
@@ -10617,13 +11664,28 @@ async function migrate$15({ cwd }) {
10617
11664
  };
10618
11665
  sourceLabel = schemaFile ? `$schema (${schemaFile})` : "$schema";
10619
11666
  notes.push("Each declaration reads its NUXT_* name with env.source(). Env reads the canonical name VITEHUB_<PATH> first, for example VITEHUB_API_SECRET before NUXT_API_SECRET.");
10620
- if (schemaFile) notes.push(`The codemod did not delete ${schemaFile}. Delete it, and its schema library if nothing else uses it.`);
11667
+ if (target && fields.some((field) => field.schema)) {
11668
+ const rendered = renderSchemaModule(target, fields, detectStyle(config.code, config.program));
11669
+ schemaModule = {
11670
+ runtimePath: target.runtimePath,
11671
+ importPath: target.importPath,
11672
+ exports: rendered.exports
11673
+ };
11674
+ generated = {
11675
+ path: target.path,
11676
+ code: rendered.code,
11677
+ importedSources: rendered.importedSources
11678
+ };
11679
+ notes.push(`${target.path} exports the $schema of each field that has a rule or transform. Server Env runs it with env.schemaFrom() when the server reads the value. Public Env runs it during the build.`);
11680
+ if (schemaFile) notes.push(`${target.path} imports ${schemaFile}. Keep ${schemaFile} and its schema library.`);
11681
+ } else if (schemaFile) notes.push(`The codemod did not delete ${schemaFile}. Delete it, and its schema library if nothing else uses it.`);
10621
11682
  }
10622
11683
  const migrated = new Set(fields.map((field) => pathLabel(field)));
10623
11684
  const edited = editNuxtConfig({
10624
11685
  config,
10625
11686
  env,
10626
- migrated
11687
+ migrated,
11688
+ schemaModule
10627
11689
  });
10628
11690
  const outOfScope = await findOutOfScopeConfigs(cwd, config);
10629
11691
  const calls = await rewriteCallSites({
@@ -10634,7 +11696,12 @@ async function migrate$15({ cwd }) {
10634
11696
  });
10635
11697
  const packageResult = await editPackageJson(cwd, version, {
10636
11698
  remove: [moduleName$3],
10637
- add: env.kind === "env-schema" ? ["vite-hub", "@vite-hub/env"] : ["vite-hub"]
11699
+ add: env.kind === "fields" ? ["vite-hub"] : [],
11700
+ require: env.kind === "env-schema" ? {
11701
+ name: "vite-hub",
11702
+ range: ">=0.5.1 <1",
11703
+ feature: "vite-hub/env/vite"
11704
+ } : void 0
10638
11705
  });
10639
11706
  const envLine = (field) => edited.lineOf([
10640
11707
  "vitehub",
@@ -10691,12 +11758,12 @@ async function migrate$15({ cwd }) {
10691
11758
  if (!reads.length) secretFollowUps.push({
10692
11759
  file: config.fileName,
10693
11760
  line: envLine(field),
10694
- message: `${accessor} is secret, a SecretEnv<string>. No rewritten file reads it. Call .unseal() where code needs the raw value.`
11761
+ message: `${accessor} is secret, a ${secretType(field)}. No rewritten file reads it. Call .unseal() where code needs the raw value.`
10695
11762
  });
10696
11763
  for (const read of reads) secretFollowUps.push({
10697
11764
  file: read.file,
10698
11765
  line: read.line,
10699
- message: `${accessor} is secret, a SecretEnv<string>. Call .unseal() where this code needs the raw value.`
11766
+ message: `${accessor} is secret, a ${secretType(field)}. Call .unseal() where this code needs the raw value.`
10700
11767
  });
10701
11768
  }
10702
11769
  const eslint = await findEslintReferences(cwd);
@@ -10705,11 +11772,17 @@ async function migrate$15({ cwd }) {
10705
11772
  before: config.code,
10706
11773
  after: edited.code
10707
11774
  }];
11775
+ if (generated) edits.push({
11776
+ path: generated.path,
11777
+ before: void 0,
11778
+ after: generated.code
11779
+ });
10708
11780
  if (packageResult.edit) edits.push(packageResult.edit);
10709
11781
  edits.push(...calls.edits);
10710
- for (const source of edited.removedImports.filter((entry) => /^[@a-z]/i.test(entry) && !entry.startsWith("nuxt"))) notes.push(`${config.fileName} no longer imports ${source}. Remove it from package.json if nothing else uses it.`);
11782
+ const moved = new Set(generated?.importedSources);
11783
+ for (const source of edited.removedImports.filter((entry) => /^[@a-z]/i.test(entry) && !entry.startsWith("nuxt") && !moved.has(entry))) notes.push(`${config.fileName} no longer imports ${source}. Remove it from package.json if nothing else uses it.`);
10711
11784
  const publicCount = fields.filter((field) => field.section === "public").length;
10712
- notes.push("Public Env values are fixed at build time. Nuxt applied NUXT_PUBLIC_* overrides when the server started; now set them when you build. Server Env values are read when the server runs.", "Shelve and the standalone Nitro module (nuxt-safe-runtime-config/nitro) are out of scope for this codemod.");
11785
+ notes.push("Public Env values are fixed at build time. Nuxt applied NUXT_PUBLIC_* overrides when the server started; now set them when you build. Server Env values are read when the server runs.", "The standalone Nitro module (nuxt-safe-runtime-config/nitro) is out of scope for this codemod.");
10713
11786
  if (!eslint.length) notes.push("No ESLint config references nuxt-safe-runtime-config/eslint.");
10714
11787
  return {
10715
11788
  summary: `migrated ${fields.length} Env declaration${fields.length === 1 ? "" : "s"} (${publicCount} public, ${fields.length - publicCount} server) from ${sourceLabel} to vite-hub/nuxt.`,
@@ -10720,13 +11793,16 @@ async function migrate$15({ cwd }) {
10720
11793
  ...calls.followUps,
10721
11794
  ...secretFollowUps,
10722
11795
  ...eslint,
10723
- ...outOfScope.followUps
11796
+ ...outOfScope.followUps,
11797
+ ...packageResult.followUps
10724
11798
  ],
10725
11799
  notes,
10726
- nextSteps: [`Run \`${packageResult.installCommand}\` to install ${env.kind === "env-schema" ? "vite-hub and @vite-hub/env" : "vite-hub"} and remove ${moduleName$3}.`, "Run `npx nuxi prepare` to generate the Env types, then type-check the app."]
11800
+ nextSteps: [`Run \`${packageResult.installCommand}\` to install vite-hub and remove ${moduleName$3}.`, "Run `npx nuxi prepare` to generate the Env types, then type-check the app."]
10727
11801
  };
10728
11802
  }
10729
- /** Remove a schema-free module only when no layer can supply options or composable calls. */
11803
+ function secretType(field) {
11804
+ return field.schema ? "SecretEnv of the schema output" : "SecretEnv<string>";
11805
+ }
10730
11806
  async function removeUnusedModule(cwd, config, safeProperty) {
10731
11807
  const editor = new ConfigEditor(config);
10732
11808
  removeModuleEntry(editor, config, moduleName$3);
@@ -10871,20 +11947,6 @@ const sections = ["dependencies", "devDependencies"];
10871
11947
  function isRecord$3(value) {
10872
11948
  return typeof value === "object" && value !== null && !Array.isArray(value);
10873
11949
  }
10874
- function catalogEntry(value, key) {
10875
- return value instanceof Map ? value.get(key) : void 0;
10876
- }
10877
- async function readPnpmCatalogVersion(cwd, name, catalog) {
10878
- let directory = cwd;
10879
- while (!existsSync(join(directory, "pnpm-workspace.yaml"))) {
10880
- if (dirname(directory) === directory) return;
10881
- directory = dirname(directory);
10882
- }
10883
- const workspace = parseDocument(await readFile(join(directory, "pnpm-workspace.yaml"), "utf8")).toJS({ mapAsMap: true });
10884
- const fallback = catalog === "default" ? catalogEntry(catalogEntry(workspace, "catalog"), name) : void 0;
10885
- const version = catalogEntry(catalogEntry(catalogEntry(workspace, "catalogs"), catalog), name) ?? fallback;
10886
- if (typeof version === "string") return version;
10887
- }
10888
11950
  function admitsNuxt5(range) {
10889
11951
  if (intersects(range, ">=5.0.0")) return true;
10890
11952
  return new Range(range).set.some((comparators) => {
@@ -16539,6 +17601,10 @@ function moves() {
16539
17601
  from: "vite-hub/auth/console-runtime",
16540
17602
  privatePath: "`vite-hub/auth/console-runtime` is no longer public. Read users and sessions with `getAuthConsoleForRequest(request)` from `vite-hub/auth/server`."
16541
17603
  },
17604
+ {
17605
+ from: "vite-hub/console/mcp-client",
17606
+ privatePath: "`vite-hub/console/mcp-client` was removed. The MCP client section of the ViteHub Console connects to MCP servers from the Console server. Remove the import, and remove `@modelcontextprotocol/sdk` when nothing else imports it."
17607
+ },
16542
17608
  {
16543
17609
  from: "vite-hub/runtime",
16544
17610
  removed: runtimeRemoved
@@ -17834,7 +18900,6 @@ const ignored = [
17834
18900
  "**/dist/**",
17835
18901
  "**/coverage/**"
17836
18902
  ];
17837
- /** Option types that this release renamed or removed, with their replacement. */
17838
18903
  const renamedTypes = {
17839
18904
  AgentModuleOptions: "AgentOptions",
17840
18905
  AuthModuleOptions: "AuthOptions",
@@ -17875,10 +18940,15 @@ async function migrations(cwd) {
17875
18940
  const results = [];
17876
18941
  for (const file of files) {
17877
18942
  const before = await readFile(join(cwd, file), "utf8");
18943
+ const directory = dirname(file);
18944
+ const hasLocalNuxtLayers = basename(file).startsWith("nuxt.config") && (basename(dirname(directory)) === "layers" || (await glob("layers/*", {
18945
+ cwd: join(cwd, directory),
18946
+ onlyDirectories: true
18947
+ })).length > 0);
17878
18948
  results.push({
17879
18949
  before,
17880
18950
  file,
17881
- result: migrateViteHubOptions(file, before)
18951
+ result: migrateViteHubOptions(file, before, { hasLocalNuxtLayers })
17882
18952
  });
17883
18953
  }
17884
18954
  for (const [file, positions] of [...imported.options.entries()].sort(([left], [right]) => left.localeCompare(right))) {
@@ -17886,7 +18956,7 @@ async function migrations(cwd) {
17886
18956
  results.push({
17887
18957
  before,
17888
18958
  file,
17889
- result: migrateViteHubOptions(file, before, (program) => optionsAt(program, positions))
18959
+ result: migrateViteHubOptions(file, before, { findOptions: (program) => optionsAt(program, positions) })
17890
18960
  });
17891
18961
  }
17892
18962
  return {
@@ -17894,7 +18964,6 @@ async function migrations(cwd) {
17894
18964
  followUps: imported.followUps
17895
18965
  };
17896
18966
  }
17897
- /** Source lines that name a renamed option type. The codemod reports them and edits nothing. */
17898
18967
  async function renamedTypeReferences(cwd) {
17899
18968
  const followUps = [];
17900
18969
  for (const file of (await glob(sourcePatterns$1, {
@@ -17927,7 +18996,7 @@ async function migrate$1({ cwd }) {
17927
18996
  });
17928
18997
  }
17929
18998
  followUps.push(...await renamedTypeReferences(cwd));
17930
- if (!edits.length && !followUps.length) throw codemodError("No vite.config or nuxt.config, or a file that one imports, sets preset, sandbox, devtools, observability.logs, logs.evlog, contentImportBase, or a top-level env, so there is nothing to migrate.");
18999
+ if (!edits.length && !followUps.length) throw codemodError("No vite.config or nuxt.config, or a file that one imports, sets preset, sandbox, devtools, console options that moved, observability.logs, logs.evlog, contentImportBase, or a top-level env, so there is nothing to migrate.");
17931
19000
  return {
17932
19001
  summary: edits.length ? `Moved vite-hub options in ${edits.length} config file${edits.length === 1 ? "" : "s"}.` : "Found nothing to move automatically.",
17933
19002
  edits,
@@ -17938,7 +19007,7 @@ async function migrate$1({ cwd }) {
17938
19007
  }
17939
19008
  const vitehubOptions = {
17940
19009
  name: "vitehub-options",
17941
- description: "Renames preset to host, moves observability.logs to logs and Env declarations into vitehub({ env }), and removes devtools and contentImportBase",
19010
+ description: "Renames preset to host, moves observability.logs to logs, Env declarations into vitehub({ env }) and the Console journal options into agent.invocations, and removes devtools, contentImportBase and the Console options that left the app",
17942
19011
  usage: "[dir]",
17943
19012
  async detect({ cwd }) {
17944
19013
  const { results, followUps } = await migrations(cwd);
@@ -18115,6 +19184,7 @@ const codemods = [
18115
19184
  cliUrlFlag,
18116
19185
  cliYesFlag,
18117
19186
  cmsRoles,
19187
+ consoleOutOfApp,
18118
19188
  choicesPackage,
18119
19189
  cliGetList,
18120
19190
  cliAgentTree,
@@ -18153,6 +19223,7 @@ const upgradeCodemods = [
18153
19223
  cliUrlFlag,
18154
19224
  cliYesFlag,
18155
19225
  cmsRoles,
19226
+ consoleOutOfApp,
18156
19227
  choicesPackage,
18157
19228
  cliGetList,
18158
19229
  cliAgentTree,
@@ -18383,11 +19454,13 @@ async function runMigration(options = {}) {
18383
19454
  });
18384
19455
  } catch (error) {
18385
19456
  if (!isCodemodError(error)) throw error;
18386
- steps.push({
19457
+ const step = {
18387
19458
  codemod,
18388
19459
  detection,
18389
19460
  error: unscratch(error.message)
18390
- });
19461
+ };
19462
+ if (error.fix) step.fix = unscratch(error.fix);
19463
+ steps.push(step);
18391
19464
  }
18392
19465
  }
18393
19466
  const needsNitro3 = steps.filter(({ result }) => result?.requiresNitro3).map(({ codemod }) => codemod.name);
@@ -18450,6 +19523,7 @@ function formatMigrationReport(migration, nextSteps = []) {
18450
19523
  for (const step of steps) {
18451
19524
  lines.push("", `${step.codemod.name} (${step.detection.reason})`);
18452
19525
  lines.push(step.result ? ` ${step.result.summary}` : ` Not migrated: ${step.error}`);
19526
+ if (step.fix) lines.push(` Fix: ${step.fix}`);
18453
19527
  }
18454
19528
  if (steps.length) {
18455
19529
  lines.push("", `${dryRun ? "Files to change" : "Files changed"} (${edits.length}):`);