@vite-hub/codemods 0.4.1 → 0.5.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.
@@ -1,11 +1,11 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { cp, lstat, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
3
- import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
3
+ import { basename, dirname, extname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
4
4
  import { defineDiagnostics } from "nostics";
5
5
  import { parse, parseExpression } from "@babel/parser";
6
6
  import MagicString from "magic-string";
7
7
  import { glob } from "tinyglobby";
8
- import { existsSync, readdirSync } from "node:fs";
8
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
9
9
  import { createJiti } from "jiti";
10
10
  import { parse as parse$1 } from "@vue/compiler-sfc";
11
11
  import { isMap, isScalar, isSeq, parseDocument, stringify } from "yaml";
@@ -171,10 +171,10 @@ function bindingResolver(program) {
171
171
  const parent = ancestors.at(-1);
172
172
  const outer = parent ? scopes.get(parent) : void 0;
173
173
  const fn = node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" || node.type === "ObjectMethod" || node.type === "ClassMethod" || node.type === "ClassPrivateMethod" || node.type === "TSDeclareFunction";
174
- const scope = fn || node.type === "Program" || node.type === "BlockStatement" || node.type === "StaticBlock" || node.type === "CatchClause" || node.type === "ForStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement" || node.type === "SwitchStatement" || node.type === "ClassDeclaration" || node.type === "ClassExpression" || !outer ? {
174
+ const scope = fn || node.type === "Program" || node.type === "BlockStatement" || node.type === "StaticBlock" || node.type === "CatchClause" || node.type === "ForStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement" || node.type === "SwitchStatement" || node.type === "ClassDeclaration" || node.type === "ClassExpression" || node.type === "TSModuleBlock" || !outer ? {
175
175
  parent: outer,
176
176
  bindings: /* @__PURE__ */ new Map(),
177
- hoists: fn || node.type === "Program" || node.type === "StaticBlock"
177
+ hoists: fn || node.type === "Program" || node.type === "StaticBlock" || node.type === "TSModuleBlock"
178
178
  } : outer;
179
179
  scopes.set(node, scope);
180
180
  if (fn) {
@@ -188,6 +188,7 @@ function bindingResolver(program) {
188
188
  } else if (node.type === "ImportSpecifier" || node.type === "ImportDefaultSpecifier" || node.type === "ImportNamespaceSpecifier") declare(node.local, scope);
189
189
  else if (node.type === "CatchClause") declare(node.param, scope);
190
190
  else if (node.type === "TSEnumDeclaration" || node.type === "TSImportEqualsDeclaration") declare(node.id, scope);
191
+ else if (node.type === "TSModuleDeclaration" && node.kind === "namespace") declare(node.id, scope);
191
192
  });
192
193
  return (node, name = node.name) => {
193
194
  let scope = scopes.get(node);
@@ -324,11 +325,18 @@ function findModuleEntry(config, moduleName) {
324
325
  function defaultExport(module) {
325
326
  return typeof module === "object" && module !== null && "default" in module ? module.default : module;
326
327
  }
328
+ const previousHelpers = /* @__PURE__ */ new WeakMap();
327
329
  /** Runs nuxt.config with a `defineNuxtConfig` stub and returns the exported object. */
328
330
  async function loadNuxtConfig(path) {
329
- const hadPrevious = Reflect.has(globalThis, "defineNuxtConfig");
330
- const previous = Reflect.get(globalThis, "defineNuxtConfig");
331
- Reflect.set(globalThis, "defineNuxtConfig", (config) => config);
331
+ const key = "defineNuxtConfig";
332
+ const current = Reflect.get(globalThis, key);
333
+ const helper = typeof current === "function" && "count" in current && typeof current.count === "number" ? current : Object.assign((config) => config, { count: 0 });
334
+ if (helper !== current) {
335
+ const previous = Object.getOwnPropertyDescriptor(globalThis, key);
336
+ if (previous) previousHelpers.set(helper, previous);
337
+ Reflect.set(globalThis, key, helper);
338
+ }
339
+ helper.count++;
332
340
  try {
333
341
  const loaded = defaultExport(await createJiti(path, {
334
342
  moduleCache: false,
@@ -342,8 +350,11 @@ async function loadNuxtConfig(path) {
342
350
  if (isCodemodError(error)) throw error;
343
351
  throw codemodError(`Cannot load ${path} to read the $schema: ${error instanceof Error ? error.message : String(error)}`);
344
352
  } finally {
345
- if (hadPrevious) Reflect.set(globalThis, "defineNuxtConfig", previous);
346
- else Reflect.deleteProperty(globalThis, "defineNuxtConfig");
353
+ if (--helper.count === 0 && Reflect.get(globalThis, key) === helper) {
354
+ const previous = previousHelpers.get(helper);
355
+ if (previous) Object.defineProperty(globalThis, key, previous);
356
+ else Reflect.deleteProperty(globalThis, key);
357
+ }
347
358
  }
348
359
  }
349
360
  function nitroPreset(config) {
@@ -372,7 +383,7 @@ const defines = new Map([["defineRealtime", {
372
383
  /** Files whose default export is a definition, also as a plain object. */
373
384
  const definitionFiles = [[/(?:^|\/)server\/realtime\/.+$/, "realtime"], [/(?:^|\/)server\/mcp\/(?:tools|prompts|resources)\/.+$/, "mcp"]];
374
385
  const sourcePatterns$19 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}"];
375
- const ignoredPatterns$19 = [
386
+ const ignoredPatterns$21 = [
376
387
  "**/node_modules/**",
377
388
  "**/.nuxt/**",
378
389
  "**/.output/**",
@@ -465,16 +476,16 @@ function rewriteMcp(context, object) {
465
476
  message: "MCP replaced `public: true` with `access: \"public\"` on tools, prompts, and resources. Set `access: \"public\"` when this value is `true`, else remove `public`."
466
477
  });
467
478
  }
468
- function rewrite$2(context, kind, node) {
479
+ function rewrite$4(context, kind, node) {
469
480
  const object = node && unwrapExpression(node);
470
481
  if (object?.type !== "ObjectExpression") return;
471
482
  if (kind === "realtime") rewriteRealtime(context, object);
472
483
  else rewriteMcp(context, object);
473
484
  }
474
- async function migrate$30({ cwd }) {
485
+ async function migrate$33({ cwd }) {
475
486
  const files = (await glob(sourcePatterns$19, {
476
487
  cwd,
477
- ignore: ignoredPatterns$19,
488
+ ignore: ignoredPatterns$21,
478
489
  dot: false
479
490
  })).sort();
480
491
  const edits = [];
@@ -509,10 +520,10 @@ async function migrate$30({ cwd }) {
509
520
  walk(program, (node) => {
510
521
  if (node.type === "CallExpression") {
511
522
  const kind = kindOf(node.callee);
512
- if (kind) rewrite$2(context, kind, node.arguments[0]);
523
+ if (kind) rewrite$4(context, kind, node.arguments[0]);
513
524
  return;
514
525
  }
515
- if (fileKind && node.type === "ExportDefaultDeclaration") rewrite$2(context, fileKind, node.declaration);
526
+ if (fileKind && node.type === "ExportDefaultDeclaration") rewrite$4(context, fileKind, node.declaration);
516
527
  });
517
528
  if (context.changed) edits.push({
518
529
  path: file,
@@ -533,13 +544,13 @@ const accessSpellings = {
533
544
  description: "Rename Realtime `auth: true` to `authorize: true`, and MCP `public: true` to `access: \"public\"`",
534
545
  usage: "[dir]",
535
546
  async detect({ cwd }) {
536
- const result = await migrate$30({ cwd });
547
+ const result = await migrate$33({ cwd });
537
548
  const [edit] = result.edits;
538
549
  if (edit) return { reason: `${edit.path} sets Realtime \`auth\` or MCP \`public\`` };
539
550
  const [followUp] = result.followUps;
540
551
  return followUp ? { reason: `${followUp.file} needs the Realtime \`authorize\` or MCP \`access\` change` } : void 0;
541
552
  },
542
- run: migrate$30
553
+ run: migrate$33
543
554
  };
544
555
  //#endregion
545
556
  //#region src/shared/bindings.ts
@@ -678,7 +689,7 @@ const providerKinds = /* @__PURE__ */ new Set([
678
689
  "sandbox"
679
690
  ]);
680
691
  const sourcePatterns$18 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,vue}"];
681
- const ignoredPatterns$18 = [
692
+ const ignoredPatterns$20 = [
682
693
  "**/node_modules/**",
683
694
  "**/.nuxt/**",
684
695
  "**/.output/**",
@@ -1041,11 +1052,11 @@ function rewriteBlock$4(context) {
1041
1052
  async function sourceFiles(cwd) {
1042
1053
  return (await glob(sourcePatterns$18, {
1043
1054
  cwd,
1044
- ignore: ignoredPatterns$18,
1055
+ ignore: ignoredPatterns$20,
1045
1056
  dot: false
1046
1057
  })).sort();
1047
1058
  }
1048
- async function migrate$29({ cwd }) {
1059
+ async function migrate$32({ cwd }) {
1049
1060
  const edits = [];
1050
1061
  const followUps = [];
1051
1062
  for (const file of await sourceFiles(cwd)) {
@@ -1121,7 +1132,7 @@ const agentSurface = {
1121
1132
  if (/\b(?:state|scheduler|sandbox)\s*:\s*\{\s*provider\s*:/.test(source)) return { reason: `${file} selects an Agent provider with \`provider\`` };
1122
1133
  }
1123
1134
  },
1124
- run: migrate$29
1135
+ run: migrate$32
1125
1136
  };
1126
1137
  //#endregion
1127
1138
  //#region src/auth-accessors/index.ts
@@ -1132,11 +1143,11 @@ const serverModules = /* @__PURE__ */ new Set([
1132
1143
  "#vitehub/auth/server"
1133
1144
  ]);
1134
1145
  /** The modules that exported `isGitHubOrgMember`. */
1135
- const rootModules = /* @__PURE__ */ new Set(["vite-hub/auth", "@vite-hub/auth"]);
1146
+ const rootModules$1 = /* @__PURE__ */ new Set(["vite-hub/auth", "@vite-hub/auth"]);
1136
1147
  /** The modules that exported `useSession`. */
1137
1148
  const vueModules = /* @__PURE__ */ new Set(["vite-hub/auth/vue", "@vite-hub/auth/vue"]);
1138
1149
  const sourcePatterns$17 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,vue}"];
1139
- const ignoredPatterns$17 = [
1150
+ const ignoredPatterns$19 = [
1140
1151
  "**/node_modules/**",
1141
1152
  "**/.nuxt/**",
1142
1153
  "**/.output/**",
@@ -1305,7 +1316,7 @@ function nonemptyOrganization(node) {
1305
1316
  /** `await isGitHubOrgMember(...)` becomes `!(await checkGitHubOrgMember(...))[0]`. */
1306
1317
  function rewriteGitHub(context) {
1307
1318
  const { program, block } = context;
1308
- const { named } = importsOf(program, rootModules, "isGitHubOrgMember");
1319
+ const { named } = importsOf(program, rootModules$1, "isGitHubOrgMember");
1309
1320
  for (const specifier of named) {
1310
1321
  const calls = [];
1311
1322
  const sites = references(context, specifier.local);
@@ -1320,7 +1331,7 @@ function rewriteGitHub(context) {
1320
1331
  followUp$7(context, node, "`isGitHubOrgMember()` was removed. Call `checkGitHubOrgMember()`, which returns `[error]`. Keep returning `false` for an empty organization if your app allows one. Throw on `AUTH_GITHUB_UNAVAILABLE` in `access.policy.allow`, so a GitHub outage does not end every session.");
1321
1332
  }
1322
1333
  if (calls.length !== sites.length) continue;
1323
- const check = replacementBinding(context, specifier, rootModules, "checkGitHubOrgMember", sites.map(({ node }) => node));
1334
+ const check = replacementBinding(context, specifier, rootModules$1, "checkGitHubOrgMember", sites.map(({ node }) => node));
1324
1335
  for (const { node, awaited } of calls) {
1325
1336
  overwrite$5(context, node, check);
1326
1337
  context.output.appendRight(block.offset + start(awaited), "(!(");
@@ -1336,10 +1347,10 @@ function reportSession(context) {
1336
1347
  const [free] = references(context, void 0, "useSession").filter(({ node, parent }) => parent?.type === "CallExpression" && parent.callee === node);
1337
1348
  if (free) followUp$7(context, free.node, useSessionMessage);
1338
1349
  }
1339
- async function migrate$28({ cwd }) {
1350
+ async function migrate$31({ cwd }) {
1340
1351
  const files = (await glob(sourcePatterns$17, {
1341
1352
  cwd,
1342
- ignore: ignoredPatterns$17,
1353
+ ignore: ignoredPatterns$19,
1343
1354
  dot: false
1344
1355
  })).sort();
1345
1356
  const edits = [];
@@ -1401,13 +1412,13 @@ const authAccessors = {
1401
1412
  description: "Replace Auth's `auth` and `getAuth()` with `useAuth()`, `isGitHubOrgMember()` with `checkGitHubOrgMember()`, and list `useSession()` calls",
1402
1413
  usage: "[dir]",
1403
1414
  async detect({ cwd }) {
1404
- const result = await migrate$28({ cwd });
1415
+ const result = await migrate$31({ cwd });
1405
1416
  const [edit] = result.edits;
1406
1417
  if (edit) return { reason: `${edit.path} uses a removed Auth accessor` };
1407
1418
  const [followUp] = result.followUps;
1408
1419
  return followUp ? { reason: `${followUp.file} uses a removed Auth accessor` } : void 0;
1409
1420
  },
1410
- run: migrate$28
1421
+ run: migrate$31
1411
1422
  };
1412
1423
  //#endregion
1413
1424
  //#region src/auth-sign-in/index.ts
@@ -1420,7 +1431,7 @@ const ignored$7 = [
1420
1431
  "**/.vitehub/**",
1421
1432
  "**/dist/**"
1422
1433
  ];
1423
- function parse$3(code, file) {
1434
+ function parse$4(code, file) {
1424
1435
  try {
1425
1436
  return {
1426
1437
  code,
@@ -1585,7 +1596,7 @@ function editDefinition(file, parsed, moved, followUps) {
1585
1596
  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(", ")} }`]);
1586
1597
  return output.hasChanged() ? output.toString() : void 0;
1587
1598
  }
1588
- async function migrate$27({ cwd }) {
1599
+ async function migrate$30({ cwd }) {
1589
1600
  const edits = [];
1590
1601
  const followUps = [];
1591
1602
  const redirects = [];
@@ -1596,7 +1607,7 @@ async function migrate$27({ cwd }) {
1596
1607
  })).sort()) {
1597
1608
  const code = await readFile(join(cwd, file), "utf8");
1598
1609
  if (!/\bredirects\b/.test(code)) continue;
1599
- const parsed = parse$3(code, file);
1610
+ const parsed = parse$4(code, file);
1600
1611
  if (!parsed) continue;
1601
1612
  configFiles.set(file, code);
1602
1613
  for (const auth of new Set(authOptionProperties(parsed.program))) {
@@ -1660,7 +1671,7 @@ async function migrate$27({ cwd }) {
1660
1671
  });
1661
1672
  } else if (definition) {
1662
1673
  const code = await readFile(join(cwd, definition), "utf8");
1663
- const parsed = /\bdefineAuth\b/.test(code) ? parse$3(code, definition) : void 0;
1674
+ const parsed = /\bdefineAuth\b/.test(code) ? parse$4(code, definition) : void 0;
1664
1675
  if (!parsed && redirects.length) followUps.push({
1665
1676
  file: definition,
1666
1677
  message: "Move `auth.redirects` by hand: the codemod could not read the Auth Definition."
@@ -1696,18 +1707,45 @@ const authSignIn = {
1696
1707
  description: "Move `vitehub({ auth: { redirects } })` and `access.signIn.callbackURL` to `access: { signIn, afterSignIn }` in server/auth.ts",
1697
1708
  usage: "[dir]",
1698
1709
  async detect({ cwd }) {
1699
- const result = await migrate$27({ cwd });
1710
+ const result = await migrate$30({ cwd });
1700
1711
  const [edit] = result.edits;
1701
1712
  if (edit) return { reason: `${edit.path} sets an Auth sign-in page in the old place` };
1702
1713
  const [followUp] = result.followUps;
1703
1714
  return followUp ? { reason: `${followUp.file} sets an Auth sign-in page in the old place` } : void 0;
1704
1715
  },
1705
- run: migrate$27
1716
+ run: migrate$30
1706
1717
  };
1707
1718
  //#endregion
1719
+ //#region src/shared/module-source.ts
1720
+ /** The literal module reference in ESM, CommonJS, and TypeScript imports. */
1721
+ function moduleSource(node) {
1722
+ if (node.type === "ImportDeclaration" || node.type === "ExportAllDeclaration") return node.source;
1723
+ if (node.type === "ExportNamedDeclaration") return node.source ?? void 0;
1724
+ if (node.type === "ImportExpression") return node.source.type === "StringLiteral" ? node.source : void 0;
1725
+ if (node.type === "CallExpression" && (node.callee.type === "Import" || node.callee.type === "Identifier" && node.callee.name === "require")) return node.arguments[0]?.type === "StringLiteral" ? node.arguments[0] : void 0;
1726
+ if (node.type === "TSExternalModuleReference") return node.expression;
1727
+ if (node.type === "TSImportType") return node.argument;
1728
+ }
1729
+ //#endregion
1708
1730
  //#region src/channels/index.ts
1709
1731
  /** Modules that exported `http()`. `http(options)` is now `channelAdapter("http", options)`. */
1710
1732
  const httpModules = /* @__PURE__ */ new Set(["vite-hub/agent/channels", "@vite-hub/agent/channels"]);
1733
+ const movedPath = "vite-hub/agent/channels";
1734
+ const adaptersPath = "vite-hub/channels/adapters";
1735
+ const channelsPath = "vite-hub/channels";
1736
+ const channelNames = /* @__PURE__ */ new Set([
1737
+ "defineChannelTrigger",
1738
+ "ignored",
1739
+ "rejected",
1740
+ "retryLater"
1741
+ ]);
1742
+ const rootModules = /* @__PURE__ */ new Set([channelsPath, "@vite-hub/channels"]);
1743
+ const rootAdapterNames = /* @__PURE__ */ new Set([
1744
+ "webhook",
1745
+ "stripe",
1746
+ "StripeEvent",
1747
+ "StripeAdapterOptions"
1748
+ ]);
1711
1749
  /** Calls whose first argument names a module, such as `vi.mock("vite-hub/agent/channels")`. */
1712
1750
  const moduleCalls$4 = /* @__PURE__ */ new Set([
1713
1751
  "mock",
@@ -1718,7 +1756,7 @@ const moduleCalls$4 = /* @__PURE__ */ new Set([
1718
1756
  "importMock"
1719
1757
  ]);
1720
1758
  const sourcePatterns$16 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,vue}"];
1721
- const ignoredPatterns$16 = [
1759
+ const ignoredPatterns$18 = [
1722
1760
  "**/node_modules/**",
1723
1761
  "**/.nuxt/**",
1724
1762
  "**/.output/**",
@@ -1727,11 +1765,17 @@ const ignoredPatterns$16 = [
1727
1765
  "**/dist/**",
1728
1766
  "**/coverage/**"
1729
1767
  ];
1730
- const needle$3 = /vite-hub\/agent\/channels|\bhttp\b|\b(?:webhook|stripe)\b|\bsecretToken\b/;
1768
+ const needle$3 = /vite-hub\/agent\/channels|\bhttp\b|\b(?:webhook|stripe)\b|\bsecretToken\b|vite-hub\/channels/;
1731
1769
  /** Modules whose import marks a file with Agent webhook registrations, in `webhooks` of a Channel or a trigger. */
1732
1770
  const agentModules = /^(?:@?vite-hub\/(?:agent|channels)(?:\/|$)|vite-hub\/agent\/)/;
1733
1771
  /** Modules that export `webhook()` and `stripe()`, whose `secret` and `signature` follow Webhooks now. */
1734
- const webhookModules = /* @__PURE__ */ new Set(["vite-hub/channels", "@vite-hub/channels"]);
1772
+ const webhookModules = /* @__PURE__ */ new Set([
1773
+ "vite-hub/channels",
1774
+ "@vite-hub/channels",
1775
+ "vite-hub/channels/adapters",
1776
+ "@vite-hub/channels/adapters",
1777
+ "@vite-hub/agent/channels"
1778
+ ]);
1735
1779
  /** Signature names before they followed `defineWebhook({ signature })`. */
1736
1780
  const renamedSignatures = /* @__PURE__ */ new Map([["github-sha256", "github"], ["stripe-sha256", "stripe"]]);
1737
1781
  const variableName = /^[A-Z_][A-Z0-9_]*$/i;
@@ -1776,6 +1820,11 @@ function importedName$7(specifier) {
1776
1820
  return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
1777
1821
  }
1778
1822
  const manualHttp = "`http()` was removed. Use `channelAdapter(\"http\", options)` from the same module to keep the Channel kind.";
1823
+ function mockSource(node) {
1824
+ if (node.type !== "CallExpression" || node.callee.type !== "MemberExpression" || node.callee.property.type !== "Identifier" || !moduleCalls$4.has(node.callee.property.name)) return;
1825
+ const first = node.arguments[0];
1826
+ return first?.type === "StringLiteral" ? first : first && moduleSource(first);
1827
+ }
1779
1828
  function reportIndirectUses(context) {
1780
1829
  const mocked = /* @__PURE__ */ new Set();
1781
1830
  walk(context.program, (node, ancestors) => {
@@ -1792,20 +1841,17 @@ function reportIndirectUses(context) {
1792
1841
  return;
1793
1842
  }
1794
1843
  if (node.type !== "CallExpression" && node.type !== "ImportExpression") return;
1795
- const callee = node.type === "CallExpression" ? node.callee : void 0;
1796
- const first = node.type === "CallExpression" ? node.arguments[0] : node.source;
1797
- const source = first?.type === "ImportExpression" ? first.source : first?.type === "CallExpression" && first.callee.type === "Import" ? first.arguments[0] : first;
1798
- if (source?.type !== "StringLiteral" || !httpModules.has(source.value)) return;
1799
- if (callee?.type === "MemberExpression" && callee.property.type === "Identifier" && moduleCalls$4.has(callee.property.name)) {
1844
+ const mock = mockSource(node);
1845
+ const source = mock ?? moduleSource(node);
1846
+ if (!source || !httpModules.has(source.value)) return;
1847
+ if (mock) {
1800
1848
  mocked.add(source.value);
1801
1849
  followUp$6(context, node, `Check this mock for the removed http export. Update the mock and its callers together. ${manualHttp}`);
1802
1850
  return;
1803
1851
  }
1804
- if (node.type === "ImportExpression" || callee?.type === "Import" || callee?.type === "Identifier" && callee.name === "require") {
1805
- const parent = ancestors.at(-1);
1806
- if (parent?.type === "CallExpression" && parent.callee.type === "MemberExpression" && parent.callee.property.type === "Identifier" && moduleCalls$4.has(parent.callee.property.name)) return;
1807
- followUp$6(context, node, `Check this module load for references to the removed http export. ${manualHttp}`);
1808
- }
1852
+ const parent = ancestors.at(-1);
1853
+ if (parent && mockSource(parent) === source) return;
1854
+ followUp$6(context, node, `Check this module load for references to the removed http export. ${manualHttp}`);
1809
1855
  });
1810
1856
  return mocked;
1811
1857
  }
@@ -2040,10 +2086,145 @@ function rewriteWebhookOptions(context) {
2040
2086
  if (tolerance) renameTolerance(context, tolerance);
2041
2087
  });
2042
2088
  }
2043
- async function migrate$26({ cwd }) {
2089
+ function moveSource(context, source, to) {
2090
+ overwrite$4(context, source, quoteString(to, context.style));
2091
+ }
2092
+ function takeSpecifiers(context, statement, source, moved) {
2093
+ const { block, output } = context;
2094
+ const remove = (from, to) => output.remove(block.offset + from, block.offset + to);
2095
+ const selected = new Set(moved);
2096
+ for (const [index, specifier] of statement.specifiers.entries()) {
2097
+ if (!selected.has(specifier)) continue;
2098
+ const next = statement.specifiers[index + 1];
2099
+ const previous = statement.specifiers[index - 1];
2100
+ const after = block.code.slice(end(specifier), next ? start(next) : start(source));
2101
+ const trivia = /^(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\r\n]*)*/.exec(after)?.[0] ?? "";
2102
+ const separator = /^,[ \t]*/.exec(after.slice(trivia.length))?.[0];
2103
+ if (separator) {
2104
+ const comma = end(specifier) + trivia.length;
2105
+ if (trivia.includes("/")) {
2106
+ remove(start(specifier), end(specifier));
2107
+ remove(comma, comma + separator.length);
2108
+ } else remove(start(specifier), comma + separator.length);
2109
+ } else {
2110
+ const before = previous && block.code.slice(end(previous), start(specifier));
2111
+ remove(before && !selected.has(previous) && /^\s*,\s*$/.test(before) ? end(previous) : start(specifier), end(specifier));
2112
+ }
2113
+ }
2114
+ return moved.map((specifier) => block.code.slice(start(specifier), end(specifier))).join(", ");
2115
+ }
2116
+ function nameUsage(name) {
2117
+ return name === void 0 ? "unknown" : rootAdapterNames.has(name) ? "adapters" : "root";
2118
+ }
2119
+ function adapterUsage(node, parent) {
2120
+ if ((parent?.type === "MemberExpression" || parent?.type === "OptionalMemberExpression") && parent.object === node) return nameUsage(keyName(parent.property, parent.computed));
2121
+ if (parent?.type === "TSQualifiedName" && parent.left === node) return nameUsage(parent.right.name);
2122
+ if (parent?.type === "VariableDeclarator" && parent.init === node && parent.id.type === "ObjectPattern") {
2123
+ const uses = new Set(parent.id.properties.map((prop) => nameUsage(prop.type === "ObjectProperty" ? keyName(prop.key, prop.computed) : void 0)));
2124
+ return uses.size === 1 ? [...uses][0] ?? "unknown" : "unknown";
2125
+ }
2126
+ return "unknown";
2127
+ }
2128
+ function reportAdapterSplit(context, node, root) {
2129
+ followUp$6(context, node, `Check for webhook and stripe exports (including their types). Import them from \`${root}/adapters\` and keep other names on \`${root}\`.`);
2130
+ }
2131
+ function moveRootAdapters(context) {
2132
+ const { block, output, program, style } = context;
2133
+ const semicolon = style.semicolons ? ";" : "";
2134
+ const changed = /* @__PURE__ */ new Set();
2135
+ const resolve = bindingResolver(program);
2136
+ for (const statement of program.program.body) {
2137
+ if (statement.type !== "ImportDeclaration" && statement.type !== "ExportNamedDeclaration" && statement.type !== "ExportAllDeclaration") continue;
2138
+ const source = statement.source;
2139
+ if (!source || !rootModules.has(source.value)) continue;
2140
+ const adaptersSource = `${source.value}/adapters`;
2141
+ if (statement.type === "ExportAllDeclaration" || statement.type === "ExportNamedDeclaration" && statement.specifiers.some((specifier) => specifier.type === "ExportNamespaceSpecifier")) {
2142
+ reportAdapterSplit(context, statement, source.value);
2143
+ continue;
2144
+ }
2145
+ const namespace = statement.specifiers.find((specifier) => specifier.type === "ImportNamespaceSpecifier");
2146
+ if (namespace) {
2147
+ let needsSplit = block.templateNames?.has(namespace.local.name) || block.hasExternalTemplate || block.hasOtherScript;
2148
+ walk(program, (node, ancestors) => {
2149
+ const parent = ancestors.at(-1);
2150
+ if (isReference(node, parent) && resolve(node) === namespace.local && adapterUsage(node, parent) !== "root") needsSplit = true;
2151
+ });
2152
+ if (needsSplit) reportAdapterSplit(context, namespace, source.value);
2153
+ continue;
2154
+ }
2155
+ const moved = statement.specifiers.filter((specifier) => {
2156
+ return nameUsage(specifier.type === "ExportSpecifier" ? keyName(specifier.local) : specifier.type === "ImportSpecifier" ? keyName(specifier.imported) : void 0) === "adapters";
2157
+ });
2158
+ if (!moved.length) continue;
2159
+ if (statement.type === "ImportDeclaration") changed.add(statement);
2160
+ if (moved.length === statement.specifiers.length) {
2161
+ moveSource(context, source, adaptersSource);
2162
+ continue;
2163
+ }
2164
+ const names = takeSpecifiers(context, statement, source, moved);
2165
+ const keyword = statement.type === "ImportDeclaration" ? statement.importKind === "type" ? "import type" : "import" : statement.exportKind === "type" ? "export type" : "export";
2166
+ output.appendLeft(block.offset + end(statement), `\n${keyword} { ${names} } from ${quoteString(adaptersSource, style)}${semicolon}`);
2167
+ }
2168
+ return changed;
2169
+ }
2170
+ function moveImports(context, changed) {
2171
+ const { block, output, program, style } = context;
2172
+ const semicolon = style.semicolons ? ";" : "";
2173
+ const channelImports = /* @__PURE__ */ new Map();
2174
+ for (const statement of program.program.body) {
2175
+ if (statement.type !== "ImportDeclaration" || statement.source.value !== channelsPath || changed.has(statement)) continue;
2176
+ if (statement.specifiers.length && statement.specifiers.every((specifier) => specifier.type === "ImportSpecifier")) channelImports.set(statement.importKind ?? "value", statement);
2177
+ }
2178
+ for (const statement of program.program.body) {
2179
+ if ((statement.type === "ExportAllDeclaration" || statement.type === "ExportNamedDeclaration") && statement.source?.value === movedPath) {
2180
+ moveSource(context, statement.source, adaptersPath);
2181
+ continue;
2182
+ }
2183
+ if (statement.type !== "ImportDeclaration" || statement.source.value !== movedPath) continue;
2184
+ const moved = statement.specifiers.length > 0 && statement.specifiers.every((specifier) => specifier.type === "ImportSpecifier") ? statement.specifiers.filter((specifier) => channelNames.has(importedName$7(specifier) ?? "")) : [];
2185
+ if (moved.length && moved.length === statement.specifiers.length) {
2186
+ moveSource(context, statement.source, channelsPath);
2187
+ continue;
2188
+ }
2189
+ moveSource(context, statement.source, adaptersPath);
2190
+ if (!moved.length) continue;
2191
+ const names = takeSpecifiers(context, statement, statement.source, moved);
2192
+ const kind = statement.importKind ?? "value";
2193
+ const target = channelImports.get(kind);
2194
+ if (target) {
2195
+ output.appendLeft(block.offset + end(target.specifiers.at(-1)), `, ${names}`);
2196
+ continue;
2197
+ }
2198
+ const keyword = kind === "type" ? "import type" : "import";
2199
+ output.appendLeft(block.offset + end(statement), `\n${keyword} { ${names} } from ${quoteString(channelsPath, style)}${semicolon}`);
2200
+ }
2201
+ walk(program, (node, ancestors) => {
2202
+ if (node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") return;
2203
+ const mock = mockSource(node);
2204
+ const source = mock ?? moduleSource(node);
2205
+ if (!source) return;
2206
+ const parent = ancestors.at(-1);
2207
+ if (parent && mockSource(parent) === source) return;
2208
+ if (source.value === movedPath) {
2209
+ moveSource(context, source, adaptersPath);
2210
+ if (mock) followUp$6(context, node, "This mock now replaces `vite-hub/channels/adapters`. `defineChannelTrigger`, `ignored`, `retryLater`, and `rejected` also come from `vite-hub/channels`: mock that path too when the code under test imports them from it.");
2211
+ return;
2212
+ }
2213
+ if (!rootModules.has(source.value)) return;
2214
+ let usage;
2215
+ if (node.type === "TSImportType" && node.qualifier) {
2216
+ let qualifier = node.qualifier;
2217
+ while (qualifier.type === "TSQualifiedName") qualifier = qualifier.left;
2218
+ usage = nameUsage(qualifier.name);
2219
+ } else usage = parent?.type === "AwaitExpression" && parent.argument === node ? adapterUsage(parent, ancestors.at(-2)) : adapterUsage(node, parent);
2220
+ if (usage === "adapters") moveSource(context, source, `${source.value}/adapters`);
2221
+ else if (usage === "unknown") reportAdapterSplit(context, node, source.value);
2222
+ });
2223
+ }
2224
+ async function migrate$29({ cwd }) {
2044
2225
  const files = (await glob(sourcePatterns$16, {
2045
2226
  cwd,
2046
- ignore: ignoredPatterns$16,
2227
+ ignore: ignoredPatterns$18,
2047
2228
  dot: false
2048
2229
  })).sort();
2049
2230
  const edits = [];
@@ -2078,6 +2259,7 @@ async function migrate$26({ cwd }) {
2078
2259
  style: detectStyle(block.code, program)
2079
2260
  };
2080
2261
  replaceHttp(context);
2262
+ moveImports(context, moveRootAdapters(context));
2081
2263
  rewriteWebhookOptions(context);
2082
2264
  rewriteAgentRegistrations(context);
2083
2265
  changed = output.toString() !== before || changed;
@@ -2089,7 +2271,7 @@ async function migrate$26({ cwd }) {
2089
2271
  });
2090
2272
  }
2091
2273
  return {
2092
- summary: edits.length ? `replaced http() and moved webhook options in ${edits.length} file(s)` : "no http() call or webhook option changed",
2274
+ summary: edits.length ? `moved Channel imports, replaced http(), and moved webhook options in ${edits.length} file(s)` : "no Channel import, http() call, or webhook option changed",
2093
2275
  edits,
2094
2276
  followUps,
2095
2277
  notes: [],
@@ -2098,32 +2280,21 @@ async function migrate$26({ cwd }) {
2098
2280
  }
2099
2281
  const channels = {
2100
2282
  name: "channels",
2101
- description: "Replace the Agent `http()` adapter with `channelAdapter(\"http\")`, and move `webhook()`, `stripe()`, and Agent webhook registrations to `secret` names and Webhooks signature names",
2283
+ 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",
2102
2284
  usage: "[dir]",
2103
2285
  async detect({ cwd }) {
2104
- const result = await migrate$26({ cwd });
2286
+ const result = await migrate$29({ cwd });
2105
2287
  const [edit] = result.edits;
2106
- if (edit) return { reason: `${edit.path} calls the Agent \`http()\` adapter or sets an old webhook option` };
2288
+ if (edit) return { reason: `${edit.path} imports an old Channel path, calls the Agent \`http()\` adapter, or sets an old webhook option` };
2107
2289
  const [followUp] = result.followUps;
2108
2290
  return followUp ? { reason: `${followUp.file} needs a manual Agent Channel migration` } : void 0;
2109
2291
  },
2110
- run: migrate$26
2292
+ run: migrate$29
2111
2293
  };
2112
2294
  //#endregion
2113
- //#region src/shared/module-source.ts
2114
- /** The literal module reference in ESM, CommonJS, and TypeScript imports. */
2115
- function moduleSource(node) {
2116
- if (node.type === "ImportDeclaration" || node.type === "ExportAllDeclaration") return node.source;
2117
- if (node.type === "ExportNamedDeclaration") return node.source ?? void 0;
2118
- if (node.type === "ImportExpression") return node.source.type === "StringLiteral" ? node.source : void 0;
2119
- if (node.type === "CallExpression" && (node.callee.type === "Import" || node.callee.type === "Identifier" && node.callee.name === "require")) return node.arguments[0]?.type === "StringLiteral" ? node.arguments[0] : void 0;
2120
- if (node.type === "TSExternalModuleReference") return node.expression;
2121
- if (node.type === "TSImportType") return node.argument;
2122
- }
2123
- //#endregion
2124
2295
  //#region src/choices-package/index.ts
2125
2296
  const sourcePatterns$15 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,vue}", "**/package.json"];
2126
- const ignoredPatterns$15 = [
2297
+ const ignoredPatterns$17 = [
2127
2298
  "**/node_modules/**",
2128
2299
  "**/.nuxt/**",
2129
2300
  "**/.output/**",
@@ -2268,13 +2439,13 @@ function migrateSource(file, code, followUps) {
2268
2439
  }
2269
2440
  return output.toString();
2270
2441
  }
2271
- async function migrate$25({ cwd }) {
2442
+ async function migrate$28({ cwd }) {
2272
2443
  const edits = [];
2273
2444
  const followUps = [];
2274
2445
  const changedDependencies = /* @__PURE__ */ new Set();
2275
2446
  for (const file of (await glob(sourcePatterns$15, {
2276
2447
  cwd,
2277
- ignore: ignoredPatterns$15
2448
+ ignore: ignoredPatterns$17
2278
2449
  })).sort()) {
2279
2450
  const code = await readFile(join(cwd, file), "utf8");
2280
2451
  if (!code.includes("decisions")) continue;
@@ -2298,21 +2469,21 @@ const choicesPackage = {
2298
2469
  description: "Rename `@vite-hub/decisions` to `@vite-hub/choices`, `vite-hub/decisions` to `vite-hub/choices`, and `vitehub decisions` to `vitehub choices`",
2299
2470
  usage: "[dir]",
2300
2471
  async detect({ cwd }) {
2301
- const { edits, followUps } = await migrate$25({ cwd });
2472
+ const { edits, followUps } = await migrate$28({ cwd });
2302
2473
  const file = edits[0]?.path ?? followUps[0]?.file;
2303
2474
  return file ? { reason: `Found a Decisions reference in ${file}` } : void 0;
2304
2475
  },
2305
- run: migrate$25
2476
+ run: migrate$28
2306
2477
  };
2307
2478
  //#endregion
2308
2479
  //#region src/shared/cli-calls.ts
2309
2480
  /** Files that call the `vitehub` CLI: package scripts, CI workflows, and shell scripts. */
2310
- const callerPatterns = [
2481
+ const callerPatterns$1 = [
2311
2482
  "**/package.json",
2312
2483
  ".github/workflows/*.{yml,yaml}",
2313
2484
  "**/*.sh"
2314
2485
  ];
2315
- const ignoredPatterns$14 = [
2486
+ const ignoredPatterns$16 = [
2316
2487
  "**/node_modules/**",
2317
2488
  "**/.nuxt/**",
2318
2489
  "**/.output/**",
@@ -2372,7 +2543,7 @@ function findCliCalls(source, posix) {
2372
2543
  }];
2373
2544
  });
2374
2545
  }
2375
- function rewriteShell(source, posix, rewrite) {
2546
+ function rewriteShell$1(source, posix, rewrite) {
2376
2547
  let after = "";
2377
2548
  let offset = 0;
2378
2549
  for (const { start, end, call } of findCliCalls(source, posix) ?? []) {
@@ -2413,18 +2584,18 @@ function rewriteWorkflow(source, transform, report) {
2413
2584
  }
2414
2585
  return edited.toString();
2415
2586
  }
2416
- async function rewriteCliCalls(cwd, rewrite, manual) {
2417
- const files = (await glob(callerPatterns, {
2587
+ async function rewriteCliCalls$1(cwd, rewrite, manual) {
2588
+ const files = (await glob(callerPatterns$1, {
2418
2589
  cwd,
2419
2590
  dot: true,
2420
- ignore: ignoredPatterns$14
2591
+ ignore: ignoredPatterns$16
2421
2592
  })).sort();
2422
2593
  const edits = [];
2423
2594
  const followUps = [];
2424
2595
  let calls = 0;
2425
2596
  for (const file of files) {
2426
2597
  const before = await readFile(join(cwd, file), "utf8");
2427
- const transform = (source, posix) => rewriteShell(source, posix, (call) => {
2598
+ const transform = (source, posix) => rewriteShell$1(source, posix, (call) => {
2428
2599
  const next = rewrite(call);
2429
2600
  if (next !== call.command) calls++;
2430
2601
  return next;
@@ -2479,6 +2650,382 @@ async function rewriteCliCalls(cwd, rewrite, manual) {
2479
2650
  };
2480
2651
  }
2481
2652
  //#endregion
2653
+ //#region src/cli-agent-tree/index.ts
2654
+ const renames$1 = [
2655
+ [
2656
+ "agents",
2657
+ ["list", "invoke"],
2658
+ "agent"
2659
+ ],
2660
+ [
2661
+ "invocations",
2662
+ [
2663
+ "cancel",
2664
+ "undo",
2665
+ "capabilities",
2666
+ "workspace"
2667
+ ],
2668
+ "agent invocations"
2669
+ ],
2670
+ [
2671
+ "conversations",
2672
+ ["export"],
2673
+ "agent conversations"
2674
+ ]
2675
+ ];
2676
+ const inspectionFollowUp = "Move --agent to the name in `vitehub agent get <name>`. For old `agents status` calls, pass the Console app's --url; for Dev Loop calls with a URL, use --dev --url.";
2677
+ function unquote$1(word) {
2678
+ return word.replace(/^(['"])(.*)\1$/, "$2");
2679
+ }
2680
+ function hasOption(words, flag) {
2681
+ return words.some((word) => unquote$1(word) === flag || unquote$1(word).startsWith(`${flag}=`));
2682
+ }
2683
+ function rewriteInspection(options, status) {
2684
+ let name;
2685
+ let url = false;
2686
+ let dev = false;
2687
+ const tail = [];
2688
+ for (let index = 0; index < options.length; index++) {
2689
+ const option = options[index];
2690
+ if (!status && option === "--dev") {
2691
+ dev = true;
2692
+ continue;
2693
+ }
2694
+ if ([
2695
+ "--json",
2696
+ "--help",
2697
+ "-h"
2698
+ ].includes(option)) {
2699
+ tail.push(option);
2700
+ continue;
2701
+ }
2702
+ const flag = option.split("=", 1)[0];
2703
+ if (flag !== "--agent" && flag !== "--url") return void 0;
2704
+ const separate = option === flag;
2705
+ const value = separate ? options[++index] : option.slice(flag.length + 1);
2706
+ if (!value || unquote$1(value).startsWith("-")) return void 0;
2707
+ if (flag === "--agent") {
2708
+ if (name || !/^[\w.][\w.-]*$/.test(unquote$1(value))) return void 0;
2709
+ name = value;
2710
+ } else {
2711
+ if (url) return void 0;
2712
+ url = true;
2713
+ if (separate) tail.push("--url", value);
2714
+ else tail.push(`--url=${value}`);
2715
+ }
2716
+ }
2717
+ if (!name || status && !url) return void 0;
2718
+ return [
2719
+ "agent get",
2720
+ name,
2721
+ ...dev || !status && url ? ["--dev"] : [],
2722
+ ...tail
2723
+ ].join(" ");
2724
+ }
2725
+ function rewrite$3({ command, words }) {
2726
+ const [namespace, action, ...rest] = words;
2727
+ if (!namespace || !action) return command;
2728
+ const options = rest.map((word) => word.text);
2729
+ const prefix = command.slice(0, namespace.start);
2730
+ const inspection = namespace.text === "agents" && action.text === "status" ? rewriteInspection(options, true) : namespace.text === "agent" && action.text === "get" && hasOption(options, "--agent") ? rewriteInspection(options, false) : void 0;
2731
+ if (inspection) return `${prefix}${inspection}`;
2732
+ if (namespace.text === "invocations" && (hasOption(options, "--input") || (action.text === "cancel" || action.text === "undo") && !hasOption(options, "--url"))) return command;
2733
+ for (const [from, actions, to] of renames$1) if (namespace.text === from && actions.includes(action.text)) return `${prefix}${to} ${command.slice(action.start)}`;
2734
+ return command;
2735
+ }
2736
+ function manual$2(line) {
2737
+ if (/\bvitehub\s+(?:agents\s+status\b|agent\s+get\b.*--agent\b)/.test(line)) return inspectionFollowUp;
2738
+ if (/\bvitehub\s+invocations\s+delete\b/.test(line)) return "Select the same Console app explicitly with `vitehub agent invocations delete <id> --url <app>`; without --url the new command deletes from the journal file. Add --yes for a noninteractive script.";
2739
+ if (/\bvitehub\s+invocations\s+(?:list|get)\b/.test(line)) return "Review this Console Invocation read before moving it under `vitehub agent invocations`: list no longer exposes the Console cursor and get returns a flat record rather than the Console detail envelope. Check supported filters and observation options with --help, or keep using the invocations.list/get Console RPC when you need the old inputs or response.";
2740
+ 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.";
2741
+ 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.";
2742
+ }
2743
+ async function migrate$27({ cwd }) {
2744
+ const { calls, edits, followUps } = await rewriteCliCalls$1(cwd, rewrite$3, manual$2);
2745
+ return {
2746
+ 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",
2747
+ edits,
2748
+ followUps,
2749
+ notes: [],
2750
+ nextSteps: []
2751
+ };
2752
+ }
2753
+ const cliAgentTree = {
2754
+ name: "cli-agent-tree",
2755
+ description: "Move vitehub agents, invocations, and conversations calls of scripts and CI into the vitehub agent commands",
2756
+ detectAfterEdits: true,
2757
+ usage: "[dir]",
2758
+ async detect({ cwd }) {
2759
+ const { edits, followUps } = await migrate$27({ cwd });
2760
+ const file = edits[0]?.path ?? followUps[0]?.file;
2761
+ return file ? { reason: `${file} calls a vitehub Agent command that moved` } : void 0;
2762
+ },
2763
+ run: migrate$27
2764
+ };
2765
+ //#endregion
2766
+ //#region src/cli-get-list/cli-calls.ts
2767
+ const callerPatterns = [
2768
+ "**/package.json",
2769
+ ".github/workflows/*.{yml,yaml}",
2770
+ "**/*.sh"
2771
+ ];
2772
+ const ignoredPatterns$15 = [
2773
+ "**/node_modules/**",
2774
+ "**/.nuxt/**",
2775
+ "**/.output/**",
2776
+ "**/.data/**",
2777
+ "**/.vitehub/**",
2778
+ "**/dist/**",
2779
+ "**/coverage/**"
2780
+ ];
2781
+ function rewriteShell(shell, rewrite, followUp, changed) {
2782
+ if (/\$\(|`|<<|\\\r?\n/.test(shell) || /\$\[|\$\{(?![A-Za-z_]\w*\})/.test(shell)) return shell;
2783
+ const token = /[ \t\r]+|\n|#[^\n]*|&&|\|\||[;&|()<>]|(?:'[^']*'|"(?:\\[\s\S]|[^"\\])*"|\\[^\n]|[^\s'"\\;&|()<>])+/gy;
2784
+ const edits = new MagicString(shell);
2785
+ const commands = [[]];
2786
+ let redirected = false;
2787
+ for (let offset = 0; offset < shell.length;) {
2788
+ const match = token.exec(shell);
2789
+ if (!match) return shell;
2790
+ const [text] = match;
2791
+ if (/^[()]$/.test(text)) return shell;
2792
+ if (/^(?:\n|;|&&?|\|\|?)$/.test(text)) {
2793
+ commands.push([]);
2794
+ redirected = false;
2795
+ } else if (text === "<" || text === ">") redirected = true;
2796
+ else if (!redirected && !/^(?:\s|#)/.test(text)) commands.at(-1).push({
2797
+ start: offset,
2798
+ text
2799
+ });
2800
+ offset = token.lastIndex;
2801
+ }
2802
+ if (commands.some((words) => /^(?:case|for|select|function)$/.test(words[0]?.text ?? ""))) return shell;
2803
+ for (const words of commands) {
2804
+ let index = 0;
2805
+ while (/^[A-Za-z_][A-Za-z_0-9]*=/.test(words[index]?.text ?? "")) index++;
2806
+ if ([
2807
+ "pnpm",
2808
+ "npm",
2809
+ "npx",
2810
+ "yarn",
2811
+ "bun",
2812
+ "bunx"
2813
+ ].includes(words[index]?.text ?? "")) {
2814
+ const runner = words[index++].text;
2815
+ if ([
2816
+ "pnpm",
2817
+ "npm",
2818
+ "yarn",
2819
+ "bun"
2820
+ ].includes(runner) && words[index]?.text === "exec") index++;
2821
+ else if (runner === "npm") continue;
2822
+ }
2823
+ if (words[index]?.text !== "vitehub" || !words[index + 1]) continue;
2824
+ const args = words.slice(index + 1);
2825
+ const start = args[0].start;
2826
+ const last = args.at(-1);
2827
+ const end = last.start + last.text.length;
2828
+ const before = shell.slice(start, end);
2829
+ const after = rewrite(before, args.map((word) => ({
2830
+ ...word,
2831
+ start: word.start - start
2832
+ })));
2833
+ if (typeof after !== "string") followUp(after.message, start);
2834
+ else if (after !== before) {
2835
+ edits.overwrite(start, end, after);
2836
+ changed();
2837
+ }
2838
+ }
2839
+ return edits.toString();
2840
+ }
2841
+ function supportedShell(shell) {
2842
+ return typeof shell === "string" && /^(?:bash|sh)(?:\s|$)/.test(shell);
2843
+ }
2844
+ async function rewriteCliCalls(cwd, rewrite) {
2845
+ const files = (await glob(callerPatterns, {
2846
+ cwd,
2847
+ dot: true,
2848
+ ignore: ignoredPatterns$15
2849
+ })).sort();
2850
+ const edits = [];
2851
+ const followUps = [];
2852
+ let calls = 0;
2853
+ for (const file of files) {
2854
+ const before = await readFile(join(cwd, file), "utf8");
2855
+ const lineAt = (offset) => before.slice(0, offset).split("\n").length;
2856
+ const rewriteScript = (shell, line) => rewriteShell(shell, rewrite, (message, offset) => {
2857
+ followUps.push({
2858
+ file,
2859
+ line: line(offset),
2860
+ message
2861
+ });
2862
+ }, () => {
2863
+ calls++;
2864
+ });
2865
+ let after;
2866
+ if (file.endsWith(".sh")) after = rewriteScript(before, lineAt);
2867
+ else {
2868
+ const json = file.endsWith(".json");
2869
+ if (json) try {
2870
+ JSON.parse(before);
2871
+ } catch {
2872
+ continue;
2873
+ }
2874
+ const document = parseDocument(before);
2875
+ if (document.errors.length) continue;
2876
+ const output = new MagicString(before);
2877
+ const update = (node) => {
2878
+ if (!isScalar(node) || typeof node.value !== "string" || !node.range || node.anchor || node.tag) return;
2879
+ const [start, end] = node.range;
2880
+ if ((node.type === "BLOCK_FOLDED" || node.type === "BLOCK_LITERAL") && node.comment) return;
2881
+ const next = rewriteScript(node.value, () => lineAt(start));
2882
+ if (next === node.value) return;
2883
+ output.overwrite(start, end, `${JSON.stringify(next)}${before.slice(start, end).endsWith("\n") ? "\n" : ""}`);
2884
+ };
2885
+ if (json) {
2886
+ const scripts = document.get("scripts", true);
2887
+ if (isMap(scripts)) for (const script of scripts.items) update(script.value);
2888
+ } else {
2889
+ const jobs = document.get("jobs", true);
2890
+ if (isMap(jobs)) for (const { value: job } of jobs.items) {
2891
+ if (!isMap(job)) continue;
2892
+ const steps = job.get("steps", true);
2893
+ if (!isSeq(steps)) continue;
2894
+ for (const step of steps.items) {
2895
+ if (!isMap(step) || step.has("uses")) continue;
2896
+ const shell = step.get("shell") ?? job.getIn([
2897
+ "defaults",
2898
+ "run",
2899
+ "shell"
2900
+ ]) ?? document.getIn([
2901
+ "defaults",
2902
+ "run",
2903
+ "shell"
2904
+ ]);
2905
+ const runner = job.get("runs-on");
2906
+ if (shell !== void 0 ? !supportedShell(shell) : typeof runner !== "string" || !/^(?:ubuntu|macos)-/.test(runner)) continue;
2907
+ update(step.get("run", true));
2908
+ }
2909
+ }
2910
+ }
2911
+ after = output.toString();
2912
+ }
2913
+ if (after !== before) edits.push({
2914
+ after,
2915
+ before,
2916
+ path: file
2917
+ });
2918
+ }
2919
+ return {
2920
+ calls,
2921
+ edits,
2922
+ followUps
2923
+ };
2924
+ }
2925
+ //#endregion
2926
+ //#region src/cli-get-list/index.ts
2927
+ /** `get` reads one record and `list` reads many. Each entry rewrites the start of the arguments after `vitehub `. */
2928
+ const renames = [
2929
+ [/^agent\s+invocations\s+show(?=\s|$)/, "agent invocations get"],
2930
+ [/^content\s+show(?=\s|$)/, "content get"],
2931
+ [/^email\s+outbox\s+show(?=\s|$)/, "email outbox get"],
2932
+ [/^queue\s+jobs\s+show(?=\s|$)/, "queue jobs get"],
2933
+ [/^workspace\s+show(?=\s|$)/, "workspace get"],
2934
+ [/^schedule\s+attempts(?=\s|$)/, "schedule runs get"],
2935
+ [/^env\s+inspect(?=\s|$)/, "env list"],
2936
+ [/^project\s+info(?=\s|$)/, "project get"]
2937
+ ];
2938
+ function unquote(word) {
2939
+ return word.replace(/^(['"])(.*)\1$/, "$2");
2940
+ }
2941
+ function rewrite$2(args, words) {
2942
+ const [namespace, command, subcommand] = words.map((word) => word.text);
2943
+ if (namespace === "agent" && command === "info") {
2944
+ const end = words[1].start + command.length;
2945
+ return `agent get${words.slice(2).some((word) => /^--url(?:=|$)/.test(unquote(word.text))) ? " --dev" : ""}${args.slice(end)}`;
2946
+ }
2947
+ if (namespace === "definitions" && command === "list") return { message: "`definitions list` was removed. Use `vitehub inspect definitions --kind <kind>` for local definitions, or the Console for runtime records." };
2948
+ if (namespace === "schedule" && command === "runs" && subcommand && ![
2949
+ "list",
2950
+ "get",
2951
+ "-h",
2952
+ "--help"
2953
+ ].includes(unquote(subcommand))) return `schedule runs list${args.slice(words[1].start + 4)}`;
2954
+ if (namespace === "env" && command === "status") {
2955
+ const options = words.slice(2).map((word) => unquote(word.text));
2956
+ let url = false;
2957
+ let json = false;
2958
+ for (let index = 0; index < options.length; index++) {
2959
+ const option = options[index];
2960
+ if (option === "--json") json = true;
2961
+ else if (option === "--url" && options[index + 1] && !options[index + 1].startsWith("-")) {
2962
+ url = true;
2963
+ index++;
2964
+ } else if (/^--url=[^-].*$/.test(option)) url = true;
2965
+ else return { message: "Update `env status` to `vitehub env list --url <app> --json`. Review the old options: `env list` does not accept `--input` or `--timeout`." };
2966
+ }
2967
+ if (!url) return { message: "`env status` read a running dev server. Pass its URL explicitly to `vitehub env list --url <app> --json` to keep that target." };
2968
+ return `env list${json ? "" : " --json"}${args.slice(words[1].start + 6)}`;
2969
+ }
2970
+ if (namespace === "workflow" && (command === "get" || command === "runs" && subcommand === "show")) {
2971
+ const show = command === "runs";
2972
+ const last = words[show ? 2 : 1];
2973
+ const end = last.start + last.text.length;
2974
+ let tail = args.slice(end);
2975
+ let json = false;
2976
+ const flags = [];
2977
+ for (let index = show ? 3 : 2; index < words.length; index++) {
2978
+ const word = words[index];
2979
+ const option = unquote(word.text);
2980
+ if (option === "--") break;
2981
+ if (option === "--json") json = true;
2982
+ const name = option.split("=", 1)[0];
2983
+ if (show && name === "--input") return { message: "Update `workflow runs show` to `vitehub workflow runs get` and rename `id` to `runId` in its `--input` JSON or file." };
2984
+ if (show && name === "--id") {
2985
+ if (!word.text.startsWith("--id")) return { message: "Update `workflow runs show` to `vitehub workflow runs get` and pass `--run-id` instead of `--id`." };
2986
+ flags.push({
2987
+ start: word.start - end,
2988
+ end: word.start + 4 - end,
2989
+ value: "--run-id"
2990
+ });
2991
+ }
2992
+ if (name === option && [
2993
+ "--id",
2994
+ "--run-id",
2995
+ "--input",
2996
+ "--url",
2997
+ "--workflow",
2998
+ "--timeout"
2999
+ ].includes(option)) index++;
3000
+ }
3001
+ for (const flag of flags.reverse()) tail = `${tail.slice(0, flag.start)}${flag.value}${tail.slice(flag.end)}`;
3002
+ return `workflow runs get${show || json ? "" : " --json"}${tail}`;
3003
+ }
3004
+ for (const [pattern, now] of renames) if (pattern.test(args)) return args.replace(pattern, now);
3005
+ return args;
3006
+ }
3007
+ async function migrate$26({ cwd }) {
3008
+ const { calls, edits, followUps } = await rewriteCliCalls(cwd, rewrite$2);
3009
+ return {
3010
+ 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",
3011
+ edits,
3012
+ followUps,
3013
+ notes: [],
3014
+ nextSteps: []
3015
+ };
3016
+ }
3017
+ const cliGetList = {
3018
+ name: "cli-get-list",
3019
+ 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",
3020
+ usage: "[dir]",
3021
+ async detect({ cwd }) {
3022
+ const { edits, followUps } = await migrate$26({ cwd });
3023
+ const file = edits[0]?.path ?? followUps[0]?.file;
3024
+ return file ? { reason: `${file} calls a renamed vitehub read command` } : void 0;
3025
+ },
3026
+ run: migrate$26
3027
+ };
3028
+ //#endregion
2482
3029
  //#region src/cli-url-flag/index.ts
2483
3030
  function serverOptions({ words }) {
2484
3031
  const [group, action, ...args] = words;
@@ -2555,8 +3102,8 @@ function manual$1(command) {
2555
3102
  const calls = findCliCalls(command, true);
2556
3103
  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.";
2557
3104
  }
2558
- async function migrate$24({ cwd }) {
2559
- const { edits, followUps } = await rewriteCliCalls(cwd, rewrite$1, manual$1);
3105
+ async function migrate$25({ cwd }) {
3106
+ const { edits, followUps } = await rewriteCliCalls$1(cwd, rewrite$1, manual$1);
2560
3107
  return {
2561
3108
  summary: edits.length ? `moved vitehub calls from --server to --url in ${edits.length} file(s)` : "no vitehub calls migrated",
2562
3109
  edits,
@@ -2570,11 +3117,11 @@ const cliUrlFlag = {
2570
3117
  description: "Use --url, the app URL, in vitehub calls of scripts and CI instead of --server",
2571
3118
  usage: "[dir]",
2572
3119
  async detect({ cwd }) {
2573
- const { edits, followUps } = await migrate$24({ cwd });
3120
+ const { edits, followUps } = await migrate$25({ cwd });
2574
3121
  const file = edits[0]?.path ?? followUps[0]?.file;
2575
3122
  return file ? { reason: `${file} may pass --server to vitehub` } : void 0;
2576
3123
  },
2577
- run: migrate$24
3124
+ run: migrate$25
2578
3125
  };
2579
3126
  //#endregion
2580
3127
  //#region src/cli-yes-flag/index.ts
@@ -2620,8 +3167,8 @@ function manual(command) {
2620
3167
  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.";
2621
3168
  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.";
2622
3169
  }
2623
- async function migrate$23({ cwd }) {
2624
- const { calls, edits, followUps } = await rewriteCliCalls(cwd, rewrite, manual);
3170
+ async function migrate$24({ cwd }) {
3171
+ const { calls, edits, followUps } = await rewriteCliCalls$1(cwd, rewrite, manual);
2625
3172
  return {
2626
3173
  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",
2627
3174
  edits,
@@ -2635,16 +3182,16 @@ const cliYesFlag = {
2635
3182
  description: "Use --yes in vitehub calls of scripts and CI: database drop|reset --force, connections revoke --confirm, database generate --non-interactive",
2636
3183
  usage: "[dir]",
2637
3184
  async detect({ cwd }) {
2638
- const { edits, followUps } = await migrate$23({ cwd });
3185
+ const { edits, followUps } = await migrate$24({ cwd });
2639
3186
  const file = edits[0]?.path ?? followUps[0]?.file;
2640
3187
  return file ? { reason: `${file} may use a removed vitehub prompt flag` } : void 0;
2641
3188
  },
2642
- run: migrate$23
3189
+ run: migrate$24
2643
3190
  };
2644
3191
  //#endregion
2645
3192
  //#region src/cms-roles/index.ts
2646
3193
  const sourcePatterns$14 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}"];
2647
- const ignoredPatterns$13 = [
3194
+ const ignoredPatterns$14 = [
2648
3195
  "**/node_modules/**",
2649
3196
  "**/.nuxt/**",
2650
3197
  "**/.output/**",
@@ -2689,12 +3236,12 @@ function isCmsPreset(node, bindings, resolve) {
2689
3236
  if (value.type === "Identifier") return resolvesTo(value, bindings.presets, resolve);
2690
3237
  return value.type === "MemberExpression" && !value.computed && value.property.type === "Identifier" && (value.property.name === "cms" || value.property.name === "default") && resolvesTo(value.object, bindings.namespaces, resolve);
2691
3238
  }
2692
- async function migrate$22({ cwd }) {
3239
+ async function migrate$23({ cwd }) {
2693
3240
  const edits = [];
2694
3241
  const followUps = [];
2695
3242
  for (const file of (await glob(sourcePatterns$14, {
2696
3243
  cwd,
2697
- ignore: ignoredPatterns$13
3244
+ ignore: ignoredPatterns$14
2698
3245
  })).sort()) {
2699
3246
  const code = await readFile(join(cwd, file), "utf8");
2700
3247
  if (!code.includes("cms") || !/\baccess\b/.test(code)) continue;
@@ -2757,18 +3304,18 @@ const cmsRoles = {
2757
3304
  description: "Rename the cms preset option `access: \"roles\"` to `roles: true`",
2758
3305
  usage: "[dir]",
2759
3306
  async detect({ cwd }) {
2760
- const result = await migrate$22({ cwd });
3307
+ const result = await migrate$23({ cwd });
2761
3308
  const [edit] = result.edits;
2762
3309
  if (edit) return { reason: `${edit.path} sets the cms preset option \`access\`` };
2763
3310
  const [followUp] = result.followUps;
2764
3311
  return followUp ? { reason: `${followUp.file} sets the cms preset option \`access\`` } : void 0;
2765
3312
  },
2766
- run: migrate$22
3313
+ run: migrate$23
2767
3314
  };
2768
3315
  //#endregion
2769
3316
  //#region src/define-forms/shared.ts
2770
3317
  const sourcePatterns$13 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}"];
2771
- const ignoredPatterns$12 = [
3318
+ const ignoredPatterns$13 = [
2772
3319
  "**/node_modules/**",
2773
3320
  "**/.nuxt/**",
2774
3321
  "**/.output/**",
@@ -2782,7 +3329,7 @@ const ignoredPatterns$12 = [
2782
3329
  async function readSourceFiles(cwd) {
2783
3330
  const paths = (await glob(sourcePatterns$13, {
2784
3331
  cwd,
2785
- ignore: ignoredPatterns$12,
3332
+ ignore: ignoredPatterns$13,
2786
3333
  dot: false
2787
3334
  })).sort();
2788
3335
  return await Promise.all(paths.map(async (path) => ({
@@ -2954,7 +3501,7 @@ function rewriteContentImports(file, parsed, contentFiles, output, followUps) {
2954
3501
  const configFile$1 = /^config\.(?:c|m)?[jt]s$/;
2955
3502
  const indexFile = /^index\.(?:c|m)?[jt]s$/;
2956
3503
  const scriptFile = /\.(?:c|m)?[jt]sx?$/;
2957
- const declarationFile = /\.d\.(?:c|m)?ts$/;
3504
+ const declarationFile$1 = /\.d\.(?:c|m)?ts$/;
2958
3505
  /** Calls whose first argument names a module, such as `vi.mock("../databases/config")`. */
2959
3506
  const moduleCalls$3 = /* @__PURE__ */ new Set([
2960
3507
  "mock",
@@ -3019,7 +3566,7 @@ function planDatabaseMoves(paths, isDefinition) {
3019
3566
  continue;
3020
3567
  }
3021
3568
  for (const path of namedConfigs) plan.files.set(`${root}/${path}`, `${root}/${folderOf(path)}/${posix.basename(path).replace(/^config/, "index")}`);
3022
- const definitions = relativeFiles.filter((path) => scriptFile.test(path) && !declarationFile.test(path) && !path.startsWith("migrations/"));
3569
+ const definitions = relativeFiles.filter((path) => scriptFile.test(path) && !declarationFile$1.test(path) && !path.startsWith("migrations/"));
3023
3570
  const migrations = relativeFiles.filter((path) => path.startsWith("migrations/"));
3024
3571
  if (migrations.length && !definitions.length && !relativeFiles.some((path) => path.startsWith("default/"))) {
3025
3572
  for (const path of migrations) plan.files.set(`${root}/${path}`, `${root}/default/${path}`);
@@ -3041,7 +3588,7 @@ function strayDefinitions(paths, plan, isDefinition) {
3041
3588
  const followUps = [];
3042
3589
  for (const path of final) {
3043
3590
  const root = databasesRoot(path);
3044
- if (!root || !scriptFile.test(path) || declarationFile.test(path) || indexFile.test(posix.basename(path))) continue;
3591
+ if (!root || !scriptFile.test(path) || declarationFile$1.test(path) || indexFile.test(posix.basename(path))) continue;
3045
3592
  let inside = false;
3046
3593
  for (let folder = folderOf(path); folder.length > root.length; folder = folderOf(folder)) if (indexFolders.has(folder)) inside = true;
3047
3594
  if (inside) continue;
@@ -3496,7 +4043,7 @@ const configPatterns$1 = ["**/{package.json,wrangler.json,wrangler.jsonc,wrangle
3496
4043
  async function databaseFiles(cwd) {
3497
4044
  return (await glob(["**/server/databases/**"], {
3498
4045
  cwd,
3499
- ignore: ignoredPatterns$12,
4046
+ ignore: ignoredPatterns$13,
3500
4047
  dot: false
3501
4048
  })).sort();
3502
4049
  }
@@ -3555,7 +4102,7 @@ function rewriteCode(file, contentFiles, counts, followUps, migratedContentFiles
3555
4102
  }
3556
4103
  return output.toString();
3557
4104
  }
3558
- async function migrate$21({ cwd }) {
4105
+ async function migrate$22({ cwd }) {
3559
4106
  const sources = await readSourceFiles(cwd);
3560
4107
  const followUps = [];
3561
4108
  const notes = [];
@@ -3637,7 +4184,7 @@ async function migrate$21({ cwd }) {
3637
4184
  async function configFollowUps(cwd) {
3638
4185
  const files = (await glob(configPatterns$1, {
3639
4186
  cwd,
3640
- ignore: ignoredPatterns$12,
4187
+ ignore: ignoredPatterns$13,
3641
4188
  dot: false
3642
4189
  })).sort();
3643
4190
  const followUps = [];
@@ -3677,11 +4224,11 @@ const defineForms = {
3677
4224
  const reason = await detectFormerForm(cwd);
3678
4225
  return reason ? { reason } : void 0;
3679
4226
  },
3680
- run: migrate$21
4227
+ run: migrate$22
3681
4228
  };
3682
4229
  //#endregion
3683
4230
  //#region package.json
3684
- var version = "0.4.1";
4231
+ var version = "0.5.0";
3685
4232
  //#endregion
3686
4233
  //#region src/shared/config-editor.ts
3687
4234
  const vitehubModule = "vite-hub/nuxt";
@@ -4509,7 +5056,7 @@ async function assertContentDestinations(cwd, edits) {
4509
5056
  if (entry && (path === destination || !entry.isDirectory())) throw codemodError(`${destination}: ${path} is occupied. Move it before migrating.`);
4510
5057
  }
4511
5058
  }
4512
- async function migrate$20({ cwd }) {
5059
+ async function migrate$21({ cwd }) {
4513
5060
  const config = await readNuxtConfig(cwd);
4514
5061
  const entry = docusEntry(config);
4515
5062
  if (!entry) throw codemodError(`${config.fileName} does not extend the docus layer. Docus apps write extends: ['docus'].`);
@@ -4740,8 +5287,660 @@ const docus = {
4740
5287
  description: "Move a Docus site to @vite-hub/docs: the module, the site options, and the page frontmatter.",
4741
5288
  usage: "[dir]",
4742
5289
  detect: detect$2,
4743
- run: migrate$20
5290
+ run: migrate$21
5291
+ };
5292
+ //#endregion
5293
+ //#region src/shared/config-imports.ts
5294
+ const extensions = [
5295
+ ".ts",
5296
+ ".mts",
5297
+ ".cts",
5298
+ ".js",
5299
+ ".mjs",
5300
+ ".cjs"
5301
+ ];
5302
+ function resolveRelativeImport(cwd, importer, source) {
5303
+ const base = resolve(cwd, dirname(importer), source);
5304
+ const file = [
5305
+ base,
5306
+ base.replace(/\.(m|c)?js$/, (_, prefix) => `.${prefix ?? ""}ts`),
5307
+ ...extensions.map((extension) => `${base}${extension}`),
5308
+ ...extensions.map((extension) => join(base, `index${extension}`))
5309
+ ].find((candidate) => existsSync(candidate) && statSync(candidate).isFile());
5310
+ if (!file) return;
5311
+ const path = relative(cwd, file).replaceAll("\\", "/");
5312
+ return path.startsWith("..") || isAbsolute(path) || path.split("/").includes("node_modules") ? void 0 : path;
5313
+ }
5314
+ function readModule(cwd, file) {
5315
+ const program = parseProgram(readFileSync(join(cwd, file), "utf8"), {
5316
+ jsx: /\.[jt]sx$/.test(file),
5317
+ typescript: !/\.(?:c|m)?jsx?$/.test(file)
5318
+ });
5319
+ const binding = bindingResolver(program);
5320
+ const values = /* @__PURE__ */ new Map();
5321
+ const imports = /* @__PURE__ */ new Map();
5322
+ const exports = /* @__PURE__ */ new Map();
5323
+ walk(program, (node, ancestors) => {
5324
+ const parent = ancestors.at(-1);
5325
+ if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.init && parent?.type === "VariableDeclaration" && parent.kind === "const") values.set(node.id, node.init);
5326
+ if (node.type === "FunctionDeclaration" && node.id) values.set(node.id, node);
5327
+ });
5328
+ for (const statement of program.program.body) if (statement.type === "ImportDeclaration" && statement.importKind !== "type") for (const specifier of statement.specifiers) {
5329
+ const name = specifier.type === "ImportDefaultSpecifier" ? "default" : specifier.type === "ImportSpecifier" && specifier.importKind !== "type" ? keyName(specifier.imported) : void 0;
5330
+ if (name) imports.set(specifier.local, {
5331
+ source: statement.source.value,
5332
+ name
5333
+ });
5334
+ }
5335
+ else if (statement.type === "ExportDefaultDeclaration") exports.set("default", statement.declaration);
5336
+ else if (statement.type === "ExportNamedDeclaration" && !statement.source && statement.exportKind !== "type") {
5337
+ const { declaration } = statement;
5338
+ if (declaration?.type === "FunctionDeclaration" && declaration.id) exports.set(declaration.id.name, declaration);
5339
+ if (declaration?.type === "VariableDeclaration" && declaration.kind === "const") {
5340
+ for (const item of declaration.declarations) if (item.id.type === "Identifier" && item.init) exports.set(item.id.name, item.init);
5341
+ }
5342
+ for (const specifier of statement.specifiers) {
5343
+ if (specifier.type !== "ExportSpecifier") continue;
5344
+ const name = keyName(specifier.exported);
5345
+ if (name) exports.set(name, specifier.local);
5346
+ }
5347
+ }
5348
+ return {
5349
+ file,
5350
+ program,
5351
+ binding,
5352
+ values,
5353
+ imports,
5354
+ exports
5355
+ };
5356
+ }
5357
+ function propertyValue(object, name) {
5358
+ for (let index = object.properties.length - 1; index >= 0; index--) {
5359
+ const property = object.properties[index];
5360
+ if (property.type === "SpreadElement") return void 0;
5361
+ const key = keyName(property.key, property.computed);
5362
+ if (key === void 0) return void 0;
5363
+ if (key === name) return property.type === "ObjectProperty" ? property.value : void 0;
5364
+ }
5365
+ }
5366
+ function returnedValue(fn) {
5367
+ if (fn.type !== "ArrowFunctionExpression" && fn.type !== "FunctionExpression" && fn.type !== "FunctionDeclaration") return;
5368
+ if (fn.async || fn.generator) return;
5369
+ if (fn.body.type !== "BlockStatement") return fn.body;
5370
+ const last = fn.body.body.at(-1);
5371
+ if (last?.type === "ReturnStatement" && fn.body.body.slice(0, -1).every((statement) => statement.type === "VariableDeclaration" && statement.kind === "const")) return last.argument ?? void 0;
5372
+ }
5373
+ /** Trace only options consumed by the config, crossing at most one relative import. */
5374
+ function importedConfigOptions(cwd, configFiles, findRoot) {
5375
+ const modules = /* @__PURE__ */ new Map();
5376
+ const options = /* @__PURE__ */ new Map();
5377
+ const followUps = [];
5378
+ const load = (file) => {
5379
+ if (!modules.has(file)) try {
5380
+ modules.set(file, readModule(cwd, file));
5381
+ } catch {
5382
+ modules.set(file, void 0);
5383
+ }
5384
+ return modules.get(file);
5385
+ };
5386
+ for (const file of configFiles) {
5387
+ const config = load(file);
5388
+ const root = config && findRoot(config.program, file);
5389
+ if (!config || !root) continue;
5390
+ const active = /* @__PURE__ */ new Set();
5391
+ const trace = (module, input) => {
5392
+ const node = unwrapExpression(input);
5393
+ if (active.has(node)) return void 0;
5394
+ active.add(node);
5395
+ const result = readValue(module, node);
5396
+ active.delete(node);
5397
+ return result;
5398
+ };
5399
+ const readValue = (module, node) => {
5400
+ if (node.type === "Identifier") {
5401
+ const binding = module.binding(node);
5402
+ if (!binding) return;
5403
+ const local = module.values.get(binding);
5404
+ if (local) return trace(module, local);
5405
+ const imported = module === config ? module.imports.get(binding) : void 0;
5406
+ if (!imported || !/^\.\.?\//.test(imported.source)) return;
5407
+ const path = resolveRelativeImport(cwd, file, imported.source);
5408
+ const target = path && !configFiles.includes(path) ? load(path) : void 0;
5409
+ const exported = target?.exports.get(imported.name);
5410
+ if (target && exported) return trace(target, exported);
5411
+ return;
5412
+ }
5413
+ if (node.type === "MemberExpression") {
5414
+ const name = keyName(node.property, node.computed);
5415
+ if (name === void 0) return;
5416
+ const object = trace(module, node.object);
5417
+ const value = object?.node.type === "ObjectExpression" ? propertyValue(object.node, name) : void 0;
5418
+ if (object && value) return trace(object.module, value);
5419
+ return;
5420
+ }
5421
+ if (node.type === "CallExpression") {
5422
+ const callee = trace(module, node.callee);
5423
+ const returned = callee && returnedValue(callee.node);
5424
+ if (callee && returned) return trace(callee.module, returned);
5425
+ return;
5426
+ }
5427
+ return {
5428
+ module,
5429
+ node
5430
+ };
5431
+ };
5432
+ const follow = (input) => {
5433
+ const item = {
5434
+ file,
5435
+ line: line(input),
5436
+ message: "The codemod could not trace these vite-hub options to an object literal. Check and migrate them by hand."
5437
+ };
5438
+ if (!followUps.some((entry) => entry.file === item.file && entry.line === item.line)) followUps.push(item);
5439
+ };
5440
+ const collect = (module, input, origin = input) => {
5441
+ if (!input) return;
5442
+ const result = trace(module, input);
5443
+ if (result?.node.type === "ObjectExpression") {
5444
+ if (result.module === config) return;
5445
+ const positions = options.get(result.module.file) ?? /* @__PURE__ */ new Set();
5446
+ positions.add(start(result.node));
5447
+ options.set(result.module.file, positions);
5448
+ } else if (origin && result?.node.type !== "BooleanLiteral") follow(origin);
5449
+ };
5450
+ if (/^(?:.*\/)?vite\.config\./.test(file)) {
5451
+ const plugins = propertyValue(root, "plugins");
5452
+ const resolved = plugins && trace(config, plugins);
5453
+ if (!resolved || resolved.module !== config || resolved.node.type !== "ArrayExpression") continue;
5454
+ for (const entry of resolved.node.elements) {
5455
+ if (!entry) continue;
5456
+ const call = unwrapExpression(entry);
5457
+ if (call.type !== "CallExpression" || call.callee.type !== "Identifier") continue;
5458
+ const binding = config.binding(call.callee);
5459
+ const imported = binding && config.imports.get(binding);
5460
+ if (imported?.source === "vite-hub" && imported.name === "vitehub") collect(config, call.arguments[0]);
5461
+ }
5462
+ } else {
5463
+ const scopeOptions = (module, scope, origin) => {
5464
+ collect(module, propertyValue(scope, "vitehub"), origin);
5465
+ const modules = propertyValue(scope, "modules");
5466
+ const entries = modules && unwrapExpression(modules);
5467
+ if (entries?.type !== "ArrayExpression") return;
5468
+ for (const element of entries.elements) {
5469
+ if (!element) continue;
5470
+ const tuple = unwrapExpression(element);
5471
+ if (tuple.type !== "ArrayExpression" || !tuple.elements[0]) continue;
5472
+ const head = unwrapExpression(tuple.elements[0]);
5473
+ const binding = head.type === "Identifier" && module.binding(head);
5474
+ const imported = binding && module.imports.get(binding);
5475
+ if (head.type === "StringLiteral" && head.value === "vite-hub/nuxt" || imported && imported.source === "vite-hub/nuxt" && imported.name === "default") collect(module, tuple.elements[1] ?? void 0, origin);
5476
+ }
5477
+ };
5478
+ const override = (module, input, origin, named) => {
5479
+ const scope = trace(module, input);
5480
+ if (scope?.node.type !== "ObjectExpression") return follow(origin);
5481
+ if (!named) return scopeOptions(scope.module, scope.node, origin);
5482
+ for (const entry of scope.node.properties) {
5483
+ if (entry.type !== "ObjectProperty") continue;
5484
+ const value = trace(scope.module, entry.value);
5485
+ if (value?.node.type === "ObjectExpression") scopeOptions(value.module, value.node, origin);
5486
+ else follow(origin);
5487
+ }
5488
+ };
5489
+ scopeOptions(config, root);
5490
+ for (const entry of root.properties) {
5491
+ if (entry.type !== "ObjectProperty") continue;
5492
+ const name = keyName(entry.key, entry.computed);
5493
+ if (name?.startsWith("$") && propertyValue(root, name) === entry.value) override(config, entry.value, entry.value, name === "$env");
5494
+ }
5495
+ }
5496
+ }
5497
+ return {
5498
+ options,
5499
+ followUps
5500
+ };
5501
+ }
5502
+ function optionsAt(program, positions) {
5503
+ const options = [];
5504
+ walk(program, (node) => {
5505
+ if (node.type === "ObjectExpression" && positions.has(start(node))) options.push(node);
5506
+ });
5507
+ return options;
5508
+ }
5509
+ //#endregion
5510
+ //#region src/vitehub-options/transform.ts
5511
+ /** Top-level Vite keys that owner plugins read before `vitehub()` became the only config place. */
5512
+ const removedViteKeys = [
5513
+ "agent",
5514
+ "auth",
5515
+ "blob",
5516
+ "browser",
5517
+ "database",
5518
+ "kv",
5519
+ "queue",
5520
+ "rateLimit",
5521
+ "sandboxTask",
5522
+ "vitehub",
5523
+ "workflow",
5524
+ "workspace"
5525
+ ];
5526
+ /** The standalone plugin that takes the options of each key as its argument. */
5527
+ const ownerPlugins = {
5528
+ agent: {
5529
+ name: "hubAgent",
5530
+ package: "agent"
5531
+ },
5532
+ auth: {
5533
+ name: "hubAuth",
5534
+ package: "auth"
5535
+ },
5536
+ blob: {
5537
+ name: "hubBlob",
5538
+ package: "blob"
5539
+ },
5540
+ browser: {
5541
+ name: "hubBrowser",
5542
+ package: "browser"
5543
+ },
5544
+ database: {
5545
+ name: "hubDatabase",
5546
+ previousName: "hubDb",
5547
+ package: "database"
5548
+ },
5549
+ kv: {
5550
+ name: "hubKV",
5551
+ previousName: "hubKv",
5552
+ package: "kv"
5553
+ },
5554
+ queue: {
5555
+ name: "hubQueue",
5556
+ package: "queue"
5557
+ },
5558
+ rateLimit: {
5559
+ name: "hubRateLimit",
5560
+ package: "rate-limit"
5561
+ },
5562
+ sandboxTask: {
5563
+ name: "hubSandboxTask",
5564
+ package: "sandbox/task"
5565
+ },
5566
+ workflow: {
5567
+ name: "hubWorkflow",
5568
+ package: "workflow"
5569
+ },
5570
+ workspace: {
5571
+ name: "hubWorkspace",
5572
+ package: "workspace"
5573
+ }
4744
5574
  };
5575
+ const configFunctions = /* @__PURE__ */ new Set([
5576
+ "defineConfig",
5577
+ "defineNuxtConfig",
5578
+ "defineNitroConfig"
5579
+ ]);
5580
+ /** The object of `defineConfig({...})`, `defineConfig(() => ({...}))`, `defineNuxtConfig({...})`, or `export default {...}`. */
5581
+ function findConfigRoot(program, followUps, file) {
5582
+ const exported = program.program.body.find((statement) => statement.type === "ExportDefaultDeclaration");
5583
+ if (!exported) return void 0;
5584
+ let value = unwrapExpression(exported.declaration);
5585
+ if (value.type === "Identifier") {
5586
+ const name = value.name;
5587
+ for (const statement of program.program.body) {
5588
+ if (statement.type !== "VariableDeclaration") continue;
5589
+ for (const declarator of statement.declarations) if (declarator.id.type === "Identifier" && declarator.id.name === name && declarator.init) value = unwrapExpression(declarator.init);
5590
+ }
5591
+ }
5592
+ if (value.type === "CallExpression") {
5593
+ if (value.callee.type !== "Identifier" || !configFunctions.has(value.callee.name)) return void 0;
5594
+ const [argument] = value.arguments;
5595
+ if (!argument) return void 0;
5596
+ value = unwrapExpression(argument);
5597
+ }
5598
+ if (value.type === "ArrowFunctionExpression" || value.type === "FunctionExpression" || value.type === "FunctionDeclaration") {
5599
+ if (value.body.type !== "BlockStatement") value = unwrapExpression(value.body);
5600
+ else {
5601
+ const returns = [];
5602
+ walk(value.body, (node, ancestors) => {
5603
+ if (node.type === "ReturnStatement" && node.argument && !ancestors.some((ancestor) => ancestor.type === "ArrowFunctionExpression" || ancestor.type === "FunctionExpression" || ancestor.type === "FunctionDeclaration" || ancestor.type === "ObjectMethod" || ancestor.type === "ClassMethod" || ancestor.type === "ClassPrivateMethod")) returns.push(node.argument);
5604
+ });
5605
+ const returned = returns.length === 1 ? objectValue$1(returns[0]) : void 0;
5606
+ if (!returned) {
5607
+ followUps.push({
5608
+ file,
5609
+ line: line(value),
5610
+ message: "The config factory does not return one object literal. Move top-level feature and Env options into vitehub() or owner plugin arguments, and move observability.logs to the top-level logs key by hand."
5611
+ });
5612
+ return;
5613
+ }
5614
+ value = returned;
5615
+ }
5616
+ }
5617
+ return value.type === "ObjectExpression" ? value : void 0;
5618
+ }
5619
+ function property(object, name) {
5620
+ return findProperty(object, name);
5621
+ }
5622
+ function objectValue$1(node) {
5623
+ const value = node ? unwrapExpression(node) : void 0;
5624
+ return value?.type === "ObjectExpression" ? value : void 0;
5625
+ }
5626
+ function nuxtEnvironmentOverrides(root) {
5627
+ return root.properties.flatMap((item) => {
5628
+ if (item.type !== "ObjectProperty") return [];
5629
+ const name = keyName(item.key, item.computed);
5630
+ const scope = objectValue$1(item.value);
5631
+ if (!scope || !name?.startsWith("$")) return [];
5632
+ if (name !== "$env") return [scope];
5633
+ return scope.properties.flatMap((entry) => {
5634
+ const override = entry.type === "ObjectProperty" ? objectValue$1(entry.value) : void 0;
5635
+ return override ? [override] : [];
5636
+ });
5637
+ });
5638
+ }
5639
+ function logsMode(node) {
5640
+ const value = unwrapExpression(node);
5641
+ if (value.type === "BooleanLiteral") return value.value ? "capture" : "possibly-disabled";
5642
+ if (value.type === "ObjectExpression") {
5643
+ if (value.properties.some((item) => item.type === "SpreadElement" || keyName(item.key, item.computed) === void 0)) return;
5644
+ return value.properties.some((item) => item.type !== "SpreadElement" && keyName(item.key, item.computed) === "source") ? "source" : "capture";
5645
+ }
5646
+ if (value.type === "SequenceExpression") return logsMode(value.expressions.at(-1));
5647
+ if (value.type === "ConditionalExpression") {
5648
+ const left = logsMode(value.consequent);
5649
+ const right = logsMode(value.alternate);
5650
+ if (left === right) return left;
5651
+ if (left && right && left !== "source" && right !== "source") return "possibly-disabled";
5652
+ }
5653
+ }
5654
+ /** Value imports of the expected API, checked against each call's lexical binding. */
5655
+ function importedNames(program, sources, imported) {
5656
+ const names = /* @__PURE__ */ new Map();
5657
+ const imports = typeof imported === "string" ? [imported] : imported;
5658
+ for (const statement of program.program.body) {
5659
+ if (statement.type !== "ImportDeclaration" || statement.importKind === "type" || !sources.includes(statement.source.value)) continue;
5660
+ for (const specifier of statement.specifiers) if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && imports.some((name) => name === keyName(specifier.imported))) names.set(specifier.local.name, specifier.local);
5661
+ }
5662
+ return names;
5663
+ }
5664
+ function callsOf(scope, names, resolveBinding) {
5665
+ const calls = [];
5666
+ walk(scope, (node) => {
5667
+ if (node.type === "CallExpression" && node.callee.type === "Identifier" && names.has(node.callee.name) && names.get(node.callee.name) === resolveBinding(node.callee)) calls.push(node);
5668
+ });
5669
+ return calls;
5670
+ }
5671
+ /** Moves the lines of `text` after the first from the indentation `from` to `to`. */
5672
+ function reindent(text, from, to) {
5673
+ if (from === to) return text;
5674
+ return text.split("\n").map((value, index) => {
5675
+ if (index === 0 || !value.trim()) return value;
5676
+ if (value.startsWith(from)) return to + value.slice(from.length);
5677
+ return to.length > from.length ? to.slice(from.length) + value : value;
5678
+ }).join("\n");
5679
+ }
5680
+ /**
5681
+ * Moves the vite-hub options of a config file. `findRoots` selects other config objects, such as the inline configs of
5682
+ * a test file. Without it, the file's default export is the config.
5683
+ */
5684
+ /**
5685
+ * `findOptions` selects the options objects traced from a config that imports this file.
5686
+ */
5687
+ function migrateViteHubOptions(file, code, findOptions) {
5688
+ const followUps = [];
5689
+ const notes = [];
5690
+ const unchanged = {
5691
+ code,
5692
+ changed: false,
5693
+ followUps,
5694
+ notes
5695
+ };
5696
+ if (!findOptions && !/vite-hub|vitehub|hubEnv/.test(code)) return unchanged;
5697
+ let program;
5698
+ try {
5699
+ program = parseProgram(code, {
5700
+ jsx: /\.[jt]sx$/.test(file),
5701
+ typescript: !/\.(?:c|m)?jsx?$/.test(file)
5702
+ });
5703
+ } catch {
5704
+ return unchanged;
5705
+ }
5706
+ const importedOptions = findOptions?.(program);
5707
+ const root = importedOptions ? importedOptions[0] : findConfigRoot(program, followUps, file);
5708
+ if (!root) return unchanged;
5709
+ const nuxt = basename(file).startsWith("nuxt.config");
5710
+ const editor = new ConfigEditor({
5711
+ code,
5712
+ fileName: file,
5713
+ path: file,
5714
+ program,
5715
+ root
5716
+ });
5717
+ const resolveBinding = bindingResolver(program);
5718
+ const removed = /* @__PURE__ */ new Set();
5719
+ const additions = /* @__PURE__ */ new Map();
5720
+ const insertProperties = (object, entries) => {
5721
+ additions.set(object, [...additions.get(object) ?? [], ...entries]);
5722
+ };
5723
+ let changed = false;
5724
+ const text = (node) => code.slice(start(node), end(node));
5725
+ const follow = (node, message) => followUps.push({
5726
+ file,
5727
+ line: line(node),
5728
+ message
5729
+ });
5730
+ const remove = (node) => {
5731
+ editor.removeItem(node);
5732
+ removed.add(node);
5733
+ changed = true;
5734
+ };
5735
+ /** Renames the `from` key of a vite-hub options object to `to`, and keeps its value. */
5736
+ const renameKey = (options, from, to, conflict) => {
5737
+ const item = property(options, from);
5738
+ if (!item) return;
5739
+ if (property(options, to)) {
5740
+ follow(item, conflict);
5741
+ return;
5742
+ }
5743
+ if (item.shorthand || item.computed) editor.output.overwrite(start(item), end(item), `${to}: ${text(item.value)}`);
5744
+ else editor.output.overwrite(start(item.key), end(item.key), to);
5745
+ changed = true;
5746
+ };
5747
+ const optionObjects = importedOptions ?? [];
5748
+ const environmentOptions = [];
5749
+ const emptyCalls = [];
5750
+ if (!importedOptions && nuxt) {
5751
+ const key = objectValue$1(property(root, "vitehub")?.value);
5752
+ if (key) optionObjects.push(key);
5753
+ const entry = findViteHubEntry({
5754
+ code,
5755
+ fileName: file,
5756
+ path: file,
5757
+ program,
5758
+ root
5759
+ });
5760
+ const inline = entry?.type === "ArrayExpression" ? objectValue$1(entry.elements[1] ?? void 0) : void 0;
5761
+ if (inline) optionObjects.push(inline);
5762
+ for (const scope of nuxtEnvironmentOverrides(root)) {
5763
+ const options = objectValue$1(property(scope, "vitehub")?.value);
5764
+ if (options) environmentOptions.push(options);
5765
+ const entry = findViteHubEntry({
5766
+ code,
5767
+ fileName: file,
5768
+ path: file,
5769
+ program,
5770
+ root: scope
5771
+ });
5772
+ const inline = entry?.type === "ArrayExpression" ? objectValue$1(entry.elements[1] ?? void 0) : void 0;
5773
+ if (inline) environmentOptions.push(inline);
5774
+ }
5775
+ } else if (!importedOptions) {
5776
+ const names = importedNames(program, ["vite-hub"], "vitehub");
5777
+ const local = callsOf(root, names, resolveBinding);
5778
+ for (const call of local.length ? local : callsOf(program, names, resolveBinding)) {
5779
+ const [argument] = call.arguments;
5780
+ const options = objectValue$1(argument);
5781
+ if (options) optionObjects.push(options);
5782
+ else if (!argument) emptyCalls.push(call);
5783
+ }
5784
+ }
5785
+ for (const options of /* @__PURE__ */ new Set([...optionObjects, ...environmentOptions])) {
5786
+ renameKey(options, "preset", "host", "Both preset and host are set. Remove preset: host picks the deployment target.");
5787
+ const sandbox = property(options, "sandbox");
5788
+ const sandboxValue = sandbox ? unwrapExpression(sandbox.value) : void 0;
5789
+ if (sandbox && sandboxValue?.type === "BooleanLiteral") {
5790
+ if (!sandboxValue.value) remove(sandbox);
5791
+ else renameKey(options, "sandbox", "sandboxTask", "Both sandbox and sandboxTask are set. Remove sandbox.");
5792
+ } else if (sandbox) follow(sandbox, "sandbox is now sandboxTask. Move these options into sandboxTask by hand.");
5793
+ const devtools = property(options, "devtools");
5794
+ if (devtools) {
5795
+ remove(devtools);
5796
+ notes.push(`${file}: removed devtools. Use the ViteHub Console with console: true.`);
5797
+ }
5798
+ const cloudflare = property(options, "cloudflare");
5799
+ 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.");
5800
+ const contentImportBase = property(options, "contentImportBase");
5801
+ if (contentImportBase) {
5802
+ remove(contentImportBase);
5803
+ notes.push(`${file}: removed contentImportBase. ViteHub always imports Content from vite-hub/content.`);
5804
+ }
5805
+ const observability = property(options, "observability");
5806
+ const observabilityValue = observability ? unwrapExpression(observability.value) : void 0;
5807
+ const observabilityObject = objectValue$1(observability?.value);
5808
+ const logs = property(options, "logs");
5809
+ const nestedLogs = observabilityObject ? property(observabilityObject, "logs") : void 0;
5810
+ if (observability && observabilityObject && nestedLogs) {
5811
+ if (logs) {
5812
+ follow(nestedLogs, "Both logs and observability.logs are set. Merge observability.logs into logs by hand.");
5813
+ continue;
5814
+ }
5815
+ const mode = logsMode(nestedLogs.value);
5816
+ const onlyLogs = observabilityObject.properties.length === 1;
5817
+ const service = property(observabilityObject, "service");
5818
+ const serviceValue = service && unwrapExpression(service.value);
5819
+ const hasService = serviceValue?.type === "StringLiteral" && Boolean(serviceValue.value);
5820
+ if (!mode || observabilityObject.properties.some((item) => item.type === "SpreadElement") || mode === "source" && !onlyLogs && !hasService) {
5821
+ follow(nestedLogs, "Move observability.logs to logs by hand. Keep observability to preserve Evlog when capture is disabled; omit or disable observability for a read-only source that did not run Evlog.");
5822
+ continue;
5823
+ }
5824
+ const parenStart = nestedLogs.value.extra?.parenStart;
5825
+ const value = code.slice(typeof parenStart === "number" ? parenStart : start(nestedLogs.value), end(nestedLogs));
5826
+ const indent = indentAt(code, start(observability));
5827
+ const logsText = `logs: ${reindent(value, indentAt(code, start(nestedLogs)), indent)}`;
5828
+ const separator = text(options).includes("\n") ? `,\n${indent}` : ", ";
5829
+ if (onlyLogs) editor.output.overwrite(start(observability), end(observability), mode === "possibly-disabled" ? `observability: true${separator}${logsText}` : logsText);
5830
+ else {
5831
+ editor.output.appendLeft(end(observability), `${separator}${logsText}`);
5832
+ remove(nestedLogs);
5833
+ }
5834
+ changed = true;
5835
+ continue;
5836
+ }
5837
+ 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.");
5838
+ const logsObject = objectValue$1(logs?.value);
5839
+ const evlog = logsObject ? property(logsObject, "evlog") : void 0;
5840
+ if (!logs || !logsObject || !evlog) continue;
5841
+ if (observabilityObject && property(observabilityObject, "evlog")) {
5842
+ follow(logs, "Both logs.evlog and observability.evlog are set. Merge logs.evlog into observability.evlog by hand.");
5843
+ continue;
5844
+ }
5845
+ if (observability && !observabilityObject && !(observabilityValue?.type === "BooleanLiteral" && observabilityValue.value)) {
5846
+ follow(logs, "observability is not an object literal. Move logs.evlog into observability.evlog by hand.");
5847
+ continue;
5848
+ }
5849
+ if (!observability) insertProperties(options, [`observability: { ${text(evlog)} }`]);
5850
+ else if (observabilityObject) insertProperties(observabilityObject, [text(evlog)]);
5851
+ else if (observabilityValue) editor.output.overwrite(start(observabilityValue), end(observabilityValue), `{ ${text(evlog)} }`);
5852
+ if (logsObject.properties.length === 1) {
5853
+ editor.output.overwrite(start(logs.value), end(logs.value), "true");
5854
+ changed = true;
5855
+ } else remove(evlog);
5856
+ }
5857
+ const viteObject = importedOptions ? void 0 : nuxt ? objectValue$1(property(root, "vite")?.value) : root;
5858
+ const envProperty = viteObject ? property(viteObject, "env") : void 0;
5859
+ if (envProperty && viteObject) {
5860
+ const envValue = unwrapExpression(envProperty.value);
5861
+ const envText = text(envValue);
5862
+ const sourceIndent = indentAt(code, start(envProperty));
5863
+ const hubEnvNames = importedNames(program, ["@vite-hub/env/vite", "vite-hub/env/vite"], "hubEnv");
5864
+ const localHubEnvCalls = callsOf(root, hubEnvNames, resolveBinding);
5865
+ const hubEnvCalls = nuxt ? [] : localHubEnvCalls.length ? localHubEnvCalls : callsOf(program, hubEnvNames, resolveBinding);
5866
+ const viteHubTargets = optionObjects.length + emptyCalls.length;
5867
+ const moveInto = (target, nested) => {
5868
+ const targetEnv = nested ? property(target, "env") : void 0;
5869
+ if (nested && !targetEnv) {
5870
+ const indent = editor.propertyIndent(target);
5871
+ insertProperties(target, [`env: ${reindent(envText, sourceIndent, indent)}`]);
5872
+ return true;
5873
+ }
5874
+ const envOptions = nested ? objectValue$1(targetEnv.value) : target;
5875
+ if (!envOptions) {
5876
+ follow(envProperty, nested ? "The Env option of vitehub() is not an object literal. Move these declarations into vitehub({ env }) by hand." : "hubEnv() options are not an object literal. Move these declarations into hubEnv() by hand.");
5877
+ return false;
5878
+ }
5879
+ const indent = editor.propertyIndent(envOptions);
5880
+ if (envValue.type !== "ObjectExpression") {
5881
+ insertProperties(envOptions, [`...${reindent(envText, sourceIndent, indent)}`]);
5882
+ return true;
5883
+ }
5884
+ const conflict = envValue.properties.find((item) => item.type === "ObjectProperty" && property(envOptions, keyName(item.key, item.computed) ?? ""));
5885
+ if (conflict) {
5886
+ follow(envProperty, `env.${keyName(conflict.key) ?? ""} is set in two places. Merge the declarations into one object by hand.`);
5887
+ return false;
5888
+ }
5889
+ const propertyIndent = envValue.properties[0] ? indentAt(code, start(envValue.properties[0])) : sourceIndent;
5890
+ insertProperties(envOptions, envValue.properties.map((item) => reindent(text(item), propertyIndent, indent)));
5891
+ return true;
5892
+ };
5893
+ let moved = false;
5894
+ const targetEnv = optionObjects[0] ? property(optionObjects[0], "env") : void 0;
5895
+ const targetEnvValue = targetEnv ? unwrapExpression(targetEnv.value) : void 0;
5896
+ const envOff = targetEnvValue?.type === "BooleanLiteral" && !targetEnvValue.value;
5897
+ if (viteHubTargets > 1) follow(envProperty, "The config has more than one vite-hub options object. Move env into the right one by hand.");
5898
+ else if (optionObjects[0] && envOff && hubEnvCalls.length !== 1) follow(envProperty, "vitehub({ env: false }) turns Env off, but the config declares Env. Remove one of them.");
5899
+ else if (optionObjects[0] && !envOff) moved = moveInto(optionObjects[0], true);
5900
+ else if (emptyCalls[0]) {
5901
+ const callIndent = indentAt(code, start(emptyCalls[0]));
5902
+ const indent = `${callIndent}${editor.style.indent}`;
5903
+ editor.output.appendLeft(end(emptyCalls[0]) - 1, `{\n${indent}env: ${reindent(envText, sourceIndent, indent)},\n${callIndent}}`);
5904
+ moved = true;
5905
+ } else if (hubEnvCalls.length === 1) {
5906
+ const call = hubEnvCalls[0];
5907
+ const [argument] = call.arguments;
5908
+ const options = objectValue$1(argument);
5909
+ if (options) moved = moveInto(options, false);
5910
+ else if (!argument) {
5911
+ editor.output.appendLeft(end(call) - 1, reindent(envText, sourceIndent, indentAt(code, start(call))));
5912
+ moved = true;
5913
+ } else follow(envProperty, "hubEnv() options are not an object literal. Move these declarations into hubEnv() by hand.");
5914
+ } 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.");
5915
+ if (moved) {
5916
+ const viteProperty = nuxt ? property(root, "vite") : void 0;
5917
+ if (viteProperty && viteObject.properties.length === 1) remove(viteProperty);
5918
+ else remove(envProperty);
5919
+ }
5920
+ }
5921
+ if (viteObject) for (const key of removedViteKeys) {
5922
+ const item = property(viteObject, key);
5923
+ if (!item || removed.has(item)) continue;
5924
+ const value = unwrapExpression(item.value);
5925
+ const sourceIndent = indentAt(code, start(item));
5926
+ const plugin = ownerPlugins[key];
5927
+ 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) : [];
5928
+ if (key !== "vitehub" && optionObjects.length === 1 && !emptyCalls.length && !property(optionObjects[0], key)) {
5929
+ insertProperties(optionObjects[0], [`${key}: ${reindent(text(value), sourceIndent, editor.propertyIndent(optionObjects[0]))}`]);
5930
+ remove(item);
5931
+ } else if (!optionObjects.length && !emptyCalls.length && pluginCalls.length === 1 && !pluginCalls[0].arguments.length) {
5932
+ editor.output.appendLeft(end(pluginCalls[0]) - 1, reindent(text(value), sourceIndent, indentAt(code, start(pluginCalls[0]))));
5933
+ remove(item);
5934
+ } else follow(item, nuxt ? `vite.${key} is no longer read. Set ${key} in the vite-hub/nuxt options.` : `The top-level Vite ${key} key is no longer read. Move it into vitehub({ ${key} }), or pass it to the feature's plugin.`);
5935
+ }
5936
+ for (const [object, entries] of additions) editor.insertProperties(object, entries, removed);
5937
+ return changed ? {
5938
+ code: editor.output.toString(),
5939
+ changed,
5940
+ followUps,
5941
+ notes
5942
+ } : unchanged;
5943
+ }
4745
5944
  //#endregion
4746
5945
  //#region src/driver-key/index.ts
4747
5946
  /** The old key that picked the backend of a feature. The new key is always `driver`. */
@@ -4875,7 +6074,7 @@ const apiCalls = /* @__PURE__ */ new Map([
4875
6074
  ]);
4876
6075
  const configFile = /^(?:vite|nuxt|nitro)\.config\.[cm]?[jt]s$/;
4877
6076
  const sourcePatterns$12 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}"];
4878
- const ignoredPatterns$11 = [
6077
+ const ignoredPatterns$12 = [
4879
6078
  "**/node_modules/**",
4880
6079
  "**/.nuxt/**",
4881
6080
  "**/.output/**",
@@ -4951,14 +6150,27 @@ function renameKey(context, property) {
4951
6150
  else context.output.overwrite(start(property.key), end(property.key), property.computed ? quoteString("driver", context.style) : "driver");
4952
6151
  context.changed = true;
4953
6152
  }
6153
+ function unwrapSafeValue(node) {
6154
+ let value = node;
6155
+ while (value.type === "ParenthesizedExpression" || value.type === "TSNonNullExpression" || (value.type === "TSAsExpression" || value.type === "TSTypeAssertion") && value.typeAnnotation.type === "TSTypeReference" && value.typeAnnotation.typeName.type === "Identifier" && value.typeAnnotation.typeName.name === "const") value = value.expression;
6156
+ return value;
6157
+ }
4954
6158
  function renameValue(context, property, values, label) {
4955
- const value = property.value;
6159
+ const value = unwrapExpression(property.value);
4956
6160
  if (value.type === "StringLiteral") {
4957
6161
  const next = Object.hasOwn(values, value.value) ? values[value.value] : void 0;
4958
- if (!next) return;
6162
+ if (!next) return true;
6163
+ if (unwrapSafeValue(property.value) !== value) {
6164
+ context.followUps.push({
6165
+ file: context.file,
6166
+ line: line(property),
6167
+ message: `\`${label}\` has an explicit type constraint. Update "${value.value}" to "${next}" and update the constraint by hand.`
6168
+ });
6169
+ return false;
6170
+ }
4959
6171
  context.output.overwrite(start(value), end(value), quoteString(next, context.style));
4960
6172
  context.changed = true;
4961
- return;
6173
+ return true;
4962
6174
  }
4963
6175
  const renamed = Object.entries(values).map(([from, to]) => `"${from}" is now "${to}"`).join(", ");
4964
6176
  context.followUps.push({
@@ -4966,6 +6178,7 @@ function renameValue(context, property, values, label) {
4966
6178
  line: line(property),
4967
6179
  message: `\`${label}\` is not a string literal. Check its value: ${renamed}.`
4968
6180
  });
6181
+ return false;
4969
6182
  }
4970
6183
  /** Rewrites the options object of one feature: the old key becomes `driver`, and old driver values get the new name. */
4971
6184
  function rewriteFeature(context, feature, object) {
@@ -4997,15 +6210,17 @@ function rewriteFeature(context, feature, object) {
4997
6210
  function rewriteWorkspaceStore(context, object) {
4998
6211
  const properties = objectProperties(object);
4999
6212
  const provider = properties.find((entry) => propertyName(entry) === "provider");
5000
- if (!provider || provider.value.type !== "StringLiteral" || !workspaceStoreDrivers.has(provider.value.value)) return;
6213
+ const providerValue = provider && unwrapExpression(provider.value);
6214
+ if (!provider || providerValue?.type !== "StringLiteral" || !workspaceStoreDrivers.has(providerValue.value)) return;
5001
6215
  if (properties.some((entry) => propertyName(entry) === "driver")) return;
5002
- renameKey(context, provider);
5003
- renameValue(context, provider, renamedValues.store, "store.driver");
6216
+ if (renameValue(context, provider, renamedValues.store, "store.driver")) renameKey(context, provider);
5004
6217
  }
5005
6218
  function rewriteWorkspace(context, object) {
5006
6219
  for (const property of objectProperties(object)) if (propertyName(property) === "store" && property.value.type === "ObjectExpression") rewriteWorkspaceStore(context, property.value);
5007
6220
  }
5008
6221
  function rewriteConfig(context, object, resolveApi) {
6222
+ if (context.rewritten.has(object)) return;
6223
+ context.rewritten.add(object);
5009
6224
  for (const property of objectProperties(object)) {
5010
6225
  const name = propertyName(property);
5011
6226
  if (name === "modules" && property.value.type === "ArrayExpression") for (const entry of property.value.elements) {
@@ -5041,14 +6256,15 @@ function rewriteProgram(context, program) {
5041
6256
  } else rewriteFeature(context, api, options);
5042
6257
  });
5043
6258
  }
5044
- async function migrate$19({ cwd }, { reportParseErrors } = { reportParseErrors: true }) {
6259
+ async function migrate$20({ cwd }, { reportParseErrors } = { reportParseErrors: true }) {
5045
6260
  const files = (await glob(sourcePatterns$12, {
5046
6261
  cwd,
5047
- ignore: ignoredPatterns$11,
6262
+ ignore: ignoredPatterns$12,
5048
6263
  dot: false
5049
6264
  })).sort();
6265
+ const imported = importedConfigOptions(cwd, files.filter((file) => configFile.test(basename(file))), (program, file) => findConfigRoot(program, [], file));
5050
6266
  const edits = [];
5051
- const followUps = [];
6267
+ const followUps = imported.followUps;
5052
6268
  for (const file of files) {
5053
6269
  const source = await readFile(join(cwd, file), "utf8");
5054
6270
  if (!needles$1.some((needle) => source.includes(needle))) continue;
@@ -5070,9 +6286,15 @@ async function migrate$19({ cwd }, { reportParseErrors } = { reportParseErrors:
5070
6286
  file,
5071
6287
  followUps,
5072
6288
  output: new MagicString(source),
6289
+ rewritten: /* @__PURE__ */ new Set(),
5073
6290
  style: detectStyle(source, program)
5074
6291
  };
5075
6292
  rewriteProgram(context, program);
6293
+ const positions = imported.options.get(file);
6294
+ if (positions) {
6295
+ const resolveApi = resolveApis(program);
6296
+ for (const options of optionsAt(program, positions)) rewriteConfig(context, options, resolveApi);
6297
+ }
5076
6298
  if (context.changed) edits.push({
5077
6299
  path: file,
5078
6300
  before: source,
@@ -5083,7 +6305,7 @@ async function migrate$19({ cwd }, { reportParseErrors } = { reportParseErrors:
5083
6305
  summary: edits.length ? `renamed the backend keys and driver values of ${edits.length} file(s) to \`driver\`` : "found no backend key to rename",
5084
6306
  edits,
5085
6307
  followUps,
5086
- notes: edits.length ? ["Config that a variable or a helper function builds is not rewritten. Search for `provider` and `authority` next to `queue`, `workflow`, `rateLimit`, `realtime`, `sandboxTask`, and Workspace `store` options."] : [],
6308
+ notes: edits.length ? ["Config that a variable or a helper function builds is not rewritten, except a `vitehub: { ... }` object in a file that a config file imports. Search for `provider` and `authority` next to `queue`, `workflow`, `rateLimit`, `realtime`, `sandboxTask`, and Workspace `store` options."] : [],
5087
6309
  nextSteps: edits.length ? ["Run your typecheck. The option types reject the old keys and values."] : []
5088
6310
  };
5089
6311
  }
@@ -5093,18 +6315,18 @@ const driverKey = {
5093
6315
  usage: "[dir]",
5094
6316
  detectAfterEdits: true,
5095
6317
  async detect(context) {
5096
- const result = await migrate$19(context, { reportParseErrors: false });
6318
+ const result = await migrate$20(context, { reportParseErrors: false });
5097
6319
  const [edit] = result.edits;
5098
6320
  if (edit) return { reason: `${edit.path} uses a former backend key or driver name` };
5099
6321
  const [followUp] = result.followUps;
5100
6322
  if (followUp) return { reason: `${followUp.file} needs a driver key migration` };
5101
6323
  },
5102
- run: migrate$19
6324
+ run: migrate$20
5103
6325
  };
5104
6326
  //#endregion
5105
6327
  //#region src/kv-list-prefix/index.ts
5106
6328
  const sourcePatterns$11 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,vue}"];
5107
- const ignoredPatterns$10 = [
6329
+ const ignoredPatterns$11 = [
5108
6330
  "**/node_modules/**",
5109
6331
  "**/.nuxt/**",
5110
6332
  "**/.output/**",
@@ -5162,13 +6384,13 @@ function belowPrefix(block, argument) {
5162
6384
  const literal = block.code.slice(start(argument), end(argument));
5163
6385
  return needsSeparator ? `${literal.slice(0, -1)}:${literal.slice(-1)}` : literal;
5164
6386
  }
5165
- async function migrate$18({ cwd }) {
6387
+ async function migrate$19({ cwd }) {
5166
6388
  const edits = [];
5167
6389
  const followUps = [];
5168
6390
  const nuxt = Boolean(findNuxtConfigName(cwd));
5169
6391
  for (const file of (await glob(sourcePatterns$11, {
5170
6392
  cwd,
5171
- ignore: ignoredPatterns$10
6393
+ ignore: ignoredPatterns$11
5172
6394
  })).sort()) {
5173
6395
  const code = await readFile(join(cwd, file), "utf8");
5174
6396
  const autoImport = nuxt && file.startsWith("server/") && !file.endsWith(".vue");
@@ -5264,13 +6486,13 @@ const kvListPrefix = {
5264
6486
  usage: "[dir]",
5265
6487
  detectAfterEdits: true,
5266
6488
  async detect({ cwd }) {
5267
- const result = await migrate$18({ cwd });
6489
+ const result = await migrate$19({ cwd });
5268
6490
  const [edit] = result.edits;
5269
6491
  if (edit) return { reason: `${edit.path} calls kv.keys() or kv.clear(base)` };
5270
6492
  const [followUp] = result.followUps;
5271
6493
  return followUp ? { reason: `${followUp.file} calls kv.keys() or kv.clear(base)` } : void 0;
5272
6494
  },
5273
- run: migrate$18
6495
+ run: migrate$19
5274
6496
  };
5275
6497
  //#endregion
5276
6498
  //#region src/nuxt-better-auth/call-sites.ts
@@ -5385,7 +6607,7 @@ function clientFollowUpsFor(file, code) {
5385
6607
  //#endregion
5386
6608
  //#region src/nuxt-better-auth/definitions.ts
5387
6609
  const moduleConfigSource = "@nuxtjs/better-auth/config";
5388
- function parse$2(file, code) {
6610
+ function parse$3(file, code) {
5389
6611
  try {
5390
6612
  return parseProgram(code, { typescript: !/\.[cm]?js$/.test(file) });
5391
6613
  } catch {
@@ -5471,7 +6693,7 @@ function moveServerDefinition(input) {
5471
6693
  ...node ? { line: line(node) } : {},
5472
6694
  message
5473
6695
  });
5474
- const program = parse$2(file, code);
6696
+ const program = parse$3(file, code);
5475
6697
  if (!program) {
5476
6698
  follow(void 0, "The codemod could not parse this file. Move it to server/auth.ts with defineAuth() from vite-hub/auth by hand.");
5477
6699
  return {
@@ -5613,7 +6835,7 @@ function moveClientDefinition(file, code) {
5613
6835
  ...node ? { line: line(node) } : {},
5614
6836
  message
5615
6837
  });
5616
- const program = parse$2(file, code);
6838
+ const program = parse$3(file, code);
5617
6839
  if (!program) {
5618
6840
  follow(void 0, "The codemod could not parse this file. Move the client plugins to app/auth.client.ts with defineAuthClient() from vite-hub/auth/vue by hand.");
5619
6841
  return {
@@ -5800,7 +7022,7 @@ function editPage(file, source, rule, style, typescript) {
5800
7022
  }
5801
7023
  //#endregion
5802
7024
  //#region src/nuxt-better-auth/index.ts
5803
- const moduleName$5 = "@nuxtjs/better-auth";
7025
+ const moduleName$6 = "@nuxtjs/better-auth";
5804
7026
  /** The Better Auth range that ViteHub Auth supports. */
5805
7027
  const betterAuthRange = "^1.7.15";
5806
7028
  const scripts$2 = "{ts,mts,js,mjs}";
@@ -5832,7 +7054,7 @@ async function readLayers(cwd, root, strict = true) {
5832
7054
  const layers = [{
5833
7055
  dir: ".",
5834
7056
  config: root,
5835
- listsModule: Boolean(findModuleEntry(root, moduleName$5))
7057
+ listsModule: Boolean(findModuleEntry(root, moduleName$6))
5836
7058
  }];
5837
7059
  const seen = /* @__PURE__ */ new Set(["."]);
5838
7060
  const automatic = (await glob(["layers/*"], {
@@ -5847,7 +7069,7 @@ async function readLayers(cwd, root, strict = true) {
5847
7069
  layers.push({
5848
7070
  dir,
5849
7071
  config,
5850
- listsModule: Boolean(findModuleEntry(config, moduleName$5))
7072
+ listsModule: Boolean(findModuleEntry(config, moduleName$6))
5851
7073
  });
5852
7074
  } catch (error) {
5853
7075
  if (!isCodemodError(error)) throw error;
@@ -5880,7 +7102,7 @@ async function readLayers(cwd, root, strict = true) {
5880
7102
  /** The module options of one config: the `auth` key and the inline options of its `modules` entry. */
5881
7103
  function moduleOptions(layer) {
5882
7104
  const options = [];
5883
- const inline = findModuleEntry(layer.config, moduleName$5)?.inlineOptions;
7105
+ const inline = findModuleEntry(layer.config, moduleName$6)?.inlineOptions;
5884
7106
  const inlineObject = inline && staticOptionsObject(inline);
5885
7107
  if (inline && !inlineObject) throw codemodError(`${layer.dir}/${layer.config.fileName}: Use literal module options before migrating Auth.`);
5886
7108
  if (inlineObject) options.push({ object: inlineObject });
@@ -5900,7 +7122,7 @@ function readRouteRules(layer, plan) {
5900
7122
  const file = posix.join(layer.dir, config.fileName);
5901
7123
  const rules = [];
5902
7124
  const nitro = objectProperty(config.root, "nitro");
5903
- const unsupported = (message, node) => codemodError(`${file}:${line(node)}: ${message} Migrate this rule by hand before removing ${moduleName$5}.`);
7125
+ const unsupported = (message, node) => codemodError(`${file}:${line(node)}: ${message} Migrate this rule by hand before removing ${moduleName$6}.`);
5904
7126
  if (!staticOptionsObject(config.root)) throw codemodError(`${file}: Use explicit Nuxt config keys so the codemod can check the Auth policy.`);
5905
7127
  const nitroProperty = findProperty(config.root, "nitro");
5906
7128
  if (nitroProperty && !staticOptionsObject(nitroProperty.value)) throw unsupported("The Nitro options are not a static object.", nitroProperty);
@@ -5962,7 +7184,7 @@ function hasDatabase(config) {
5962
7184
  async function readText(cwd, file) {
5963
7185
  return readFile(join(cwd, file), "utf8");
5964
7186
  }
5965
- async function migrate$17({ cwd }) {
7187
+ async function migrate$18({ cwd }) {
5966
7188
  const rootConfig = await readNuxtConfig(cwd);
5967
7189
  const followUps = [];
5968
7190
  const edits = [];
@@ -6181,12 +7403,12 @@ async function migrate$17({ cwd }) {
6181
7403
  if (layer.dir === ".") {
6182
7404
  const added = addViteHubOptions(editor, config, {
6183
7405
  options: [],
6184
- rootEntries: useViteHubModule(editor, config, layer.listsModule ? moduleName$5 : void 0),
7406
+ rootEntries: useViteHubModule(editor, config, layer.listsModule ? moduleName$6 : void 0),
6185
7407
  removedRootProperties: removed
6186
7408
  });
6187
7409
  host = added.host;
6188
7410
  hostNote = added.hostNote;
6189
- } else if (layer.listsModule) removeModuleEntry(editor, config, moduleName$5);
7411
+ } else if (layer.listsModule) removeModuleEntry(editor, config, moduleName$6);
6190
7412
  editor.removeUnusedBindings();
6191
7413
  const output = editor.output.toString();
6192
7414
  const after = config.code.includes("\n\n\n") ? output : output.replace(/\n{3,}/g, "\n\n");
@@ -6217,7 +7439,7 @@ async function migrate$17({ cwd }) {
6217
7439
  });
6218
7440
  });
6219
7441
  const packageResult = await editPackageJson(cwd, version, {
6220
- remove: [moduleName$5],
7442
+ remove: [moduleName$6],
6221
7443
  add: ["vite-hub", "@vite-hub/auth"],
6222
7444
  within: { "better-auth": betterAuthRange }
6223
7445
  });
@@ -6230,7 +7452,7 @@ async function migrate$17({ cwd }) {
6230
7452
  followUps,
6231
7453
  notes,
6232
7454
  nextSteps: [
6233
- `Run \`${packageResult.installCommand}\` to install vite-hub and @vite-hub/auth and remove ${moduleName$5}.`,
7455
+ `Run \`${packageResult.installCommand}\` to install vite-hub and @vite-hub/auth and remove ${moduleName$6}.`,
6234
7456
  "Run `npx nuxi prepare`, then type-check the app.",
6235
7457
  "Sign up, sign in, and open a guarded page to check the migration."
6236
7458
  ]
@@ -6238,11 +7460,11 @@ async function migrate$17({ cwd }) {
6238
7460
  }
6239
7461
  /** Detects the module in the app config, a local layer config, or package.json. */
6240
7462
  async function detect$1({ cwd }) {
6241
- const found = await detectNuxtModule(cwd, moduleName$5);
7463
+ const found = await detectNuxtModule(cwd, moduleName$6);
6242
7464
  if (found) return found;
6243
7465
  try {
6244
7466
  const config = await readNuxtConfig(cwd);
6245
- for (const layer of await readLayers(cwd, config, false)) if (layer.listsModule) return { reason: `${posix.join(layer.dir, layer.config.fileName)} lists ${moduleName$5} in modules` };
7467
+ for (const layer of await readLayers(cwd, config, false)) if (layer.listsModule) return { reason: `${posix.join(layer.dir, layer.config.fileName)} lists ${moduleName$6} in modules` };
6246
7468
  } catch (error) {
6247
7469
  if (!isCodemodError(error)) throw error;
6248
7470
  }
@@ -6252,11 +7474,11 @@ const nuxtBetterAuth = {
6252
7474
  description: "Move a Nuxt app from @nuxtjs/better-auth to ViteHub Auth through vite-hub/nuxt.",
6253
7475
  usage: "[dir]",
6254
7476
  detect: detect$1,
6255
- run: migrate$17
7477
+ run: migrate$18
6256
7478
  };
6257
7479
  //#endregion
6258
7480
  //#region src/nuxt-content/index.ts
6259
- const moduleName$4 = "@nuxt/content";
7481
+ const moduleName$5 = "@nuxt/content";
6260
7482
  const ignored$5 = [
6261
7483
  "**/node_modules/**",
6262
7484
  "**/.nuxt/**",
@@ -6393,7 +7615,7 @@ function readCollections(file, code, program, style, followUps) {
6393
7615
  if (!result.length || failures.length) throw codemodError(`${result.length ? "Not all collections" : "No collection"} of ${file} could be moved:\n${failures.map((entry) => ` ${entry.file}:${entry.line} ${entry.message}`).join("\n")}`);
6394
7616
  return result;
6395
7617
  }
6396
- async function migrate$16({ cwd }) {
7618
+ async function migrate$17({ cwd }) {
6397
7619
  const config = await readNuxtConfig(cwd);
6398
7620
  const [file] = await glob(["content.config.{ts,mts,js,mjs}"], { cwd });
6399
7621
  if (!file) throw codemodError("The app has no content.config.ts. Nuxt Content 3 apps define their collections there. Write server/content.ts with defineContent() from vite-hub/content by hand.");
@@ -6416,7 +7638,7 @@ async function migrate$16({ cwd }) {
6416
7638
  const bindings = /* @__PURE__ */ new Set();
6417
7639
  for (const statement of program.program.body) {
6418
7640
  if (statement.type !== "ImportDeclaration") continue;
6419
- for (const specifier of statement.specifiers) if (statement.source.value !== moduleName$4) bindings.add(specifier.local.name);
7641
+ for (const specifier of statement.specifiers) if (statement.source.value !== moduleName$5) bindings.add(specifier.local.name);
6420
7642
  else if (specifier.type === "ImportSpecifier" && keyName(specifier.imported, false) === "z") {
6421
7643
  bindings.add(specifier.local.name);
6422
7644
  zNames.add(specifier.local.name);
@@ -6440,7 +7662,7 @@ async function migrate$16({ cwd }) {
6440
7662
  ...zImports ? [`import { ${zImports} } from ${quote("zod")}${semicolon}`] : []
6441
7663
  ];
6442
7664
  for (const statement of program.program.body) {
6443
- if (statement.type !== "ImportDeclaration" || statement.source.value === moduleName$4) continue;
7665
+ if (statement.type !== "ImportDeclaration" || statement.source.value === moduleName$5) continue;
6444
7666
  const text = code.slice(start(statement), end(statement));
6445
7667
  imports.push(statement.source.value.startsWith(".") ? text.replace(statement.source.value, posix.join("..", statement.source.value)) : text);
6446
7668
  }
@@ -6479,13 +7701,13 @@ async function migrate$16({ cwd }) {
6479
7701
  }
6480
7702
  const added = addViteHubOptions(editor, config, {
6481
7703
  options: [],
6482
- rootEntries: useViteHubModule(editor, config, findModuleEntry(config, moduleName$4) ? moduleName$4 : void 0),
7704
+ rootEntries: useViteHubModule(editor, config, findModuleEntry(config, moduleName$5) ? moduleName$5 : void 0),
6483
7705
  removedRootProperties: removed
6484
7706
  });
6485
7707
  editor.removeUnusedBindings();
6486
7708
  const configOutput = editor.output.toString();
6487
7709
  const configCode = config.code.includes("\n\n\n") ? configOutput : configOutput.replace(/\n{3,}/g, "\n\n");
6488
- assertModuleRemoved(config.fileName, configCode, moduleName$4);
7710
+ assertModuleRemoved(config.fileName, configCode, moduleName$5);
6489
7711
  edits.unshift({
6490
7712
  path: config.fileName,
6491
7713
  before: config.code,
@@ -6513,7 +7735,7 @@ async function migrate$16({ cwd }) {
6513
7735
  });
6514
7736
  });
6515
7737
  const packageResult = await editPackageJson(cwd, version, {
6516
- remove: [moduleName$4, "better-sqlite3"],
7738
+ remove: [moduleName$5, "better-sqlite3"],
6517
7739
  add: ["vite-hub", "@vite-hub/content"],
6518
7740
  within: zImports ? { zod: "^3.25.0 || ^4.0.0" } : void 0
6519
7741
  });
@@ -6523,7 +7745,7 @@ async function migrate$16({ cwd }) {
6523
7745
  edits,
6524
7746
  followUps,
6525
7747
  notes: ["Each collection became a read-only glob() Source with the same files and paths. Content serves them at /api/content and reads them with content.get(path) and content.list().", `The codemod does not rewrite queryCollection() calls or <ContentRenderer>: the read API differs. See ${guide$1}.`],
6526
- nextSteps: [`Run \`${packageResult.installCommand}\` to install vite-hub and @vite-hub/content and remove ${moduleName$4}.`, "Run `npx nuxi prepare`, then replace the reads that the report lists."]
7748
+ nextSteps: [`Run \`${packageResult.installCommand}\` to install vite-hub and @vite-hub/content and remove ${moduleName$5}.`, "Run `npx nuxi prepare`, then replace the reads that the report lists."]
6527
7749
  };
6528
7750
  }
6529
7751
  const nuxtContent = {
@@ -6533,9 +7755,9 @@ const nuxtContent = {
6533
7755
  async detect(context) {
6534
7756
  if (await docus.detect(context)) return void 0;
6535
7757
  if (!existsSync(join(context.cwd, "content.config.ts")) && !(await glob(["content.config.{mts,js,mjs}"], { cwd: context.cwd })).length) return void 0;
6536
- return detectNuxtModule(context.cwd, moduleName$4);
7758
+ return detectNuxtModule(context.cwd, moduleName$5);
6537
7759
  },
6538
- run: migrate$16
7760
+ run: migrate$17
6539
7761
  };
6540
7762
  //#endregion
6541
7763
  //#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
@@ -6682,7 +7904,7 @@ function normalizePathDefinitionName(rootDir, file) {
6682
7904
  }
6683
7905
  //#endregion
6684
7906
  //#region src/nuxt-cron/index.ts
6685
- const moduleName$3 = "nuxt-cron";
7907
+ const moduleName$4 = "nuxt-cron";
6686
7908
  /** nuxt-cron presets, from its runtime. `everySecond` has six fields, which Schedule cannot run. */
6687
7909
  const cronPresets = {
6688
7910
  everySecond: "* * * * * *",
@@ -6830,12 +8052,12 @@ function migrateJob(file, target, code, defaults, processDriver) {
6830
8052
  migrated: true
6831
8053
  };
6832
8054
  }
6833
- async function migrate$15({ cwd }) {
8055
+ async function migrate$16({ cwd }) {
6834
8056
  const config = await readNuxtConfig(cwd);
6835
8057
  if (!staticOptionsObject(config.root)) throw codemodError(`${config.fileName} has options that cannot be read completely. Use an object literal with explicit, unique property names, then run the codemod again.`);
6836
8058
  const optionsProperty = findProperty(config.root, "cron");
6837
8059
  const defaults = { jobsDir: "cron" };
6838
- const inlineEntry = findModuleEntry(config, moduleName$3)?.inlineOptions;
8060
+ const inlineEntry = findModuleEntry(config, moduleName$4)?.inlineOptions;
6839
8061
  for (const node of [optionsProperty?.value, inlineEntry]) {
6840
8062
  if (!node) continue;
6841
8063
  const object = staticOptionsObject(node);
@@ -6854,7 +8076,7 @@ async function migrate$15({ cwd }) {
6854
8076
  }
6855
8077
  const jobsDirectory = posix.join("server", defaults.jobsDir);
6856
8078
  const files = (await glob(["**/*.{ts,js,mjs}"], { cwd: join(cwd, jobsDirectory) })).sort();
6857
- if (!files.length) throw codemodError(`${jobsDirectory} has no cron jobs, so there is nothing to migrate. Remove ${moduleName$3} by hand.`);
8079
+ if (!files.length) throw codemodError(`${jobsDirectory} has no cron jobs, so there is nothing to migrate. Remove ${moduleName$4} by hand.`);
6858
8080
  const host = planHost(config).host;
6859
8081
  if (!host) throw codemodError(`${config.fileName} has no statically known ViteHub host. Set the effective vitehub.host or inline module host to a string literal, then run the codemod again.`);
6860
8082
  if (host === "deno") throw codemodError("The ViteHub \"deno\" host cannot provide Schedule through the Nuxt integration. Keep nuxt-cron or compose an explicit Deno scheduling integration by hand.");
@@ -6902,7 +8124,7 @@ async function migrate$15({ cwd }) {
6902
8124
  const kept = files.length - migrated;
6903
8125
  const editor = new ConfigEditor(config);
6904
8126
  const removedRootProperties = /* @__PURE__ */ new Set();
6905
- const rootEntries = useViteHubModule(editor, config, kept ? void 0 : moduleName$3);
8127
+ const rootEntries = useViteHubModule(editor, config, kept ? void 0 : moduleName$4);
6906
8128
  if (optionsProperty && !kept) {
6907
8129
  editor.removeItem(optionsProperty);
6908
8130
  removedRootProperties.add(optionsProperty);
@@ -6932,12 +8154,12 @@ async function migrate$15({ cwd }) {
6932
8154
  line: lineOf(["vitehub", "host"]),
6933
8155
  message: hostNote
6934
8156
  });
6935
- if (!findModuleEntry(config, moduleName$3) && !kept) configFollowUps.push({
8157
+ if (!findModuleEntry(config, moduleName$4) && !kept) configFollowUps.push({
6936
8158
  file: config.fileName,
6937
- message: `${config.fileName} adds ${moduleName$3} in a way the codemod cannot remove, such as a conditional spread. Remove it from modules by hand.`
8159
+ message: `${config.fileName} adds ${moduleName$4} in a way the codemod cannot remove, such as a conditional spread. Remove it from modules by hand.`
6938
8160
  });
6939
8161
  const packageResult = await editPackageJson(cwd, version, {
6940
- remove: kept ? [] : [moduleName$3],
8162
+ remove: kept ? [] : [moduleName$4],
6941
8163
  add: ["vite-hub"]
6942
8164
  });
6943
8165
  edits.unshift({
@@ -6947,21 +8169,21 @@ async function migrate$15({ cwd }) {
6947
8169
  });
6948
8170
  if (packageResult.edit) edits.push(packageResult.edit);
6949
8171
  const notes = [processDriver ? "On Node, the Process Runtime runs each Schedule in the server process, as nuxt-cron did. Run one server process or replica: the runtime does not lock across processes." : `On ${host}, the host runs each Schedule from its own cron, so jobs keep running on serverless hosts. Schedules run in UTC.`, addKv ? "The Process Runtime records Schedule Runs in KV, so the codemod set vitehub.kv to true. On Node that stores them under .vitehub/data/kv. Run a Schedule by hand with `vitehub schedule run <name>` while vite dev runs." : "Run a Schedule by hand with `vitehub schedule run <name>` while vite dev runs."];
6950
- if (kept) notes.push(`${moduleName$3} stays because ${kept} job${kept === 1 ? "" : "s"} could not be moved. Remove it after the follow-ups.`);
8172
+ if (kept) notes.push(`${moduleName$4} stays because ${kept} job${kept === 1 ? "" : "s"} could not be moved. Remove it after the follow-ups.`);
6951
8173
  return {
6952
8174
  summary: `moved ${migrated} cron job${migrated === 1 ? "" : "s"} from ${jobsDirectory} to server/schedules${added ? `, host "${added}"` : ""}.`,
6953
8175
  edits,
6954
8176
  followUps: [...configFollowUps, ...followUps],
6955
8177
  notes,
6956
- nextSteps: [`Run \`${packageResult.installCommand}\` to install vite-hub${kept ? "" : ` and remove ${moduleName$3}`}.`, "Run `npx nuxi prepare`, then type-check the app."]
8178
+ nextSteps: [`Run \`${packageResult.installCommand}\` to install vite-hub${kept ? "" : ` and remove ${moduleName$4}`}.`, "Run `npx nuxi prepare`, then type-check the app."]
6957
8179
  };
6958
8180
  }
6959
8181
  const nuxtCron = {
6960
- name: moduleName$3,
8182
+ name: moduleName$4,
6961
8183
  description: "Move nuxt-cron jobs to ViteHub Schedule Definitions through vite-hub/nuxt.",
6962
8184
  usage: "[dir]",
6963
- detect: ({ cwd }) => detectNuxtModule(cwd, moduleName$3, ["cron"]),
6964
- run: migrate$15
8185
+ detect: ({ cwd }) => detectNuxtModule(cwd, moduleName$4, ["cron"]),
8186
+ run: migrate$16
6965
8187
  };
6966
8188
  //#endregion
6967
8189
  //#region ../internal/dist/object.js
@@ -7577,7 +8799,7 @@ function templateConfigReads(state, template, resolver) {
7577
8799
  }
7578
8800
  }
7579
8801
  const sourcePatterns$10 = ["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,vue}"];
7580
- const ignoredPatterns$9 = [
8802
+ const ignoredPatterns$10 = [
7581
8803
  "**/node_modules/**",
7582
8804
  "**/.nuxt/**",
7583
8805
  "**/.output/**",
@@ -7594,7 +8816,7 @@ async function rewriteCallSites(input) {
7594
8816
  const resolver = new Resolver(input.fields, input.unmigrated);
7595
8817
  const files = (await glob(sourcePatterns$10, {
7596
8818
  cwd: input.cwd,
7597
- ignore: ignoredPatterns$9,
8819
+ ignore: ignoredPatterns$10,
7598
8820
  dot: false
7599
8821
  })).filter((file) => !input.excludedDirectories?.some((directory) => file.startsWith(`${directory}/`))).sort();
7600
8822
  const result = {
@@ -7659,7 +8881,7 @@ async function rewriteCallSites(input) {
7659
8881
  }
7660
8882
  //#endregion
7661
8883
  //#region src/nuxt-safe-runtime-config/nuxt-config.ts
7662
- const moduleName$2 = "nuxt-safe-runtime-config";
8884
+ const moduleName$3 = "nuxt-safe-runtime-config";
7663
8885
  function readStaticPaths(node) {
7664
8886
  if (!node) return {};
7665
8887
  const value = unwrapExpression(node);
@@ -7852,7 +9074,7 @@ function editNuxtConfig(input) {
7852
9074
  const editor = new ConfigEditor(config);
7853
9075
  const style = editor.style;
7854
9076
  const removedRootProperties = /* @__PURE__ */ new Set();
7855
- const rootEntries = useViteHubModule(editor, config, moduleName$2);
9077
+ const rootEntries = useViteHubModule(editor, config, moduleName$3);
7856
9078
  const safeOptions = findProperty(config.root, "safeRuntimeConfig");
7857
9079
  if (safeOptions) {
7858
9080
  editor.removeItem(safeOptions);
@@ -8640,7 +9862,7 @@ async function findOutOfScopeConfigs(cwd, rootConfig) {
8640
9862
  const text = await readFile(join(cwd, file), "utf8");
8641
9863
  if (text.includes("safeRuntimeConfig") || text.includes("nuxt-safe-runtime-config")) followUps.push({
8642
9864
  file,
8643
- message: isLayer ? `This layer config also uses ${moduleName$2}. Its source was migrated with the app, but migrate this config's module options by hand.` : `This config also uses ${moduleName$2}. The codemod migrates only the app nuxt.config. Migrate this file by hand, or run the codemod in its directory.`
9865
+ message: isLayer ? `This layer config also uses ${moduleName$3}. Its source was migrated with the app, but migrate this config's module options by hand.` : `This config also uses ${moduleName$3}. The codemod migrates only the app nuxt.config. Migrate this file by hand, or run the codemod in its directory.`
8644
9866
  });
8645
9867
  else if (directory !== "." && !isLayer) followUps.push({
8646
9868
  file,
@@ -8652,11 +9874,11 @@ async function findOutOfScopeConfigs(cwd, rootConfig) {
8652
9874
  followUps
8653
9875
  };
8654
9876
  }
8655
- async function migrate$14({ cwd }) {
9877
+ async function migrate$15({ cwd }) {
8656
9878
  const config = await readNuxtConfig(cwd);
8657
- const moduleEntry = findModuleEntry(config, moduleName$2);
9879
+ const moduleEntry = findModuleEntry(config, moduleName$3);
8658
9880
  const safeProperty = findProperty(config.root, "safeRuntimeConfig");
8659
- if (!moduleEntry && !safeProperty) throw codemodError(`${config.fileName} does not use ${moduleName$2}: it has no "${moduleName$2}" module and no safeRuntimeConfig key.`);
9881
+ if (!moduleEntry && !safeProperty) throw codemodError(`${config.fileName} does not use ${moduleName$3}: it has no "${moduleName$3}" module and no safeRuntimeConfig key.`);
8660
9882
  const options = await resolveOptions(config, mergeStatic(readStaticOptions(safeProperty?.value), readStaticOptions(moduleEntry?.inlineOptions)));
8661
9883
  const hasSchema = options.schemaPath !== void 0 || options.schema !== void 0;
8662
9884
  if (options.envSchema && hasSchema) throw codemodError("safeRuntimeConfig sets both envSchema and $schema. The module accepts only one. Remove one, then run the codemod again.");
@@ -8731,7 +9953,7 @@ async function migrate$14({ cwd }) {
8731
9953
  excludedDirectories: outOfScope.directories
8732
9954
  });
8733
9955
  const packageResult = await editPackageJson(cwd, version, {
8734
- remove: [moduleName$2],
9956
+ remove: [moduleName$3],
8735
9957
  add: env.kind === "env-schema" ? ["vite-hub", "@vite-hub/env"] : ["vite-hub"]
8736
9958
  });
8737
9959
  const envLine = (field) => edited.lineOf([
@@ -8820,18 +10042,18 @@ async function migrate$14({ cwd }) {
8820
10042
  ...outOfScope.followUps
8821
10043
  ],
8822
10044
  notes,
8823
- nextSteps: [`Run \`${packageResult.installCommand}\` to install ${env.kind === "env-schema" ? "vite-hub and @vite-hub/env" : "vite-hub"} and remove ${moduleName$2}.`, "Run `npx nuxi prepare` to generate the Env types, then type-check the app."]
10045
+ 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."]
8824
10046
  };
8825
10047
  }
8826
10048
  /** Remove a schema-free module only when no layer can supply options or composable calls. */
8827
10049
  async function removeUnusedModule(cwd, config, safeProperty) {
8828
10050
  const editor = new ConfigEditor(config);
8829
- removeModuleEntry(editor, config, moduleName$2);
10051
+ removeModuleEntry(editor, config, moduleName$3);
8830
10052
  const layers = await glob(["layers/*"], {
8831
10053
  cwd,
8832
10054
  onlyDirectories: true
8833
10055
  });
8834
- if (config.root.properties.some((property) => property.type === "SpreadElement" || keyName(property.key, property.computed) === "extends" && !(property.type === "ObjectProperty" && property.value.type === "ArrayExpression" && property.value.elements.length === 0)) || layers.length) throw codemodError(`${config.fileName} uses layers or a root spread. Schema-free removal cannot verify inherited schemas or useSafeRuntimeConfig() calls. Review the layer options and calls, then remove ${moduleName$2} by hand or declare the schema in the app config and run the codemod again.`);
10056
+ if (config.root.properties.some((property) => property.type === "SpreadElement" || keyName(property.key, property.computed) === "extends" && !(property.type === "ObjectProperty" && property.value.type === "ArrayExpression" && property.value.elements.length === 0)) || layers.length) throw codemodError(`${config.fileName} uses layers or a root spread. Schema-free removal cannot verify inherited schemas or useSafeRuntimeConfig() calls. Review the layer options and calls, then remove ${moduleName$3} by hand or declare the schema in the app config and run the codemod again.`);
8835
10057
  const sources = await glob(["**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,vue}"], {
8836
10058
  cwd,
8837
10059
  ignore: [
@@ -8848,7 +10070,7 @@ async function removeUnusedModule(cwd, config, safeProperty) {
8848
10070
  if (safeProperty) editor.removeItem(safeProperty);
8849
10071
  editor.removeUnusedBindings();
8850
10072
  const packageResult = await editPackageJson(cwd, version, {
8851
- remove: [moduleName$2],
10073
+ remove: [moduleName$3],
8852
10074
  add: []
8853
10075
  });
8854
10076
  const edits = [{
@@ -8858,18 +10080,618 @@ async function removeUnusedModule(cwd, config, safeProperty) {
8858
10080
  }];
8859
10081
  if (packageResult.edit) edits.push(packageResult.edit);
8860
10082
  return {
8861
- summary: `removed ${moduleName$2}: it had no envSchema and no $schema, so it validated nothing.`,
10083
+ summary: `removed ${moduleName$3}: it had no envSchema and no $schema, so it validated nothing.`,
8862
10084
  edits,
8863
10085
  followUps: [],
8864
10086
  notes: ["To validate environment variables with ViteHub Env, declare them under vitehub.env. See https://vitehub.dev/docs/env."],
8865
- nextSteps: [`Run \`${packageResult.installCommand}\` to remove ${moduleName$2}.`]
10087
+ nextSteps: [`Run \`${packageResult.installCommand}\` to remove ${moduleName$3}.`]
8866
10088
  };
8867
10089
  }
8868
10090
  const nuxtSafeRuntimeConfig = {
8869
- name: moduleName$2,
10091
+ name: moduleName$3,
8870
10092
  description: "Move a Nuxt app from nuxt-safe-runtime-config to ViteHub Env through vite-hub/nuxt.",
8871
10093
  usage: "[dir]",
8872
- detect: ({ cwd }) => detectNuxtModule(cwd, moduleName$2, ["safeRuntimeConfig"]),
10094
+ detect: ({ cwd }) => detectNuxtModule(cwd, moduleName$3, ["safeRuntimeConfig"]),
10095
+ run: migrate$15
10096
+ };
10097
+ //#endregion
10098
+ //#region src/shared/nuxt-server-layout.ts
10099
+ const unknownSetting = Symbol("unknown Nuxt setting");
10100
+ function setting(root, ...keys) {
10101
+ let value = root;
10102
+ for (const key of keys) {
10103
+ if (!value || value === unknownSetting) return value;
10104
+ if (value.type === "BooleanLiteral") return void 0;
10105
+ if (value.type !== "ObjectExpression") return unknownSetting;
10106
+ let next;
10107
+ for (const property of value.properties) if (property.type === "SpreadElement" || property.computed && keyName(property.key, true) === void 0) next = unknownSetting;
10108
+ else if (keyName(property.key, property.computed) === key) next = property.type === "ObjectProperty" ? unwrapExpression(property.value) : unknownSetting;
10109
+ value = next !== unknownSetting && next?.type === "NullLiteral" ? void 0 : next;
10110
+ }
10111
+ return value;
10112
+ }
10113
+ function configuredDirectory(cwd, layer, value, fallback) {
10114
+ if (value !== void 0 && (value === unknownSetting || value.type !== "StringLiteral")) return void 0;
10115
+ return relative(cwd, resolve(cwd, layer, value?.value ?? fallback)).replaceAll("\\", "/") || ".";
10116
+ }
10117
+ function localDirectory(cwd, layer, entry) {
10118
+ if (entry?.type === "ArrayExpression") entry = entry.elements[0];
10119
+ if (entry?.type !== "StringLiteral" || !entry.value.startsWith(".") && !isAbsolute(entry.value)) return void 0;
10120
+ const directory = resolve(cwd, layer, entry.value);
10121
+ if (!existsSync(directory)) return void 0;
10122
+ return relative(cwd, directory).replaceAll("\\", "/") || ".";
10123
+ }
10124
+ async function nuxtServerLayout(cwd, config) {
10125
+ const layers = /* @__PURE__ */ new Map();
10126
+ const unknownLayers = /* @__PURE__ */ new Set();
10127
+ async function visit(directory, layerConfig) {
10128
+ if (layers.has(directory)) return;
10129
+ if (!layerConfig && findNuxtConfigName(join(cwd, directory))) try {
10130
+ layerConfig = await readNuxtConfig(join(cwd, directory));
10131
+ } catch {
10132
+ unknownLayers.add(`${directory}/nuxt.config`);
10133
+ return;
10134
+ }
10135
+ const root = layerConfig?.root;
10136
+ const subroot = configuredDirectory(cwd, directory, setting(root, "rootDir"), ".");
10137
+ const serverDir = subroot === void 0 ? void 0 : configuredDirectory(cwd, subroot, setting(root, "serverDir"), "server");
10138
+ const server = serverDir === ".." || serverDir?.startsWith("../") ? void 0 : serverDir;
10139
+ const shared = subroot === void 0 ? void 0 : configuredDirectory(cwd, subroot, setting(root, "dir", "shared"), "shared");
10140
+ layers.set(directory, {
10141
+ directory,
10142
+ config: layerConfig,
10143
+ server,
10144
+ shared
10145
+ });
10146
+ const parents = setting(root, "extends");
10147
+ if (parents === void 0) return;
10148
+ const entries = parents !== unknownSetting && parents.type === "ArrayExpression" ? parents.elements : [parents];
10149
+ for (const entry of entries) {
10150
+ const parent = entry === unknownSetting ? void 0 : localDirectory(cwd, directory, entry);
10151
+ if (parent === void 0) unknownLayers.add(`${directory === "." ? "" : `${directory}/`}${layerConfig?.fileName ?? "nuxt.config"} extends`);
10152
+ else await visit(parent);
10153
+ }
10154
+ }
10155
+ await visit(".", config);
10156
+ for (const path of (await glob("layers/*", {
10157
+ cwd,
10158
+ onlyDirectories: true
10159
+ })).sort().reverse()) await visit(path.replace(/\/$/, ""));
10160
+ const ordered = [...layers.values()];
10161
+ const effective = (...keys) => {
10162
+ for (const layer of ordered) {
10163
+ const value = setting(layer.config?.root, ...keys);
10164
+ if (value !== void 0) return value;
10165
+ }
10166
+ };
10167
+ const nitro = effective("nitro", "imports");
10168
+ const auto = nitro !== unknownSetting && nitro?.type === "BooleanLiteral" && !nitro.value ? nitro : effective("nitro", "imports", "autoImport") ?? effective("imports", "autoImport");
10169
+ const injection = auto === void 0 ? true : auto !== unknownSetting && auto.type === "BooleanLiteral" ? auto.value : void 0;
10170
+ const experimental = effective("experimental", "nitroAutoImports");
10171
+ const legacy = effective("nitroLegacy");
10172
+ const legacyImports = legacy !== unknownSetting && legacy?.type === "ObjectExpression" ? effective("nitroLegacy", "imports") : legacy;
10173
+ const presets = experimental !== unknownSetting && experimental?.type === "BooleanLiteral" && experimental.value || legacyImports !== unknownSetting && legacyImports?.type === "BooleanLiteral" && legacyImports.value || legacy !== unknownSetting && legacy?.type === "ObjectExpression" && legacyImports === void 0;
10174
+ const computed = (value) => value !== void 0 && (value === unknownSetting || value.type !== "BooleanLiteral");
10175
+ const state = injection === false ? "off" : injection === void 0 || unknownLayers.size ? "unknown" : presets ? "on" : computed(experimental) || computed(legacyImports) ? "unknown" : "off";
10176
+ return {
10177
+ layers: ordered,
10178
+ unknownLayers,
10179
+ effective,
10180
+ injection: unknownLayers.size && injection !== false ? void 0 : injection,
10181
+ state
10182
+ };
10183
+ }
10184
+ //#endregion
10185
+ //#region ../internal/dist/nuxt-server-imports.js
10186
+ /**
10187
+ * The server helpers that `vite-hub/nuxt` auto-imports in Nitro code, per ViteHub feature, when the app turns on
10188
+ * Nuxt's server auto-imports. This table is the only list: the Nuxt module adds these auto-imports, and the
10189
+ * `nuxt-server-imports` codemod adds an explicit import for each one. `vite-hub` checks that each name is a value
10190
+ * export of its `vite-hub/*` entry.
10191
+ *
10192
+ * Rules for an entry:
10193
+ * - Runtime helpers that server code calls in a handler, such as `kv` or `sendQueue`.
10194
+ * - `define*` helpers only when Nitro alone loads their Definition files. ViteHub also loads Agent, Auth, Comments,
10195
+ * Database, Schedule, Workflow, and Workspace Definitions outside Nitro (Vite SSR, jiti, `runnerImport`, or
10196
+ * provider bundles). Those files and their dependencies keep explicit imports for every helper they use.
10197
+ * - No name that Nuxt, Nitro, or H3 auto-imports, such as `getSession`, `useSession`, `defineTask`, or `useStorage`.
10198
+ */
10199
+ const viteHubServerImports = {
10200
+ agent: { "vite-hub/agent": ["runAgent", "streamAgent"] },
10201
+ auth: { "vite-hub/auth/server": [
10202
+ "can",
10203
+ "requireAbility",
10204
+ "requireAuth",
10205
+ "requireAuthorization",
10206
+ "requireCaller",
10207
+ "useAuth",
10208
+ "withAnonymousAuthorization",
10209
+ "withAuth",
10210
+ "withAuthorization"
10211
+ ] },
10212
+ blob: { "vite-hub/blob": ["blob"] },
10213
+ browser: { "vite-hub/browser": ["defineBrowser", "runBrowser"] },
10214
+ cache: { "vite-hub/cache": ["invalidateTag"] },
10215
+ channels: { "vite-hub/channels": ["defineChannel", "useChannel"] },
10216
+ connections: {
10217
+ "vite-hub/connections": ["defineConnection"],
10218
+ "vite-hub/connections/server": ["useConnection"]
10219
+ },
10220
+ database: { "vite-hub/database": [
10221
+ "db",
10222
+ "schema",
10223
+ "useDatabase"
10224
+ ] },
10225
+ email: { "vite-hub/email": ["email"] },
10226
+ env: { "vite-hub/env": [
10227
+ "checkServiceToken",
10228
+ "requireServiceToken",
10229
+ "useServerEnv",
10230
+ "verifyWebhook"
10231
+ ] },
10232
+ i18n: { "vite-hub/i18n/server": ["getRequestI18n", "useTranslations"] },
10233
+ kv: { "vite-hub/kv": ["kv"] },
10234
+ queue: { "vite-hub/queue": [
10235
+ "defineQueue",
10236
+ "deferQueue",
10237
+ "useQueue",
10238
+ "sendQueue"
10239
+ ] },
10240
+ rateLimit: { "vite-hub/rate-limit": [
10241
+ "checkRateLimit",
10242
+ "peekRateLimit",
10243
+ "refundRateLimit",
10244
+ "requireRateLimit",
10245
+ "resetRateLimit"
10246
+ ] },
10247
+ realtime: {
10248
+ "vite-hub/realtime": ["defineRealtime"],
10249
+ "vite-hub/realtime/server": ["isRealtimeAvailable", "refreshRealtimeDocument"]
10250
+ },
10251
+ sandboxTask: { "vite-hub/sandbox/task": ["runSandboxTask"] },
10252
+ schedule: { "vite-hub/schedule": [
10253
+ "cancelSchedule",
10254
+ "getSchedule",
10255
+ "listSchedules",
10256
+ "startSchedule"
10257
+ ] },
10258
+ seo: { "vite-hub/seo": ["defineSitemap"] },
10259
+ source: { "vite-hub/source": ["useSource"] },
10260
+ workflow: { "vite-hub/workflow": [
10261
+ "cancelWorkflow",
10262
+ "deferWorkflow",
10263
+ "getWorkflowRun",
10264
+ "resumeWorkflow",
10265
+ "startWorkflow"
10266
+ ] },
10267
+ workspace: { "vite-hub/workspace": ["useWorkspace"] }
10268
+ };
10269
+ /** Each helper name of {@link viteHubServerImports}, mapped to the `vite-hub/*` entry that exports it. */
10270
+ const viteHubServerImportSources = new Map(serverImportTables().flatMap((sources) => Object.entries(sources).flatMap(([from, names]) => names.map((name) => [name, from]))));
10271
+ function serverImportTables() {
10272
+ return Object.values(viteHubServerImports);
10273
+ }
10274
+ //#endregion
10275
+ //#region src/shared/server-imports.ts
10276
+ const valueReadingTypeParents = /* @__PURE__ */ new Set([
10277
+ "TSAsExpression",
10278
+ "TSSatisfiesExpression",
10279
+ "TSNonNullExpression",
10280
+ "TSTypeAssertion",
10281
+ "TSTypeQuery",
10282
+ "TSExportAssignment",
10283
+ "TSInstantiationExpression"
10284
+ ]);
10285
+ /**
10286
+ * The names of `candidates` that the program reads without a binding in scope, each with the first node that reads it.
10287
+ * Type positions, such as a type named `schema`, do not count.
10288
+ */
10289
+ function freeReferences(program, candidates) {
10290
+ const resolve = bindingResolver(program);
10291
+ const found = /* @__PURE__ */ new Map();
10292
+ walk(program, (node, ancestors) => {
10293
+ if (node.type !== "Identifier" || !candidates.has(node.name) || found.has(node.name)) return;
10294
+ const parent = ancestors.at(-1);
10295
+ if (!parent || !isReference(node, parent)) return;
10296
+ if (parent.type === "ExportNamespaceSpecifier" || parent.type === "ExportDefaultSpecifier") return;
10297
+ if (parent.type.startsWith("TS") && !valueReadingTypeParents.has(parent.type)) return;
10298
+ if (parent.type === "ExportSpecifier" && ancestors.at(-2)?.type === "ExportNamedDeclaration" && ancestors.at(-2).source) return;
10299
+ if (resolve(node)) return;
10300
+ found.set(node.name, node);
10301
+ });
10302
+ return found;
10303
+ }
10304
+ /**
10305
+ * Adds an import from its `vite-hub/*` entry for each ViteHub server helper that the block reads without a binding.
10306
+ * It joins the names with a named value import of the same entry when the block has one, and else adds one import
10307
+ * line per entry after the last import. Returns the names that it imported and the skipped names that the block reads.
10308
+ */
10309
+ function addServerImports(input) {
10310
+ const { code, program, output, offset = 0, style, skip } = input;
10311
+ const free = freeReferences(program, new Set([...input.names ?? viteHubServerImportSources.keys()].filter((name) => viteHubServerImportSources.has(name))));
10312
+ const skipped = [...free.keys()].filter((name) => skip.has(name)).sort();
10313
+ const byEntry = /* @__PURE__ */ new Map();
10314
+ for (const name of [...free.keys()].sort()) {
10315
+ if (skip.has(name)) continue;
10316
+ const from = viteHubServerImportSources.get(name);
10317
+ byEntry.set(from, [...byEntry.get(from) ?? [], name]);
10318
+ }
10319
+ const added = [];
10320
+ const imports = program.program.body.filter((statement) => statement.type === "ImportDeclaration");
10321
+ const lines = [];
10322
+ for (const [from, names] of [...byEntry].sort(([left], [right]) => left.localeCompare(right))) {
10323
+ added.push(...names.map((name) => ({
10324
+ name,
10325
+ from
10326
+ })));
10327
+ const last = imports.find((statement) => statement.source.value === from && isNamedValueImport(statement))?.specifiers.at(-1);
10328
+ if (last) {
10329
+ output.appendLeft(offset + end(last), `, ${names.join(", ")}`);
10330
+ continue;
10331
+ }
10332
+ lines.push(`import { ${names.join(", ")} } from ${quoteString(from, style)}${style.semicolons ? ";" : ""}`);
10333
+ }
10334
+ if (lines.length) {
10335
+ const last = imports.at(-1);
10336
+ if (last) output.appendLeft(offset + end(last), lines.map((line) => `\n${line}`).join(""));
10337
+ else output.prependLeft(offset + offsetAfterShebang(code), `${lines.join("\n")}\n${program.program.body.length ? "\n" : ""}`);
10338
+ }
10339
+ return {
10340
+ added,
10341
+ skipped
10342
+ };
10343
+ }
10344
+ function isNamedValueImport(statement) {
10345
+ return statement.importKind !== "type" && statement.specifiers.some((specifier) => specifier.type === "ImportSpecifier") && !statement.specifiers.some((specifier) => specifier.type === "ImportNamespaceSpecifier");
10346
+ }
10347
+ function offsetAfterShebang(code) {
10348
+ return code.startsWith("#!") ? code.indexOf("\n") + 1 : 0;
10349
+ }
10350
+ const sourceFile = /\.[cm]?[jt]sx?$/;
10351
+ const declarationFile = /\.d\.[cm]?ts$/;
10352
+ async function appServerImports(cwd, layout) {
10353
+ const names = /* @__PURE__ */ new Map();
10354
+ const unknown = /* @__PURE__ */ new Set();
10355
+ if (layout.injection === false) return {
10356
+ names,
10357
+ unknown
10358
+ };
10359
+ for (const source of layout.unknownLayers) unknown.add(source);
10360
+ const add = (name, from) => {
10361
+ if (!names.has(name)) names.set(name, from);
10362
+ };
10363
+ const scan = async (directory) => {
10364
+ const pattern = /[*?[{]/.test(directory) ? directory : `${directory}/*`;
10365
+ for (const file of (await glob(pattern, {
10366
+ cwd,
10367
+ onlyFiles: true
10368
+ })).sort()) {
10369
+ if (!sourceFile.test(file) || declarationFile.test(file)) continue;
10370
+ const exports = await exportNames(cwd, file, unknown);
10371
+ for (const name of exports) add(name === "default" ? defaultExportName(file) : name, file);
10372
+ }
10373
+ };
10374
+ const scanSetting = layout.effective("imports", "scan");
10375
+ if (scanSetting === unknownSetting || scanSetting !== void 0 && scanSetting.type !== "BooleanLiteral") unknown.add("imports.scan");
10376
+ const legacy = layout.effective("nitroLegacy");
10377
+ const legacyImports = layout.effective("nitroLegacy", "imports");
10378
+ const nested = legacy !== unknownSetting && (legacy?.type === "BooleanLiteral" && legacy.value || legacy?.type === "ObjectExpression" && (legacyImports === void 0 || legacyImports !== unknownSetting && legacyImports.type === "BooleanLiteral" && legacyImports.value));
10379
+ if (scanSetting === void 0 || scanSetting !== unknownSetting && scanSetting.type === "BooleanLiteral" && scanSetting.value) for (const layer of layout.layers) {
10380
+ const layerScan = setting(layer.config?.root, "imports", "scan");
10381
+ if (layerScan !== void 0 && (layerScan === unknownSetting || layerScan.type !== "BooleanLiteral")) unknown.add(`${layer.config?.path ?? layer.directory} imports.scan`);
10382
+ if (layerScan !== unknownSetting && layerScan?.type === "BooleanLiteral" && !layerScan.value) continue;
10383
+ if (layer.server) {
10384
+ await scan(posix.join(layer.server, nested ? "utils/**/*" : "utils"));
10385
+ await scan(posix.join(layer.server, "types"));
10386
+ } else unknown.add(`${layer.config?.path ?? layer.directory} serverDir`);
10387
+ if (layer.shared) {
10388
+ await scan(posix.join(layer.shared, "utils"));
10389
+ await scan(posix.join(layer.shared, "types"));
10390
+ } else unknown.add(`${layer.config?.path ?? layer.directory} dir.shared`);
10391
+ }
10392
+ for (const layer of layout.layers) for (const key of [
10393
+ "dirs",
10394
+ "imports",
10395
+ "presets"
10396
+ ]) {
10397
+ const list = setting(layer.config?.root, "nitro", "imports", key);
10398
+ if (list === void 0) continue;
10399
+ const from = `${posix.join(layer.directory, layer.config?.fileName ?? "nuxt.config")} nitro.imports.${key}`;
10400
+ if (list === unknownSetting || list.type !== "ArrayExpression") {
10401
+ unknown.add(from);
10402
+ continue;
10403
+ }
10404
+ for (const element of list.elements) {
10405
+ if (!element) continue;
10406
+ const entry = unwrapExpression(element);
10407
+ if (key === "dirs" && entry.type === "StringLiteral" && !/^[@~#]/.test(entry.value)) await scan(relative(cwd, resolve(cwd, entry.value)).replaceAll("\\", "/") || ".");
10408
+ else if (key === "imports" && entry.type === "ObjectExpression") {
10409
+ const name = setting(entry, "as") ?? setting(entry, "name");
10410
+ if (name !== unknownSetting && name?.type === "StringLiteral") {
10411
+ const type = setting(entry, "type");
10412
+ if (type === void 0 || type !== unknownSetting && type.type === "BooleanLiteral" && !type.value) add(name.value, from);
10413
+ else if (type === unknownSetting || type.type !== "BooleanLiteral") unknown.add(from);
10414
+ } else unknown.add(from);
10415
+ } else if (key === "presets" && entry.type === "ObjectExpression") {
10416
+ const imports = setting(entry, "imports");
10417
+ if (imports === unknownSetting || imports?.type !== "ArrayExpression") unknown.add(from);
10418
+ else for (const item of imports.elements) {
10419
+ const value = item && unwrapExpression(item);
10420
+ if (value?.type === "StringLiteral") add(value.value, from);
10421
+ else if (value?.type === "ArrayExpression" && value.elements[0]?.type === "StringLiteral" && value.elements[1]?.type === "StringLiteral") add(value.elements[1].value, from);
10422
+ else if (value?.type === "ObjectExpression") {
10423
+ const name = setting(value, "as") ?? setting(value, "name");
10424
+ const type = setting(value, "type");
10425
+ if (name === unknownSetting || name?.type !== "StringLiteral" || type === unknownSetting || type !== void 0 && type.type !== "BooleanLiteral") unknown.add(from);
10426
+ else if (!type?.value) add(name.value, from);
10427
+ } else unknown.add(from);
10428
+ }
10429
+ } else unknown.add(from);
10430
+ }
10431
+ }
10432
+ return {
10433
+ names,
10434
+ unknown
10435
+ };
10436
+ }
10437
+ function serverLayoutFollowUps(layout) {
10438
+ return layout.layers.filter((layer) => !layer.server).map((layer) => ({
10439
+ file: posix.join(layer.directory, layer.config?.fileName ?? "nuxt.config"),
10440
+ message: "The server directory could not be resolved statically. Check this layer for server files that need explicit ViteHub imports."
10441
+ }));
10442
+ }
10443
+ function unknownServerImports(sources, names) {
10444
+ return `The codemod could not determine whether the app provides ${[...names].sort().join(", ")} as server auto-imports (${[...sources].sort().join(", ")}). Check those bindings before changing the code.`;
10445
+ }
10446
+ function patternExports(node) {
10447
+ if (node?.type === "Identifier") return [node.name];
10448
+ if (node?.type === "ArrayPattern") return node.elements.flatMap(patternExports);
10449
+ if (node?.type === "ObjectPattern") return node.properties.flatMap((property) => patternExports(property.type === "RestElement" ? property.argument : property.value));
10450
+ if (node?.type === "RestElement") return patternExports(node.argument);
10451
+ if (node?.type === "AssignmentPattern") return patternExports(node.left);
10452
+ return [];
10453
+ }
10454
+ async function exportNames(cwd, file, unknown, seen = /* @__PURE__ */ new Set()) {
10455
+ const names = /* @__PURE__ */ new Set();
10456
+ if (seen.has(file)) return names;
10457
+ seen.add(file);
10458
+ let program;
10459
+ try {
10460
+ program = parseProgram(await readFile(join(cwd, file), "utf8"), {
10461
+ jsx: file.endsWith("x"),
10462
+ typescript: /\.[cm]?tsx?$/.test(file)
10463
+ });
10464
+ } catch {
10465
+ unknown.add(file);
10466
+ return names;
10467
+ }
10468
+ for (const statement of program.program.body) {
10469
+ if (statement.type === "ExportDefaultDeclaration" && !["TSInterfaceDeclaration", "TSDeclareFunction"].includes(statement.declaration.type)) names.add("default");
10470
+ if (statement.type === "ExportAllDeclaration" && statement.exportKind !== "type") {
10471
+ const specifier = statement.source.value;
10472
+ const base = posix.join(posix.dirname(file), specifier);
10473
+ const target = specifier.startsWith(".") ? await resolveBarrel(cwd, base) : void 0;
10474
+ if (!target) unknown.add(`${file} (export * from ${JSON.stringify(specifier)})`);
10475
+ else for (const name of await exportNames(cwd, target, unknown, seen)) if (name !== "default") names.add(name);
10476
+ }
10477
+ if (statement.type !== "ExportNamedDeclaration" || statement.exportKind === "type") continue;
10478
+ const declaration = statement.declaration;
10479
+ if (declaration && !("declare" in declaration && declaration.declare)) {
10480
+ if (declaration.type === "FunctionDeclaration" || declaration.type === "ClassDeclaration" || declaration.type === "TSEnumDeclaration" || declaration.type === "TSModuleDeclaration") {
10481
+ if (declaration.id?.type === "Identifier") names.add(declaration.id.name);
10482
+ } else if (declaration.type === "VariableDeclaration") for (const declarator of declaration.declarations) for (const name of patternExports(declarator.id)) names.add(name);
10483
+ }
10484
+ for (const specifier of statement.specifiers) {
10485
+ if (specifier.type === "ExportSpecifier" && specifier.exportKind === "type") continue;
10486
+ const name = keyName(specifier.exported);
10487
+ if (name) names.add(name);
10488
+ }
10489
+ }
10490
+ return names;
10491
+ }
10492
+ async function resolveBarrel(cwd, base) {
10493
+ const source = base.replace(/\.[cm]?js$/, "");
10494
+ const extensions = [
10495
+ ".ts",
10496
+ ".mts",
10497
+ ".cts",
10498
+ ".js",
10499
+ ".mjs",
10500
+ ".cjs",
10501
+ ".tsx",
10502
+ ".jsx"
10503
+ ];
10504
+ const paths = [
10505
+ base,
10506
+ ...extensions.map((extension) => `${source}${extension}`),
10507
+ ...extensions.map((extension) => `${base}/index${extension}`)
10508
+ ];
10509
+ const files = new Set(await glob(paths, {
10510
+ cwd,
10511
+ onlyFiles: true
10512
+ }));
10513
+ return paths.find((file) => files.has(file) && sourceFile.test(file) && !declarationFile.test(file));
10514
+ }
10515
+ function defaultExportName(file) {
10516
+ const name = basename(file, extname(file));
10517
+ return (name === "index" ? basename(dirname(file)) : name).replace(/[-_.\s]+(\w)/g, (_, letter) => letter.toUpperCase());
10518
+ }
10519
+ //#endregion
10520
+ //#region src/nuxt-server-imports/index.ts
10521
+ const moduleName$2 = "vite-hub/nuxt";
10522
+ const ignoredPatterns$9 = [
10523
+ "**/node_modules/**",
10524
+ "**/*.d.ts",
10525
+ "**/*.d.mts",
10526
+ "**/*.d.cts"
10527
+ ];
10528
+ const helperPattern = new RegExp(`\\b(?:${[...viteHubServerImportSources.keys()].join("|")})\\b`);
10529
+ const helperNames = new Set(viteHubServerImportSources.keys());
10530
+ const reportedNitroHelpers = /* @__PURE__ */ new Set([
10531
+ "createError",
10532
+ "defineEventHandler",
10533
+ "eventHandler",
10534
+ "getQuery",
10535
+ "getRouterParam",
10536
+ "readBody",
10537
+ "useRuntimeConfig"
10538
+ ]);
10539
+ function listsViteHub(config) {
10540
+ if (findModuleEntry(config, moduleName$2)) return true;
10541
+ const locals = /* @__PURE__ */ new Set();
10542
+ for (const statement of config.program.program.body) {
10543
+ if (statement.type !== "ImportDeclaration" || statement.source.value !== moduleName$2) continue;
10544
+ for (const specifier of statement.specifiers) if (specifier.type === "ImportDefaultSpecifier") locals.add(specifier.local.name);
10545
+ }
10546
+ const modules = findProperty(config.root, "modules");
10547
+ const list = modules ? unwrapExpression(modules.value) : void 0;
10548
+ if (list?.type !== "ArrayExpression") return false;
10549
+ return list.elements.some((element) => {
10550
+ const entry = element ? unwrapExpression(element) : void 0;
10551
+ const head = entry?.type === "ArrayExpression" && entry.elements[0] ? unwrapExpression(entry.elements[0]) : entry;
10552
+ return head?.type === "Identifier" && locals.has(head.name);
10553
+ });
10554
+ }
10555
+ async function readProject(cwd) {
10556
+ let config;
10557
+ try {
10558
+ config = await readNuxtConfig(cwd);
10559
+ } catch (error) {
10560
+ if (isCodemodError(error)) return void 0;
10561
+ throw error;
10562
+ }
10563
+ if (!listsViteHub(config) && !(await readDependencies(cwd)).has("vite-hub")) return void 0;
10564
+ const layout = await nuxtServerLayout(cwd, config);
10565
+ const dirs = new Set(layout.layers.flatMap((layer) => layer.server ?? []));
10566
+ const files = await glob([...dirs].map((dir) => `${dir}/**/*.{ts,mts,cts,js,mjs,cjs,tsx,jsx}`), {
10567
+ cwd,
10568
+ ignore: ignoredPatterns$9
10569
+ });
10570
+ return {
10571
+ config,
10572
+ layout,
10573
+ serverFiles: files.sort()
10574
+ };
10575
+ }
10576
+ function parse$2(file, code) {
10577
+ return parseProgram(code, {
10578
+ jsx: file.endsWith("x"),
10579
+ typescript: /\.[cm]?tsx?$/.test(file)
10580
+ });
10581
+ }
10582
+ async function migrate$14({ cwd }) {
10583
+ const project = await readProject(cwd);
10584
+ const empty = {
10585
+ edits: [],
10586
+ followUps: [],
10587
+ notes: [],
10588
+ nextSteps: []
10589
+ };
10590
+ if (!project) return {
10591
+ summary: `found no Nuxt app with ${moduleName$2}`,
10592
+ ...empty
10593
+ };
10594
+ if (project.layout.state === "on") return {
10595
+ summary: `found Nuxt server auto-imports on in ${project.config.fileName}, so server files keep the ViteHub auto-imports`,
10596
+ ...empty
10597
+ };
10598
+ if (project.layout.state === "unknown") {
10599
+ const message = "The effective Nuxt server auto-import settings could not be determined statically. Check which server files need explicit ViteHub imports.";
10600
+ return {
10601
+ ...empty,
10602
+ summary: message,
10603
+ followUps: [{
10604
+ file: project.config.fileName,
10605
+ message
10606
+ }]
10607
+ };
10608
+ }
10609
+ const { names: appNames, unknown } = await appServerImports(cwd, project.layout);
10610
+ const skip = new Set(appNames.keys());
10611
+ const edits = [];
10612
+ const followUps = serverLayoutFollowUps(project.layout);
10613
+ const kept = /* @__PURE__ */ new Map();
10614
+ const nitroFiles = [];
10615
+ let added = 0;
10616
+ for (const file of project.serverFiles) {
10617
+ const source = await readFile(join(cwd, file), "utf8");
10618
+ const helpers = helperPattern.test(source);
10619
+ if (!helpers && ![...reportedNitroHelpers].some((name) => source.includes(name))) continue;
10620
+ let program;
10621
+ try {
10622
+ program = parse$2(file, source);
10623
+ } catch (error) {
10624
+ if (helpers) followUps.push({
10625
+ file,
10626
+ message: `The codemod could not parse this file (${error instanceof Error ? error.message : String(error)}). Import the ViteHub helpers that it uses from their vite-hub/* paths by hand.`
10627
+ });
10628
+ continue;
10629
+ }
10630
+ if (freeReferences(program, reportedNitroHelpers).size) nitroFiles.push(file);
10631
+ if (!helpers) continue;
10632
+ if (unknown.size) {
10633
+ const uncertain = [...freeReferences(program, helperNames).keys()].filter((name) => !skip.has(name));
10634
+ if (uncertain.length) followUps.push({
10635
+ file,
10636
+ message: unknownServerImports(unknown, uncertain)
10637
+ });
10638
+ }
10639
+ const output = new MagicString(source);
10640
+ const result = addServerImports({
10641
+ code: source,
10642
+ program,
10643
+ output,
10644
+ style: detectStyle(source, program),
10645
+ skip: unknown.size ? helperNames : skip
10646
+ });
10647
+ for (const name of result.skipped) if (skip.has(name)) kept.set(name, (kept.get(name) ?? /* @__PURE__ */ new Set()).add(file));
10648
+ if (!result.added.length) continue;
10649
+ added += result.added.length;
10650
+ edits.push({
10651
+ path: file,
10652
+ before: source,
10653
+ after: output.toString()
10654
+ });
10655
+ }
10656
+ const notes = [];
10657
+ for (const [name, files] of [...kept].sort(([left], [right]) => left.localeCompare(right))) {
10658
+ const from = viteHubServerImportSources.get(name);
10659
+ notes.push(`${appNames.get(name)} gives \`${name}\`, and Nuxt still auto-imports it, so ${files.size} file(s) keep the app's \`${name}\`. Import ViteHub's from "${from}" where you need it.`);
10660
+ }
10661
+ if (nitroFiles.length) notes.push(`Nuxt 5 also stops auto-importing the Nitro and H3 helpers, such as defineEventHandler, in ${nitroFiles.length} server file(s), for example ${nitroFiles[0]}. Import each one from the module that the Nuxt 5 build error names: "nitro/h3" or "nuxt/server".`);
10662
+ return {
10663
+ summary: edits.length ? `added ${added} vite-hub import(s) to ${edits.length} server file(s)` : followUps.length ? "left server files that need a manual check" : "found no server file that uses a ViteHub helper without an import",
10664
+ edits,
10665
+ followUps,
10666
+ notes,
10667
+ nextSteps: edits.length ? ["Run `npx nuxi prepare`, then type-check the app."] : []
10668
+ };
10669
+ }
10670
+ const nuxtServerImports = {
10671
+ name: "nuxt-server-imports",
10672
+ description: "Import the ViteHub server helpers, such as kv and sendQueue, from vite-hub/* in Nuxt server files that used the auto-imports",
10673
+ usage: "[dir]",
10674
+ detectAfterEdits: true,
10675
+ async detect({ cwd }) {
10676
+ const project = await readProject(cwd);
10677
+ if (!project || project.layout.state === "on") return void 0;
10678
+ if (project.layout.state === "unknown") return { reason: "the effective Nuxt server auto-import settings could not be determined statically" };
10679
+ if (serverLayoutFollowUps(project.layout).length) return { reason: "a Nuxt server directory could not be resolved statically" };
10680
+ const { names: appNames, unknown } = await appServerImports(cwd, project.layout);
10681
+ const names = new Set([...helperNames].filter((name) => !appNames.has(name)));
10682
+ for (const file of project.serverFiles) {
10683
+ const source = await readFile(join(cwd, file), "utf8");
10684
+ if (!helperPattern.test(source)) continue;
10685
+ let program;
10686
+ try {
10687
+ program = parse$2(file, source);
10688
+ } catch {
10689
+ continue;
10690
+ }
10691
+ const [name] = freeReferences(program, names).keys();
10692
+ if (name) return { reason: unknown.size ? `${file} uses ${name}, whose auto-import source could not be determined statically` : `${file} uses ${name} without an import, and Nuxt server auto-imports are off` };
10693
+ }
10694
+ },
8873
10695
  run: migrate$14
8874
10696
  };
8875
10697
  //#endregion
@@ -9642,14 +11464,16 @@ function insideAsyncFunction(ancestors) {
9642
11464
  return false;
9643
11465
  }
9644
11466
  /** Rewrites the KV and Blob calls of one server module to check the `[error, value]` tuple. */
9645
- function rewriteCalls$1(file, code, program, output, receivers, followUps) {
11467
+ function rewriteCalls$1(file, code, program, output, receivers, implicit, followUps) {
9646
11468
  const names = /* @__PURE__ */ new Set();
11469
+ const resolve = bindingResolver(program);
9647
11470
  walk(program, (node) => {
9648
11471
  if (node.type === "Identifier") names.add(node.name);
9649
11472
  });
9650
11473
  const sites = [];
9651
11474
  walk(program, (node, ancestors) => {
9652
11475
  if (node.type !== "Identifier" || !receivers.has(node.name)) return;
11476
+ if (implicit.has(node.name) && resolve(node)) return;
9653
11477
  const parent = ancestors.at(-1);
9654
11478
  if (!isReference(node, parent) || parent?.type === "TSTypeQuery") return;
9655
11479
  const feature = receivers.get(node.name);
@@ -9767,7 +11591,15 @@ function hasWhereCallback(ancestors) {
9767
11591
  return callback;
9768
11592
  }
9769
11593
  async function rewriteSources(input) {
9770
- const { cwd, features, schema } = input;
11594
+ const { cwd, features, schema, layout } = input;
11595
+ const { names: appNames, unknown } = await appServerImports(cwd, layout);
11596
+ const serverDirectories = layout.layers.flatMap((layer) => layer.server ?? []);
11597
+ const names = new Set([
11598
+ features.kv && "kv",
11599
+ features.blob && "blob",
11600
+ ...features.database ? ["db", "schema"] : []
11601
+ ].filter((name) => typeof name === "string"));
11602
+ const appOwned = new Set(appNames.keys());
9771
11603
  const files = await glob(["**/*.{ts,mts,cts,js,mjs,cjs,tsx,jsx,vue}"], {
9772
11604
  cwd,
9773
11605
  ignore: [
@@ -9786,17 +11618,17 @@ async function rewriteSources(input) {
9786
11618
  if (schema?.oldModule && schema.schemaModule) movedOld.set(schema.oldModule, schema.schemaModule);
9787
11619
  const result = {
9788
11620
  edits: [],
9789
- followUps: [],
11621
+ followUps: serverLayoutFollowUps(layout),
9790
11622
  imports: 0,
9791
11623
  calls: 0
9792
11624
  };
9793
11625
  for (const file of files.sort()) {
9794
11626
  if (input.skip.has(file)) continue;
9795
11627
  const source = await readFile(join(cwd, file), "utf8");
9796
- if (!/hub:|@nuxthub\/|hub[A-Z]\w*\(|\b(?:kv|blob|db)[.[]|useUpload|useMultipartUpload|db\/schema/.test(source)) continue;
11628
+ const server = serverDirectories.some((dir) => dir === "." || file.startsWith(`${dir}/`));
11629
+ if (!/hub:|@nuxthub\/|hub[A-Z]\w*\(|useUpload|useMultipartUpload|db\/schema/.test(source) && !(server && /\b(?:kv|blob|db|schema)\b/.test(source))) continue;
9797
11630
  const output = new MagicString(source);
9798
11631
  const followUps = [];
9799
- const server = file.split("/").includes("server");
9800
11632
  let blocks;
9801
11633
  try {
9802
11634
  blocks = scriptBlocks$6(file, source);
@@ -9821,6 +11653,7 @@ async function rewriteSources(input) {
9821
11653
  const bindings = blockBindings(program);
9822
11654
  const receivers = /* @__PURE__ */ new Map();
9823
11655
  const databases = /* @__PURE__ */ new Set();
11656
+ const implicit = /* @__PURE__ */ new Set();
9824
11657
  walk(program, (node) => {
9825
11658
  const literal = moduleSource(node);
9826
11659
  if (!literal) return;
@@ -9883,12 +11716,33 @@ async function rewriteSources(input) {
9883
11716
  receivers.delete(name);
9884
11717
  }
9885
11718
  if (server && script) {
9886
- for (const feature of ["kv", "blob"]) if (features[feature] && !bindings.has(feature)) receivers.set(feature, feature);
9887
- if (features.database && !bindings.has("db")) databases.add("db");
11719
+ if (unknown.size) {
11720
+ const uncertain = [...freeReferences(program, names).keys()].filter((name) => !appOwned.has(name));
11721
+ if (uncertain.length) followUps.push({
11722
+ file,
11723
+ message: unknownServerImports(unknown, uncertain)
11724
+ });
11725
+ } else {
11726
+ const { added } = addServerImports({
11727
+ code: block.code,
11728
+ program,
11729
+ output,
11730
+ offset: block.offset,
11731
+ style: detectStyle(block.code, program),
11732
+ skip: appOwned,
11733
+ names
11734
+ });
11735
+ for (const { name } of added) {
11736
+ implicit.add(name);
11737
+ if (name === "kv" || name === "blob") receivers.set(name, name);
11738
+ if (name === "db") databases.add(name);
11739
+ }
11740
+ }
9888
11741
  }
9889
- if (receivers.size && script) result.calls += rewriteCalls$1(file, source, program, output, receivers, followUps);
11742
+ if (receivers.size && script) result.calls += rewriteCalls$1(file, source, program, output, receivers, implicit, followUps);
11743
+ const resolve = bindingResolver(program);
9890
11744
  walk(program, (node, ancestors) => {
9891
- if (node.type === "MemberExpression" && keyName(node.property, node.computed) === "query" && node.object.type === "Identifier" && databases.has(node.object.name)) followUps.push({
11745
+ if (node.type === "MemberExpression" && keyName(node.property, node.computed) === "query" && node.object.type === "Identifier" && databases.has(node.object.name) && (!implicit.has(node.object.name) || !resolve(node.object))) followUps.push({
9892
11746
  file,
9893
11747
  line: at(node),
9894
11748
  message: hasWhereCallback(ancestors) ? "This query passes a function as where. Drizzle 1.0 reads where as an object, such as where: { id: 1 }, or where: { RAW: (table, { eq }) => eq(table.id, 1) }. Rewrite it, and check ownership filters and nested queries before running this call. orderBy functions still work. See https://orm.drizzle.team/docs/relations-v1-v2." : "Drizzle 1.0 changes relational queries. Check this query, migrate declared relations with defineRelations(), pass them to the Database Definition, and check nested queries before running this call. See https://orm.drizzle.team/docs/relations-v1-v2."
@@ -10368,7 +12222,8 @@ async function migrate$13({ cwd, dependencyRoot = cwd }) {
10368
12222
  cwd,
10369
12223
  features,
10370
12224
  schema,
10371
- skip
12225
+ skip,
12226
+ layout: await nuxtServerLayout(cwd, config)
10372
12227
  });
10373
12228
  const featurePackages = [
10374
12229
  features.database && "@vite-hub/database",
@@ -10399,7 +12254,7 @@ async function migrate$13({ cwd, dependencyRoot = cwd }) {
10399
12254
  features.blob && "blob",
10400
12255
  features.cache && "cache"
10401
12256
  ].filter(Boolean);
10402
- const notes = ["vite-hub/nuxt auto-imports kv, blob, db, and schema in server code for each enabled feature, as NuxtHub did.", "Local data stays in .data/. ViteHub reads .vitehub/data/. The follow-ups list the commands that copy it."];
12257
+ const notes = ["NuxtHub auto-imported kv, blob, db, and schema in server code. Nuxt 5 turns server auto-imports off, so the codemod imports them from vite-hub/* in each server file. Set experimental: { nitroAutoImports: true } in nuxt.config to auto-import them again.", "Local data stays in .data/. ViteHub reads .vitehub/data/. The follow-ups list the commands that copy it."];
10403
12258
  if (features.database) notes.push("NuxtHub's server/db/migrations/ stays in place for reference. ViteHub writes new migrations to server/databases/default/migrations/ and does not apply them during dev or build. Delete the old folder after the baseline.");
10404
12259
  if (features.cache) notes.push("Cached handlers come from Nitro and use the cache store of cache: true. In Nitro 3, import defineCachedHandler() (formerly cachedEventHandler()) and defineCachedFunction() from nitro/cache.");
10405
12260
  const installed = new Intl.ListFormat("en", { type: "conjunction" }).format(["vite-hub", ...featurePackages]);
@@ -13743,6 +15598,97 @@ const authRemoved = new Map([
13743
15598
  ["assertAuthOrigin", "Check the origin with `useAuth(event).$context` and its `isTrustedOrigin()`."]
13744
15599
  ].map(([name, fix]) => [name, `\`${name}\` is no longer public. ${fix}`]));
13745
15600
  const authPrivate = "ViteHub imports it in generated code. Remove the import.";
15601
+ /** `[name, fix]` pairs for exports that moved to an `internal/*` entry that only ViteHub packages import. */
15602
+ function internalNames(entries) {
15603
+ return new Map(entries.flatMap(([names, fix]) => names.map((name) => [name, `\`${name}\` is no longer public. ${fix}`])));
15604
+ }
15605
+ const packageOnly = "Only ViteHub packages use it. Remove the import.";
15606
+ const runtimeRemoved = internalNames([
15607
+ [[
15608
+ "hostedConsoleOrigin",
15609
+ "normalizeConsolePath",
15610
+ "normalizeConsoleProjectUrl",
15611
+ "consoleInvocationUrl"
15612
+ ], "Build a Console link with `hostedConsoleUrl(projectUrl, path)` from `vite-hub/runtime`."],
15613
+ [[
15614
+ "deserializeResponse",
15615
+ "isResponse",
15616
+ "isSerializedResponse",
15617
+ "serializeResponse"
15618
+ ], "Return a `Response` from the step, run, or Task. ViteHub stores it and gives it back."],
15619
+ [["emitTraceEvent"], "Append to the log of the context with `context.traceLog?.append(event)`."],
15620
+ [[
15621
+ "createExecutionBudget",
15622
+ "createRuntimeWaitUntilController",
15623
+ "decodeRouteSegment",
15624
+ "encodeRouteSegment",
15625
+ "isExecutionBudgetExceededError",
15626
+ "isResolvable",
15627
+ "isTraceContentAttributeKey",
15628
+ "leaseTable",
15629
+ "resolveRuntimeValue",
15630
+ "runtimeErrorDiagnostics",
15631
+ "traceEventsToOpenTelemetryLogRecords",
15632
+ "traceEventsToOpenTelemetrySpans"
15633
+ ], packageOnly]
15634
+ ]);
15635
+ const realtimeRemoved = internalNames([[[
15636
+ "applyRealtimeAwarenessUpdate",
15637
+ "applyRealtimeSyncMessage",
15638
+ "assertRealtimeRoomStateQuota",
15639
+ "bindAwarenessIdentity",
15640
+ "claimAwarenessClientIds",
15641
+ "compactRealtimeAwareness",
15642
+ "containsRealtimeState",
15643
+ "createRealtimeYDoc",
15644
+ "diffRealtimeYDoc",
15645
+ "encodeAwarenessState",
15646
+ "encodeSyncStep1",
15647
+ "encodeSyncUpdate",
15648
+ "isRealtimeWorkspaceDocument",
15649
+ "readRealtimeRequestState",
15650
+ "readRealtimeWorkspaceDocument",
15651
+ "readRealtimeYDoc",
15652
+ "realtimePersistenceDefaults",
15653
+ "realtimeRoomKey",
15654
+ "resolveRealtimeDefinition",
15655
+ "restoreRealtimeDocument",
15656
+ "RealtimeSyncOptions"
15657
+ ], "The generated Realtime route uses it. Remove the import."]]);
15658
+ const realtimeRootNames = /* @__PURE__ */ new Set([
15659
+ "RealtimeDocumentConflict",
15660
+ "isRealtimeDocumentConflict",
15661
+ "readRealtimeStatus",
15662
+ "realtimeDocumentLayout"
15663
+ ]);
15664
+ const commentsClientNames = /* @__PURE__ */ new Set(["commentsErrorDiagnostics"]);
15665
+ const commentsRemoved = internalNames([[[
15666
+ "builtinCommentSubjects",
15667
+ "commentsPageScope",
15668
+ "commentsRealtimeDefinition",
15669
+ "commentsRoute",
15670
+ "commentsRuntimeOf",
15671
+ "resolveCommentsRuntime"
15672
+ ], "The generated Comments route uses it. Remove the import."]]);
15673
+ const formsGuardNames = /* @__PURE__ */ new Set([
15674
+ "guardRequest",
15675
+ "GuardedRequest",
15676
+ "GuardRequestOptions",
15677
+ "GuardRequestServices"
15678
+ ]);
15679
+ const formsRemoved = internalNames([[["isFormDefinition"], "A file in `server/forms/` default-exports `defineForm()`. ViteHub checks it."]]);
15680
+ const workspaceFilesNames = /* @__PURE__ */ new Set([
15681
+ "normalizeSafeWorkspacePath",
15682
+ "resolveWorkspaceStoreTarget",
15683
+ "WorkspaceStoreTarget"
15684
+ ]);
15685
+ const workspaceRuntimeNames = /* @__PURE__ */ new Set(["invalidateWorkspaceStore", "resolveRegisteredWorkspaceDefinition"]);
15686
+ const workspaceRemoved = internalNames([[[
15687
+ "assertModelWorkspaceGlobPattern",
15688
+ "modelWorkspaceGlobPatternLimits",
15689
+ "resolveWorkspaceAutoCommit",
15690
+ "WorkspaceGlobPatternLimits"
15691
+ ], packageOnly]]);
13746
15692
  function moves() {
13747
15693
  return [
13748
15694
  {
@@ -13795,7 +15741,59 @@ function moves() {
13795
15741
  {
13796
15742
  from: "vite-hub/auth/console-runtime",
13797
15743
  privatePath: "`vite-hub/auth/console-runtime` is no longer public. Read users and sessions with `getAuthConsoleForRequest(request)` from `vite-hub/auth/server`."
13798
- }
15744
+ },
15745
+ {
15746
+ from: "vite-hub/runtime",
15747
+ removed: runtimeRemoved
15748
+ },
15749
+ {
15750
+ from: "@vite-hub/runtime",
15751
+ removed: runtimeRemoved
15752
+ },
15753
+ {
15754
+ from: "vite-hub/realtime/server",
15755
+ to: "vite-hub/realtime",
15756
+ names: realtimeRootNames,
15757
+ removed: realtimeRemoved
15758
+ },
15759
+ {
15760
+ from: "@vite-hub/realtime/server",
15761
+ to: "@vite-hub/realtime",
15762
+ names: realtimeRootNames,
15763
+ removed: realtimeRemoved
15764
+ },
15765
+ {
15766
+ from: "vite-hub/comments",
15767
+ to: "vite-hub/comments/client",
15768
+ names: commentsClientNames,
15769
+ removed: commentsRemoved
15770
+ },
15771
+ {
15772
+ from: "@vite-hub/comments",
15773
+ to: "@vite-hub/comments/client",
15774
+ names: commentsClientNames,
15775
+ removed: commentsRemoved
15776
+ },
15777
+ {
15778
+ from: "vite-hub/forms",
15779
+ removed: new Map([...formsRemoved, ...[...formsGuardNames].map((name) => [name, `\`${name}\` moved to \`@vite-hub/forms/guard\`. Install \`@vite-hub/forms\` and import it from there.`])])
15780
+ },
15781
+ {
15782
+ from: "@vite-hub/forms",
15783
+ to: "@vite-hub/forms/guard",
15784
+ names: formsGuardNames,
15785
+ removed: formsRemoved
15786
+ },
15787
+ ...["vite-hub/workspace", "@vite-hub/workspace"].map((from) => ({
15788
+ from,
15789
+ to: `${from}/files`,
15790
+ names: workspaceFilesNames,
15791
+ additional: {
15792
+ to: `${from}/runtime`,
15793
+ names: workspaceRuntimeNames
15794
+ },
15795
+ removed: workspaceRemoved
15796
+ }))
13799
15797
  ];
13800
15798
  }
13801
15799
  const rateLimitModules = /* @__PURE__ */ new Set(["vite-hub/rate-limit", "@vite-hub/rate-limit"]);
@@ -13829,11 +15827,11 @@ function importedName(specifier) {
13829
15827
  if (specifier.type !== "ImportSpecifier") return void 0;
13830
15828
  return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
13831
15829
  }
13832
- function isMoving(move, name) {
13833
- if (!move.to || name === void 0 || move.removed?.has(name)) return false;
13834
- if (move.names) return move.names.has(name);
13835
- if (move.keep) return !move.keep.has(name);
13836
- return true;
15830
+ function destination(move, name) {
15831
+ if (name === void 0 || move.removed?.has(name)) return void 0;
15832
+ if (move.additional?.names.has(name)) return move.additional.to;
15833
+ if (move.names ? !move.names.has(name) : move.keep?.has(name)) return void 0;
15834
+ return move.to;
13837
15835
  }
13838
15836
  /** The text of a moved specifier, with the new name when it was renamed. */
13839
15837
  function specifierText(context, specifier, move) {
@@ -13841,7 +15839,10 @@ function specifierText(context, specifier, move) {
13841
15839
  const imported = importedName(specifier);
13842
15840
  const renamed = imported ? move.renames?.get(imported) : void 0;
13843
15841
  if (!renamed || specifier.type !== "ImportSpecifier") return original;
13844
- return `${specifier.importKind === "type" ? "type " : ""}${renamed} as ${specifier.local.name}`;
15842
+ const from = start(specifier.imported) - start(specifier);
15843
+ const to = end(specifier.imported) - start(specifier);
15844
+ const alias = start(specifier.local) === start(specifier.imported) ? ` as ${specifier.local.name}` : "";
15845
+ return `${original.slice(0, from)}${renamed}${alias}${original.slice(to)}`;
13845
15846
  }
13846
15847
  function replaceSource(context, source, to) {
13847
15848
  const { block, output, style } = context;
@@ -13849,7 +15850,50 @@ function replaceSource(context, source, to) {
13849
15850
  }
13850
15851
  /** An import of `to` with named imports in the same file. The moved names join it. */
13851
15852
  function joinedImport(context, statement, to) {
13852
- return context.program.program.body.find((other) => other.type === "ImportDeclaration" && other !== statement && other.source.value === to && (other.importKind ?? "value") === (statement.importKind ?? "value") && other.specifiers.length > 0 && other.specifiers.every((specifier) => specifier.type === "ImportSpecifier"));
15853
+ if (hasImportComments(context, statement)) return void 0;
15854
+ return context.program.program.body.find((other) => other.type === "ImportDeclaration" && other !== statement && other.source.value === to && (other.importKind ?? "value") === (statement.importKind ?? "value") && other.specifiers.length > 0 && !hasImportComments(context, other) && other.specifiers.every((specifier) => specifier.type === "ImportSpecifier"));
15855
+ }
15856
+ function hasImportComments(context, statement) {
15857
+ return context.program.comments?.some((comment) => comment.start >= start(statement) && comment.end <= end(statement)) ?? false;
15858
+ }
15859
+ function skipImportTrivia(code, offset) {
15860
+ return offset + /^(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\r\n\u2028\u2029]*)*/.exec(code.slice(offset))[0].length;
15861
+ }
15862
+ function splitNamedImports(context, statement, move) {
15863
+ const { code } = context.block;
15864
+ const defaultImport = statement.specifiers.find((specifier) => specifier.type === "ImportDefaultSpecifier");
15865
+ const prefixEnd = skipImportTrivia(code, defaultImport ? end(defaultImport) : start(statement) + 6);
15866
+ const open = defaultImport ? skipImportTrivia(code, prefixEnd + 1) : statement.importKind === "type" ? skipImportTrivia(code, prefixEnd + 4) : prefixEnd;
15867
+ let cursor = open + 1;
15868
+ const kept = [];
15869
+ const moved = /* @__PURE__ */ new Map();
15870
+ let lastItems = kept;
15871
+ for (const specifier of statement.specifiers) {
15872
+ if (specifier.type !== "ImportSpecifier") continue;
15873
+ const separator = skipImportTrivia(code, end(specifier));
15874
+ const left = code.slice(cursor, start(specifier)).trimStart();
15875
+ const right = code.slice(end(specifier), separator).trimEnd();
15876
+ const trailingLineComment = (right.match(/\/\*[\s\S]*?\*\/|\/\/[^\r\n\u2028\u2029]*/g)?.at(-1))?.startsWith("//");
15877
+ const to = destination(move, importedName(specifier));
15878
+ const text = to ? specifierText(context, specifier, move) : code.slice(start(specifier), end(specifier));
15879
+ lastItems = to ? moved.get(to) ?? [] : kept;
15880
+ if (to) moved.set(to, lastItems);
15881
+ lastItems.push(left + text + right + (trailingLineComment ? "\n" : ""));
15882
+ cursor = code[separator] === "," ? separator + 1 : separator;
15883
+ }
15884
+ const close = skipImportTrivia(code, cursor);
15885
+ const afterTrailingComma = code.slice(cursor, close).trimStart();
15886
+ if (afterTrailingComma.trim()) {
15887
+ const items = kept.length ? kept : lastItems;
15888
+ items[items.length - 1] += `, ${afterTrailingComma}`;
15889
+ }
15890
+ return {
15891
+ prefixEnd,
15892
+ open,
15893
+ close,
15894
+ kept,
15895
+ moved
15896
+ };
13853
15897
  }
13854
15898
  /** Rewrites one import of a moved path. */
13855
15899
  function rewriteImport(context, statement, move) {
@@ -13863,36 +15907,52 @@ function rewriteImport(context, statement, move) {
13863
15907
  if (message) followUp(context, specifier, message);
13864
15908
  }
13865
15909
  if (!move.to) return;
13866
- const named = statement.specifiers.filter((specifier) => specifier.type === "ImportSpecifier");
13867
15910
  const others = statement.specifiers.filter((specifier) => specifier.type !== "ImportSpecifier");
13868
15911
  for (const specifier of others) followUp(context, specifier, `\`${move.from}\` changed: ${describeMove(move)} Update the reads through this ${specifier.type === "ImportNamespaceSpecifier" ? "namespace" : "default"} import by hand.`);
13869
- const moving = named.filter((specifier) => isMoving(move, importedName(specifier)));
13870
- if (!moving.length) return;
13871
- context.moved.add(move.to);
13872
- const texts = moving.map((specifier) => specifierText(context, specifier, move));
13873
- if (moving.length === statement.specifiers.length && !joinedImport(context, statement, move.to)) {
13874
- replaceSource(context, statement.source, move.to);
13875
- moving.forEach((specifier, index) => {
13876
- const text = texts[index];
15912
+ const moving = statement.specifiers.flatMap((specifier) => {
15913
+ const to = destination(move, importedName(specifier));
15914
+ return to ? [{
15915
+ specifier,
15916
+ to
15917
+ }] : [];
15918
+ });
15919
+ if (!moving[0]) return;
15920
+ const first = moving[0].to;
15921
+ const destinations = new Set(moving.map((item) => item.to));
15922
+ for (const to of destinations) context.moved.add(to);
15923
+ const target = destinations.size === 1 ? joinedImport(context, statement, first) : void 0;
15924
+ const wholeImport = moving.length === statement.specifiers.length;
15925
+ if (wholeImport && destinations.size === 1 && !target) {
15926
+ replaceSource(context, statement.source, first);
15927
+ for (const { specifier } of moving) {
15928
+ const text = specifierText(context, specifier, move);
13877
15929
  if (text !== block.code.slice(start(specifier), end(specifier))) output.overwrite(block.offset + start(specifier), block.offset + end(specifier), text);
13878
- });
15930
+ }
13879
15931
  return;
13880
15932
  }
13881
- for (const node of moving.length === statement.specifiers.length ? [statement] : moving) {
13882
- const [from, to] = listItemRemoval(block.code, node);
15933
+ const { prefixEnd, open, close, kept, moved } = splitNamedImports(context, statement, move);
15934
+ if (wholeImport && target) {
15935
+ const [from, to] = listItemRemoval(block.code, statement);
13883
15936
  output.remove(block.offset + from, block.offset + to);
13884
- }
13885
- const target = joinedImport(context, statement, move.to);
13886
- if (target) {
13887
- output.appendLeft(block.offset + end(target.specifiers.at(-1)), `, ${texts.join(", ")}`);
13888
- return;
13889
- }
15937
+ } else if (wholeImport) {
15938
+ replaceSource(context, statement.source, first);
15939
+ output.overwrite(block.offset + open + 1, block.offset + close, ` ${moved.get(first).join(", ")} `);
15940
+ moved.delete(first);
15941
+ } else if (kept.length) output.overwrite(block.offset + open + 1, block.offset + close, ` ${kept.join(", ")} `);
15942
+ else output.remove(block.offset + prefixEnd, block.offset + close + 1);
13890
15943
  const typeOnly = statement.importKind === "type" ? "type " : "";
13891
15944
  const semicolon = style.semicolons ? ";" : "";
13892
- output.appendLeft(block.offset + end(statement), `\nimport ${typeOnly}{ ${texts.join(", ")} } from ${quoteString(move.to, style)}${semicolon}`);
15945
+ for (const [to, items] of moved) {
15946
+ const target = joinedImport(context, statement, to);
15947
+ if (target) output.appendLeft(block.offset + end(target.specifiers.at(-1)), `, ${items.join(", ")}`);
15948
+ else output.appendLeft(block.offset + end(statement), `\nimport ${typeOnly}{ ${items.join(", ")} } from ${quoteString(to, style)}${semicolon}`);
15949
+ }
13893
15950
  }
13894
15951
  function describeMove(move) {
13895
- if (move.names) return `${[...move.names].map((name) => `\`${name}\``).join(" and ")} moved to \`${move.to}\`.`;
15952
+ if (move.names) {
15953
+ const describe = (names, to) => `${[...names].map((name) => `\`${name}\``).join(" and ")} moved to \`${to}\`.`;
15954
+ return move.additional ? `${describe(move.names, move.to)} ${describe(move.additional.names, move.additional.to)}` : describe(move.names, move.to);
15955
+ }
13896
15956
  if (move.keep) return `the names that ViteHub does not own moved to \`${move.to}\`.`;
13897
15957
  return `its exports moved to \`${move.to}\`.`;
13898
15958
  }
@@ -14013,7 +16073,7 @@ async function migrate$5({ cwd }) {
14013
16073
  }
14014
16074
  const runtimeContracts = {
14015
16075
  name: "runtime-contracts",
14016
- description: "Import getRuntimeContext and getStandardContext from vite-hub/runtime, read checkRateLimit() as a Result, and move private runtime, logs, and Auth imports",
16076
+ description: "Import getRuntimeContext and getStandardContext from vite-hub/runtime, read checkRateLimit() as a Result, and move private runtime, logs, Auth, Realtime, Comments, Forms, and Workspace imports",
14017
16077
  usage: "[dir]",
14018
16078
  async detect({ cwd }) {
14019
16079
  const files = (await glob(sourcePatterns$3, {
@@ -14023,7 +16083,7 @@ const runtimeContracts = {
14023
16083
  })).sort();
14024
16084
  for (const file of files) {
14025
16085
  const source = await readFile(join(cwd, file), "utf8");
14026
- const move = moves().find((move) => (source.includes(`"${move.from}"`) || source.includes(`'${move.from}'`)) && (move.to || move.privatePath || [...move.removed?.keys() ?? []].some((name) => new RegExp(`\\b${name}\\b`).test(source))));
16086
+ const move = moves().find((move) => (source.includes(`"${move.from}"`) || source.includes(`'${move.from}'`)) && (move.to && !move.names || move.privatePath || [...move.names ?? [], ...move.removed?.keys() ?? []].some((name) => new RegExp(`\\b${name}\\b`).test(source))));
14027
16087
  if (move) return { reason: `${file} imports ${move.from}` };
14028
16088
  if (source.includes("checkRateLimit") && [...rateLimitModules].some((module) => source.includes(module))) return { reason: `${file} calls checkRateLimit()` };
14029
16089
  }
@@ -14856,547 +16916,120 @@ const ignored$1 = [
14856
16916
  "**/node_modules/**",
14857
16917
  "**/.nuxt/**",
14858
16918
  "**/.output/**",
14859
- "**/.data/**",
14860
- "**/.vitehub/**",
14861
- "**/dist/**",
14862
- "**/coverage/**"
14863
- ];
14864
- /** Folders that ViteHub and Nuxt write. A `#vitehub/*` path into them maps an alias that ViteHub now types and resolves itself. */
14865
- const generatedFolder = /(?:^|\/)\.(?:vitehub|nuxt)\//;
14866
- function objectValue$1(node) {
14867
- return node?.type === "ObjectExpression" ? node : void 0;
14868
- }
14869
- function targets(property) {
14870
- if (property.value.type !== "ArrayExpression") return void 0;
14871
- const values = [];
14872
- for (const element of property.value.elements) {
14873
- if (element?.type !== "StringLiteral") return void 0;
14874
- values.push(element.value);
14875
- }
14876
- return values;
14877
- }
14878
- /** Plans the removal of the `#vitehub/*` entries of one tsconfig file's `compilerOptions.paths`. */
14879
- function planPaths(file, code) {
14880
- const plan = {
14881
- followUps: [],
14882
- removed: []
14883
- };
14884
- if (!code.includes("#vitehub/")) return plan;
14885
- let root;
14886
- try {
14887
- root = objectValue$1(parseExpression(code));
14888
- } catch {
14889
- plan.followUps.push({
14890
- file,
14891
- message: "The codemod could not parse this tsconfig. Remove the `#vitehub/*` entries of `compilerOptions.paths` by hand: ViteHub types and resolves them itself."
14892
- });
14893
- return plan;
14894
- }
14895
- const compilerOptions = objectValue$1(root && findProperty(root, "compilerOptions")?.value);
14896
- const pathsProperty = compilerOptions && findProperty(compilerOptions, "paths");
14897
- const paths = objectValue$1(pathsProperty?.value);
14898
- if (!pathsProperty || !paths) return plan;
14899
- const output = new MagicString(code);
14900
- const entries = paths.properties.filter((item) => item.type === "ObjectProperty");
14901
- for (const entry of entries) {
14902
- const alias = keyName(entry.key, entry.computed);
14903
- if (!alias?.startsWith("#vitehub/")) continue;
14904
- const values = targets(entry);
14905
- if (values?.length && values.every((value) => generatedFolder.test(value.replace(/^\.\//, "")))) {
14906
- const [from, to] = listItemRemoval(code, entry);
14907
- output.remove(from, to);
14908
- plan.removed.push(alias);
14909
- } else plan.followUps.push({
14910
- file,
14911
- line: line(entry),
14912
- message: `\`${alias}\` maps a ViteHub alias to your own file. ViteHub types and resolves \`#vitehub/*\` itself. Remove this entry unless it points at a test stub on purpose.`
14913
- });
14914
- }
14915
- if (!plan.removed.length) return plan;
14916
- if (plan.removed.length === paths.properties.length) {
14917
- const [from, to] = listItemRemoval(code, pathsProperty);
14918
- return {
14919
- ...plan,
14920
- edit: {
14921
- path: file,
14922
- before: code,
14923
- after: `${code.slice(0, from)}${code.slice(to)}`
14924
- }
14925
- };
14926
- }
14927
- return {
14928
- ...plan,
14929
- edit: {
14930
- path: file,
14931
- before: code,
14932
- after: output.toString()
14933
- }
14934
- };
14935
- }
14936
- async function tsconfigFiles(cwd) {
14937
- return (await glob(tsconfigPatterns, {
14938
- cwd,
14939
- ignore: ignored$1,
14940
- dot: false
14941
- })).sort();
14942
- }
14943
- async function migrate$2({ cwd }) {
14944
- const edits = [];
14945
- const followUps = [];
14946
- const notes = [];
14947
- for (const file of await tsconfigFiles(cwd)) {
14948
- const plan = planPaths(file, await readFile(join(cwd, file), "utf8"));
14949
- if (plan.edit) edits.push(plan.edit);
14950
- followUps.push(...plan.followUps);
14951
- if (plan.removed.length) notes.push(`${file}: removed ${plan.removed.map((alias) => `\`${alias}\``).join(", ")} from compilerOptions.paths. ViteHub generates their types in .vitehub/types/.`);
14952
- }
14953
- return {
14954
- summary: edits.length ? `removed stale #vitehub/* paths from ${edits.length} tsconfig file(s)` : "found no #vitehub/* path to remove",
14955
- edits,
14956
- followUps,
14957
- notes,
14958
- nextSteps: edits.length ? ["Run `vitehub types prepare` or start the dev server, so ViteHub writes the types of the #vitehub/* aliases."] : []
14959
- };
14960
- }
14961
- const tsconfigPaths = {
14962
- name: "tsconfig-paths",
14963
- description: "Remove the #vitehub/* entries of tsconfig paths that point into generated folders, because ViteHub types those aliases itself",
14964
- usage: "[dir]",
14965
- async detect({ cwd }) {
14966
- for (const file of await tsconfigFiles(cwd)) {
14967
- const plan = planPaths(file, await readFile(join(cwd, file), "utf8"));
14968
- if (plan.edit || plan.followUps.length) return { reason: `${file} maps #vitehub/* in compilerOptions.paths` };
14969
- }
14970
- },
14971
- run: migrate$2
14972
- };
14973
- //#endregion
14974
- //#region src/vitehub-options/transform.ts
14975
- /** Top-level Vite keys that owner plugins read before `vitehub()` became the only config place. */
14976
- const removedViteKeys = [
14977
- "agent",
14978
- "auth",
14979
- "blob",
14980
- "browser",
14981
- "database",
14982
- "kv",
14983
- "queue",
14984
- "rateLimit",
14985
- "sandboxTask",
14986
- "vitehub",
14987
- "workflow",
14988
- "workspace"
14989
- ];
14990
- /** The standalone plugin that takes the options of each key as its argument. */
14991
- const ownerPlugins = {
14992
- agent: {
14993
- name: "hubAgent",
14994
- package: "agent"
14995
- },
14996
- auth: {
14997
- name: "hubAuth",
14998
- package: "auth"
14999
- },
15000
- blob: {
15001
- name: "hubBlob",
15002
- package: "blob"
15003
- },
15004
- browser: {
15005
- name: "hubBrowser",
15006
- package: "browser"
15007
- },
15008
- database: {
15009
- name: "hubDatabase",
15010
- previousName: "hubDb",
15011
- package: "database"
15012
- },
15013
- kv: {
15014
- name: "hubKV",
15015
- previousName: "hubKv",
15016
- package: "kv"
15017
- },
15018
- queue: {
15019
- name: "hubQueue",
15020
- package: "queue"
15021
- },
15022
- rateLimit: {
15023
- name: "hubRateLimit",
15024
- package: "rate-limit"
15025
- },
15026
- sandboxTask: {
15027
- name: "hubSandboxTask",
15028
- package: "sandbox/task"
15029
- },
15030
- workflow: {
15031
- name: "hubWorkflow",
15032
- package: "workflow"
15033
- },
15034
- workspace: {
15035
- name: "hubWorkspace",
15036
- package: "workspace"
15037
- }
15038
- };
15039
- const configFunctions = /* @__PURE__ */ new Set(["defineConfig", "defineNuxtConfig"]);
15040
- /** The object of `defineConfig({...})`, `defineConfig(() => ({...}))`, `defineNuxtConfig({...})`, or `export default {...}`. */
15041
- function findConfigRoot(program, followUps, file) {
15042
- const exported = program.program.body.find((statement) => statement.type === "ExportDefaultDeclaration");
15043
- if (!exported) return void 0;
15044
- let value = unwrapExpression(exported.declaration);
15045
- if (value.type === "Identifier") {
15046
- const name = value.name;
15047
- for (const statement of program.program.body) {
15048
- if (statement.type !== "VariableDeclaration") continue;
15049
- for (const declarator of statement.declarations) if (declarator.id.type === "Identifier" && declarator.id.name === name && declarator.init) value = unwrapExpression(declarator.init);
15050
- }
15051
- }
15052
- if (value.type === "CallExpression") {
15053
- if (value.callee.type !== "Identifier" || !configFunctions.has(value.callee.name)) return void 0;
15054
- const [argument] = value.arguments;
15055
- if (!argument) return void 0;
15056
- value = unwrapExpression(argument);
15057
- }
15058
- if (value.type === "ArrowFunctionExpression" || value.type === "FunctionExpression" || value.type === "FunctionDeclaration") {
15059
- if (value.body.type !== "BlockStatement") value = unwrapExpression(value.body);
15060
- else {
15061
- const returns = [];
15062
- walk(value.body, (node, ancestors) => {
15063
- if (node.type === "ReturnStatement" && node.argument && !ancestors.some((ancestor) => ancestor.type === "ArrowFunctionExpression" || ancestor.type === "FunctionExpression" || ancestor.type === "FunctionDeclaration" || ancestor.type === "ObjectMethod" || ancestor.type === "ClassMethod" || ancestor.type === "ClassPrivateMethod")) returns.push(node.argument);
15064
- });
15065
- const returned = returns.length === 1 ? objectValue(returns[0]) : void 0;
15066
- if (!returned) {
15067
- followUps.push({
15068
- file,
15069
- line: line(value),
15070
- message: "The config factory does not return one object literal. Move top-level feature and Env options into vitehub() or owner plugin arguments, and move observability.logs to the top-level logs key by hand."
15071
- });
15072
- return;
15073
- }
15074
- value = returned;
15075
- }
15076
- }
15077
- return value.type === "ObjectExpression" ? value : void 0;
15078
- }
15079
- function property(object, name) {
15080
- return findProperty(object, name);
15081
- }
16919
+ "**/.data/**",
16920
+ "**/.vitehub/**",
16921
+ "**/dist/**",
16922
+ "**/coverage/**"
16923
+ ];
16924
+ /** Folders that ViteHub and Nuxt write. A `#vitehub/*` path into them maps an alias that ViteHub now types and resolves itself. */
16925
+ const generatedFolder = /(?:^|\/)\.(?:vitehub|nuxt)\//;
15082
16926
  function objectValue(node) {
15083
- const value = node ? unwrapExpression(node) : void 0;
15084
- return value?.type === "ObjectExpression" ? value : void 0;
15085
- }
15086
- function nuxtEnvironmentOverrides(root) {
15087
- return root.properties.flatMap((item) => {
15088
- if (item.type !== "ObjectProperty") return [];
15089
- const name = keyName(item.key, item.computed);
15090
- const scope = objectValue(item.value);
15091
- if (!scope || !name?.startsWith("$")) return [];
15092
- if (name !== "$env") return [scope];
15093
- return scope.properties.flatMap((entry) => {
15094
- const override = entry.type === "ObjectProperty" ? objectValue(entry.value) : void 0;
15095
- return override ? [override] : [];
15096
- });
15097
- });
15098
- }
15099
- function logsMode(node) {
15100
- const value = unwrapExpression(node);
15101
- if (value.type === "BooleanLiteral") return value.value ? "capture" : "possibly-disabled";
15102
- if (value.type === "ObjectExpression") {
15103
- if (value.properties.some((item) => item.type === "SpreadElement" || keyName(item.key, item.computed) === void 0)) return;
15104
- return value.properties.some((item) => item.type !== "SpreadElement" && keyName(item.key, item.computed) === "source") ? "source" : "capture";
15105
- }
15106
- if (value.type === "SequenceExpression") return logsMode(value.expressions.at(-1));
15107
- if (value.type === "ConditionalExpression") {
15108
- const left = logsMode(value.consequent);
15109
- const right = logsMode(value.alternate);
15110
- if (left === right) return left;
15111
- if (left && right && left !== "source" && right !== "source") return "possibly-disabled";
15112
- }
16927
+ return node?.type === "ObjectExpression" ? node : void 0;
15113
16928
  }
15114
- /** Value imports of the expected API, checked against each call's lexical binding. */
15115
- function importedNames(program, sources, imported) {
15116
- const names = /* @__PURE__ */ new Map();
15117
- const imports = typeof imported === "string" ? [imported] : imported;
15118
- for (const statement of program.program.body) {
15119
- if (statement.type !== "ImportDeclaration" || statement.importKind === "type" || !sources.includes(statement.source.value)) continue;
15120
- for (const specifier of statement.specifiers) if (specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && imports.some((name) => name === keyName(specifier.imported))) names.set(specifier.local.name, specifier.local);
16929
+ function targets(property) {
16930
+ if (property.value.type !== "ArrayExpression") return void 0;
16931
+ const values = [];
16932
+ for (const element of property.value.elements) {
16933
+ if (element?.type !== "StringLiteral") return void 0;
16934
+ values.push(element.value);
15121
16935
  }
15122
- return names;
15123
- }
15124
- function callsOf(scope, names, resolveBinding) {
15125
- const calls = [];
15126
- walk(scope, (node) => {
15127
- if (node.type === "CallExpression" && node.callee.type === "Identifier" && names.has(node.callee.name) && names.get(node.callee.name) === resolveBinding(node.callee)) calls.push(node);
15128
- });
15129
- return calls;
15130
- }
15131
- /** Moves the lines of `text` after the first from the indentation `from` to `to`. */
15132
- function reindent(text, from, to) {
15133
- if (from === to) return text;
15134
- return text.split("\n").map((value, index) => {
15135
- if (index === 0 || !value.trim()) return value;
15136
- if (value.startsWith(from)) return to + value.slice(from.length);
15137
- return to.length > from.length ? to.slice(from.length) + value : value;
15138
- }).join("\n");
16936
+ return values;
15139
16937
  }
15140
- /**
15141
- * Moves the vite-hub options of a config file. `findRoots` selects other config objects, such as the inline configs of
15142
- * a test file. Without it, the file's default export is the config.
15143
- */
15144
- function migrateViteHubOptions(file, code, findRoots) {
15145
- const followUps = [];
15146
- const notes = [];
15147
- const unchanged = {
15148
- code,
15149
- changed: false,
15150
- followUps,
15151
- notes
16938
+ /** Plans the removal of the `#vitehub/*` entries of one tsconfig file's `compilerOptions.paths`. */
16939
+ function planPaths(file, code) {
16940
+ const plan = {
16941
+ followUps: [],
16942
+ removed: []
15152
16943
  };
15153
- if (!/vite-hub|vitehub|hubEnv/.test(code)) return unchanged;
15154
- let program;
16944
+ if (!code.includes("#vitehub/")) return plan;
16945
+ let root;
15155
16946
  try {
15156
- program = parseProgram(code);
16947
+ root = objectValue(parseExpression(code));
15157
16948
  } catch {
15158
- return unchanged;
16949
+ plan.followUps.push({
16950
+ file,
16951
+ message: "The codemod could not parse this tsconfig. Remove the `#vitehub/*` entries of `compilerOptions.paths` by hand: ViteHub types and resolves them itself."
16952
+ });
16953
+ return plan;
15159
16954
  }
15160
- const defaultRoot = findConfigRoot(program, followUps, file);
15161
- const roots = findRoots ? findRoots(program) : defaultRoot ? [defaultRoot] : [];
15162
- if (!roots[0]) return unchanged;
15163
- const nuxt = basename(file).startsWith("nuxt.config");
15164
- const editor = new ConfigEditor({
15165
- code,
15166
- fileName: file,
15167
- path: file,
15168
- program,
15169
- root: roots[0]
15170
- });
15171
- const resolveBinding = bindingResolver(program);
15172
- const removed = /* @__PURE__ */ new Set();
15173
- const additions = /* @__PURE__ */ new Map();
15174
- const insertProperties = (object, entries) => {
15175
- additions.set(object, [...additions.get(object) ?? [], ...entries]);
15176
- };
15177
- let changed = false;
15178
- const text = (node) => code.slice(start(node), end(node));
15179
- const follow = (node, message) => followUps.push({
15180
- file,
15181
- line: line(node),
15182
- message
15183
- });
15184
- const remove = (node) => {
15185
- editor.removeItem(node);
15186
- removed.add(node);
15187
- changed = true;
15188
- };
15189
- /** Renames the `from` key of a vite-hub options object to `to`, and keeps its value. */
15190
- const renameKey = (options, from, to, conflict) => {
15191
- const item = property(options, from);
15192
- if (!item) return;
15193
- if (property(options, to)) {
15194
- follow(item, conflict);
15195
- return;
15196
- }
15197
- if (item.shorthand || item.computed) editor.output.overwrite(start(item), end(item), `${to}: ${text(item.value)}`);
15198
- else editor.output.overwrite(start(item.key), end(item.key), to);
15199
- changed = true;
15200
- };
15201
- for (const root of roots) {
15202
- const optionObjects = [];
15203
- const environmentOptions = [];
15204
- const emptyCalls = [];
15205
- if (nuxt) {
15206
- const key = objectValue(property(root, "vitehub")?.value);
15207
- if (key) optionObjects.push(key);
15208
- const entry = findViteHubEntry({
15209
- code,
15210
- fileName: file,
16955
+ const compilerOptions = objectValue(root && findProperty(root, "compilerOptions")?.value);
16956
+ const pathsProperty = compilerOptions && findProperty(compilerOptions, "paths");
16957
+ const paths = objectValue(pathsProperty?.value);
16958
+ if (!pathsProperty || !paths) return plan;
16959
+ const output = new MagicString(code);
16960
+ const entries = paths.properties.filter((item) => item.type === "ObjectProperty");
16961
+ for (const entry of entries) {
16962
+ const alias = keyName(entry.key, entry.computed);
16963
+ if (!alias?.startsWith("#vitehub/")) continue;
16964
+ const values = targets(entry);
16965
+ if (values?.length && values.every((value) => generatedFolder.test(value.replace(/^\.\//, "")))) {
16966
+ const [from, to] = listItemRemoval(code, entry);
16967
+ output.remove(from, to);
16968
+ plan.removed.push(alias);
16969
+ } else plan.followUps.push({
16970
+ file,
16971
+ line: line(entry),
16972
+ message: `\`${alias}\` maps a ViteHub alias to your own file. ViteHub types and resolves \`#vitehub/*\` itself. Remove this entry unless it points at a test stub on purpose.`
16973
+ });
16974
+ }
16975
+ if (!plan.removed.length) return plan;
16976
+ if (plan.removed.length === paths.properties.length) {
16977
+ const [from, to] = listItemRemoval(code, pathsProperty);
16978
+ return {
16979
+ ...plan,
16980
+ edit: {
15211
16981
  path: file,
15212
- program,
15213
- root
15214
- });
15215
- const inline = entry?.type === "ArrayExpression" ? objectValue(entry.elements[1] ?? void 0) : void 0;
15216
- if (inline) optionObjects.push(inline);
15217
- for (const scope of nuxtEnvironmentOverrides(root)) {
15218
- const options = objectValue(property(scope, "vitehub")?.value);
15219
- if (options) environmentOptions.push(options);
15220
- const entry = findViteHubEntry({
15221
- code,
15222
- fileName: file,
15223
- path: file,
15224
- program,
15225
- root: scope
15226
- });
15227
- const inline = entry?.type === "ArrayExpression" ? objectValue(entry.elements[1] ?? void 0) : void 0;
15228
- if (inline) environmentOptions.push(inline);
15229
- }
15230
- } else {
15231
- const names = importedNames(program, ["vite-hub"], "vitehub");
15232
- const local = callsOf(root, names, resolveBinding);
15233
- for (const call of local.length || findRoots ? local : callsOf(program, names, resolveBinding)) {
15234
- const [argument] = call.arguments;
15235
- const options = objectValue(argument);
15236
- if (options) optionObjects.push(options);
15237
- else if (!argument) emptyCalls.push(call);
15238
- }
15239
- }
15240
- for (const options of [...optionObjects, ...environmentOptions]) {
15241
- renameKey(options, "preset", "host", "Both preset and host are set. Remove preset: host picks the deployment target.");
15242
- const sandbox = property(options, "sandbox");
15243
- const sandboxValue = sandbox ? unwrapExpression(sandbox.value) : void 0;
15244
- if (sandbox && sandboxValue?.type === "BooleanLiteral") {
15245
- if (!sandboxValue.value) remove(sandbox);
15246
- else renameKey(options, "sandbox", "sandboxTask", "Both sandbox and sandboxTask are set. Remove sandbox.");
15247
- } else if (sandbox) follow(sandbox, "sandbox is now sandboxTask. Move these options into sandboxTask by hand.");
15248
- const devtools = property(options, "devtools");
15249
- if (devtools) {
15250
- remove(devtools);
15251
- notes.push(`${file}: removed devtools. Use the ViteHub Console with console: true.`);
15252
- }
15253
- const cloudflare = property(options, "cloudflare");
15254
- 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.");
15255
- const contentImportBase = property(options, "contentImportBase");
15256
- if (contentImportBase) {
15257
- remove(contentImportBase);
15258
- notes.push(`${file}: removed contentImportBase. ViteHub always imports Content from vite-hub/content.`);
15259
- }
15260
- const observability = property(options, "observability");
15261
- const observabilityValue = observability ? unwrapExpression(observability.value) : void 0;
15262
- const observabilityObject = objectValue(observability?.value);
15263
- const logs = property(options, "logs");
15264
- const nestedLogs = observabilityObject ? property(observabilityObject, "logs") : void 0;
15265
- if (observability && observabilityObject && nestedLogs) {
15266
- if (logs) {
15267
- follow(nestedLogs, "Both logs and observability.logs are set. Merge observability.logs into logs by hand.");
15268
- continue;
15269
- }
15270
- const mode = logsMode(nestedLogs.value);
15271
- const onlyLogs = observabilityObject.properties.length === 1;
15272
- const service = property(observabilityObject, "service");
15273
- const serviceValue = service && unwrapExpression(service.value);
15274
- const hasService = serviceValue?.type === "StringLiteral" && Boolean(serviceValue.value);
15275
- if (!mode || observabilityObject.properties.some((item) => item.type === "SpreadElement") || mode === "source" && !onlyLogs && !hasService) {
15276
- follow(nestedLogs, "Move observability.logs to logs by hand. Keep observability to preserve Evlog when capture is disabled; omit or disable observability for a read-only source that did not run Evlog.");
15277
- continue;
15278
- }
15279
- const parenStart = nestedLogs.value.extra?.parenStart;
15280
- const value = code.slice(typeof parenStart === "number" ? parenStart : start(nestedLogs.value), end(nestedLogs));
15281
- const indent = indentAt(code, start(observability));
15282
- const logsText = `logs: ${reindent(value, indentAt(code, start(nestedLogs)), indent)}`;
15283
- const separator = text(options).includes("\n") ? `,\n${indent}` : ", ";
15284
- if (onlyLogs) editor.output.overwrite(start(observability), end(observability), mode === "possibly-disabled" ? `observability: true${separator}${logsText}` : logsText);
15285
- else {
15286
- editor.output.appendLeft(end(observability), `${separator}${logsText}`);
15287
- remove(nestedLogs);
15288
- }
15289
- changed = true;
15290
- continue;
15291
- }
15292
- 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.");
15293
- const logsObject = objectValue(logs?.value);
15294
- const evlog = logsObject ? property(logsObject, "evlog") : void 0;
15295
- if (!logs || !logsObject || !evlog) continue;
15296
- if (observabilityObject && property(observabilityObject, "evlog")) {
15297
- follow(logs, "Both logs.evlog and observability.evlog are set. Merge logs.evlog into observability.evlog by hand.");
15298
- continue;
15299
- }
15300
- if (observability && !observabilityObject && !(observabilityValue?.type === "BooleanLiteral" && observabilityValue.value)) {
15301
- follow(logs, "observability is not an object literal. Move logs.evlog into observability.evlog by hand.");
15302
- continue;
16982
+ before: code,
16983
+ after: `${code.slice(0, from)}${code.slice(to)}`
15303
16984
  }
15304
- if (!observability) insertProperties(options, [`observability: { ${text(evlog)} }`]);
15305
- else if (observabilityObject) insertProperties(observabilityObject, [text(evlog)]);
15306
- else if (observabilityValue) editor.output.overwrite(start(observabilityValue), end(observabilityValue), `{ ${text(evlog)} }`);
15307
- if (logsObject.properties.length === 1) {
15308
- editor.output.overwrite(start(logs.value), end(logs.value), "true");
15309
- changed = true;
15310
- } else remove(evlog);
15311
- }
15312
- const viteObject = nuxt ? objectValue(property(root, "vite")?.value) : root;
15313
- const envProperty = viteObject ? property(viteObject, "env") : void 0;
15314
- if (envProperty && viteObject) {
15315
- const envValue = unwrapExpression(envProperty.value);
15316
- const envText = text(envValue);
15317
- const sourceIndent = indentAt(code, start(envProperty));
15318
- const hubEnvNames = importedNames(program, ["@vite-hub/env/vite", "vite-hub/env/vite"], "hubEnv");
15319
- const localHubEnvCalls = callsOf(root, hubEnvNames, resolveBinding);
15320
- const hubEnvCalls = nuxt ? [] : localHubEnvCalls.length || findRoots ? localHubEnvCalls : callsOf(program, hubEnvNames, resolveBinding);
15321
- const viteHubTargets = optionObjects.length + emptyCalls.length;
15322
- const moveInto = (target, nested) => {
15323
- const targetEnv = nested ? property(target, "env") : void 0;
15324
- if (nested && !targetEnv) {
15325
- const indent = editor.propertyIndent(target);
15326
- insertProperties(target, [`env: ${reindent(envText, sourceIndent, indent)}`]);
15327
- return true;
15328
- }
15329
- const envOptions = nested ? objectValue(targetEnv.value) : target;
15330
- if (!envOptions) {
15331
- follow(envProperty, nested ? "The Env option of vitehub() is not an object literal. Move these declarations into vitehub({ env }) by hand." : "hubEnv() options are not an object literal. Move these declarations into hubEnv() by hand.");
15332
- return false;
15333
- }
15334
- const indent = editor.propertyIndent(envOptions);
15335
- if (envValue.type !== "ObjectExpression") {
15336
- insertProperties(envOptions, [`...${reindent(envText, sourceIndent, indent)}`]);
15337
- return true;
15338
- }
15339
- const conflict = envValue.properties.find((item) => item.type === "ObjectProperty" && property(envOptions, keyName(item.key, item.computed) ?? ""));
15340
- if (conflict) {
15341
- follow(envProperty, `env.${keyName(conflict.key) ?? ""} is set in two places. Merge the declarations into one object by hand.`);
15342
- return false;
15343
- }
15344
- const propertyIndent = envValue.properties[0] ? indentAt(code, start(envValue.properties[0])) : sourceIndent;
15345
- insertProperties(envOptions, envValue.properties.map((item) => reindent(text(item), propertyIndent, indent)));
15346
- return true;
15347
- };
15348
- let moved = false;
15349
- const targetEnv = optionObjects[0] ? property(optionObjects[0], "env") : void 0;
15350
- const targetEnvValue = targetEnv ? unwrapExpression(targetEnv.value) : void 0;
15351
- const envOff = targetEnvValue?.type === "BooleanLiteral" && !targetEnvValue.value;
15352
- if (viteHubTargets > 1) follow(envProperty, "The config has more than one vite-hub options object. Move env into the right one by hand.");
15353
- else if (optionObjects[0] && envOff && hubEnvCalls.length !== 1) follow(envProperty, "vitehub({ env: false }) turns Env off, but the config declares Env. Remove one of them.");
15354
- else if (optionObjects[0] && !envOff) moved = moveInto(optionObjects[0], true);
15355
- else if (emptyCalls[0]) {
15356
- const callIndent = indentAt(code, start(emptyCalls[0]));
15357
- const indent = `${callIndent}${editor.style.indent}`;
15358
- editor.output.appendLeft(end(emptyCalls[0]) - 1, `{\n${indent}env: ${reindent(envText, sourceIndent, indent)},\n${callIndent}}`);
15359
- moved = true;
15360
- } else if (hubEnvCalls.length === 1) {
15361
- const call = hubEnvCalls[0];
15362
- const [argument] = call.arguments;
15363
- const options = objectValue(argument);
15364
- if (options) moved = moveInto(options, false);
15365
- else if (!argument) {
15366
- editor.output.appendLeft(end(call) - 1, reindent(envText, sourceIndent, indentAt(code, start(call))));
15367
- moved = true;
15368
- } else follow(envProperty, "hubEnv() options are not an object literal. Move these declarations into hubEnv() by hand.");
15369
- } 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.");
15370
- if (moved) {
15371
- const viteProperty = nuxt ? property(root, "vite") : void 0;
15372
- if (viteProperty && viteObject.properties.length === 1) remove(viteProperty);
15373
- else remove(envProperty);
15374
- }
15375
- }
15376
- if (viteObject) for (const key of removedViteKeys) {
15377
- const item = property(viteObject, key);
15378
- if (!item || removed.has(item)) continue;
15379
- const value = unwrapExpression(item.value);
15380
- const sourceIndent = indentAt(code, start(item));
15381
- const plugin = ownerPlugins[key];
15382
- 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) : [];
15383
- if (key !== "vitehub" && optionObjects.length === 1 && !emptyCalls.length && !property(optionObjects[0], key)) {
15384
- insertProperties(optionObjects[0], [`${key}: ${reindent(text(value), sourceIndent, editor.propertyIndent(optionObjects[0]))}`]);
15385
- remove(item);
15386
- } else if (!optionObjects.length && !emptyCalls.length && pluginCalls.length === 1 && !pluginCalls[0].arguments.length) {
15387
- editor.output.appendLeft(end(pluginCalls[0]) - 1, reindent(text(value), sourceIndent, indentAt(code, start(pluginCalls[0]))));
15388
- remove(item);
15389
- } else follow(item, nuxt ? `vite.${key} is no longer read. Set ${key} in the vite-hub/nuxt options.` : `The top-level Vite ${key} key is no longer read. Move it into vitehub({ ${key} }), or pass it to the feature's plugin.`);
16985
+ };
16986
+ }
16987
+ return {
16988
+ ...plan,
16989
+ edit: {
16990
+ path: file,
16991
+ before: code,
16992
+ after: output.toString()
15390
16993
  }
16994
+ };
16995
+ }
16996
+ async function tsconfigFiles(cwd) {
16997
+ return (await glob(tsconfigPatterns, {
16998
+ cwd,
16999
+ ignore: ignored$1,
17000
+ dot: false
17001
+ })).sort();
17002
+ }
17003
+ async function migrate$2({ cwd }) {
17004
+ const edits = [];
17005
+ const followUps = [];
17006
+ const notes = [];
17007
+ for (const file of await tsconfigFiles(cwd)) {
17008
+ const plan = planPaths(file, await readFile(join(cwd, file), "utf8"));
17009
+ if (plan.edit) edits.push(plan.edit);
17010
+ followUps.push(...plan.followUps);
17011
+ if (plan.removed.length) notes.push(`${file}: removed ${plan.removed.map((alias) => `\`${alias}\``).join(", ")} from compilerOptions.paths. ViteHub generates their types in .vitehub/types/.`);
15391
17012
  }
15392
- for (const [object, entries] of additions) editor.insertProperties(object, entries, removed);
15393
- return changed ? {
15394
- code: editor.output.toString(),
15395
- changed,
17013
+ return {
17014
+ summary: edits.length ? `removed stale #vitehub/* paths from ${edits.length} tsconfig file(s)` : "found no #vitehub/* path to remove",
17015
+ edits,
15396
17016
  followUps,
15397
- notes
15398
- } : unchanged;
17017
+ notes,
17018
+ nextSteps: edits.length ? ["Run `vitehub types prepare` or start the dev server, so ViteHub writes the types of the #vitehub/* aliases."] : []
17019
+ };
15399
17020
  }
17021
+ const tsconfigPaths = {
17022
+ name: "tsconfig-paths",
17023
+ description: "Remove the #vitehub/* entries of tsconfig paths that point into generated folders, because ViteHub types those aliases itself",
17024
+ usage: "[dir]",
17025
+ async detect({ cwd }) {
17026
+ for (const file of await tsconfigFiles(cwd)) {
17027
+ const plan = planPaths(file, await readFile(join(cwd, file), "utf8"));
17028
+ if (plan.edit || plan.followUps.length) return { reason: `${file} maps #vitehub/* in compilerOptions.paths` };
17029
+ }
17030
+ },
17031
+ run: migrate$2
17032
+ };
15400
17033
  //#endregion
15401
17034
  //#region src/vitehub-options/index.ts
15402
17035
  const configPatterns = ["**/{vite,nuxt}.config.{ts,mts,cts,js,mjs,cjs}"];
@@ -15445,6 +17078,31 @@ async function configFiles(cwd) {
15445
17078
  ignore: ignored
15446
17079
  })).sort();
15447
17080
  }
17081
+ async function migrations(cwd) {
17082
+ const files = await configFiles(cwd);
17083
+ const imported = importedConfigOptions(cwd, files, (program, file) => findConfigRoot(program, [], file));
17084
+ const results = [];
17085
+ for (const file of files) {
17086
+ const before = await readFile(join(cwd, file), "utf8");
17087
+ results.push({
17088
+ before,
17089
+ file,
17090
+ result: migrateViteHubOptions(file, before)
17091
+ });
17092
+ }
17093
+ for (const [file, positions] of [...imported.options.entries()].sort(([left], [right]) => left.localeCompare(right))) {
17094
+ const before = await readFile(join(cwd, file), "utf8");
17095
+ results.push({
17096
+ before,
17097
+ file,
17098
+ result: migrateViteHubOptions(file, before, (program) => optionsAt(program, positions))
17099
+ });
17100
+ }
17101
+ return {
17102
+ results,
17103
+ followUps: imported.followUps
17104
+ };
17105
+ }
15448
17106
  /** Source lines that name a renamed option type. The codemod reports them and edits nothing. */
15449
17107
  async function renamedTypeReferences(cwd) {
15450
17108
  const followUps = [];
@@ -15466,12 +17124,9 @@ async function renamedTypeReferences(cwd) {
15466
17124
  }
15467
17125
  async function migrate$1({ cwd }) {
15468
17126
  const edits = [];
15469
- const followUps = [];
17127
+ const { results, followUps } = await migrations(cwd);
15470
17128
  const notes = [];
15471
- const files = await configFiles(cwd);
15472
- for (const file of files) {
15473
- const before = await readFile(join(cwd, file), "utf8");
15474
- const result = migrateViteHubOptions(file, before);
17129
+ for (const { before, file, result } of results) {
15475
17130
  followUps.push(...result.followUps);
15476
17131
  notes.push(...result.notes);
15477
17132
  if (result.changed) edits.push({
@@ -15481,7 +17136,7 @@ async function migrate$1({ cwd }) {
15481
17136
  });
15482
17137
  }
15483
17138
  followUps.push(...await renamedTypeReferences(cwd));
15484
- if (!edits.length && !followUps.length) throw codemodError("No vite.config or nuxt.config sets preset, sandbox, devtools, observability.logs, logs.evlog, contentImportBase, or a top-level env, so there is nothing to migrate.");
17139
+ 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.");
15485
17140
  return {
15486
17141
  summary: edits.length ? `Moved vite-hub options in ${edits.length} config file${edits.length === 1 ? "" : "s"}.` : "Found nothing to move automatically.",
15487
17142
  edits,
@@ -15495,10 +17150,9 @@ const vitehubOptions = {
15495
17150
  description: "Renames preset to host, moves observability.logs to logs and Env declarations into vitehub({ env }), and removes devtools and contentImportBase",
15496
17151
  usage: "[dir]",
15497
17152
  async detect({ cwd }) {
15498
- for (const file of await configFiles(cwd)) {
15499
- const result = migrateViteHubOptions(file, await readFile(join(cwd, file), "utf8"));
15500
- if (result.changed || result.followUps.length) return { reason: `${file} uses vite-hub options that moved` };
15501
- }
17153
+ const { results, followUps } = await migrations(cwd);
17154
+ for (const { file, result } of results) if (result.changed || result.followUps.length) return { reason: `${file} uses vite-hub options that moved` };
17155
+ return followUps[0] ? { reason: `${followUps[0].file} passes vite-hub options that need manual review` } : void 0;
15502
17156
  },
15503
17157
  run: migrate$1
15504
17158
  };
@@ -15672,7 +17326,10 @@ const codemods = [
15672
17326
  cliUrlFlag,
15673
17327
  cliYesFlag,
15674
17328
  cmsRoles,
15675
- choicesPackage
17329
+ choicesPackage,
17330
+ cliGetList,
17331
+ cliAgentTree,
17332
+ nuxtServerImports
15676
17333
  ];
15677
17334
  /**
15678
17335
  * Codemods that move an app between ViteHub releases. `vitehub migrate` runs each one that applies, in this order, and
@@ -15680,7 +17337,8 @@ const codemods = [
15680
17337
  * keys into `vitehub()`, where `agent-surface` then renames the Agent driver keys. `define-forms` moves the Database
15681
17338
  * files before the import codemods rewrite them. `root-accessors` moves `#vitehub/env/server` to `vite-hub/env` before
15682
17339
  * `one-entry-imports` joins the `vite-hub/env/*` imports with it. `queue-durations` and `result-tuples` run after
15683
- * `queue-workflow-verbs`, so they also read the calls that `queue-workflow-verbs` renamed. The codemods that move an
17340
+ * `queue-workflow-verbs`, so they also read the calls that `queue-workflow-verbs` renamed. `nuxt-server-imports` runs
17341
+ * last and detects again after the others, so it imports the helpers under their new names. The codemods that move an
15684
17342
  * app from another module, such as NuxtHub, are not upgrades, so only `npx @vite-hub/codemods` runs them.
15685
17343
  */
15686
17344
  const upgradeCodemods = [
@@ -15706,7 +17364,10 @@ const upgradeCodemods = [
15706
17364
  cliUrlFlag,
15707
17365
  cliYesFlag,
15708
17366
  cmsRoles,
15709
- choicesPackage
17367
+ choicesPackage,
17368
+ cliGetList,
17369
+ cliAgentTree,
17370
+ nuxtServerImports
15710
17371
  ];
15711
17372
  //#endregion
15712
17373
  //#region src/runner.ts