@vite-hub/cli 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,10 +1,12 @@
1
- import { $ as readProvisionStateSync, At as viteCliProjectConfig, B as readConsoleCredential, Ct as quoteSupportedInstallSpecifier, Dt as createCliDiscoveryNitroCloser, Et as collectViteHubCliContribution, Mt as isRecord, Ot as findViteHubDevServerUrl, Tt as appUrlError, X as PROVISION_STATE_FILE, Y as cliErrorDiagnostics, at as collectOperationContributions, ct as operationCliOptions, dt as parseOperationInput, ft as operationInputJsonSchema, ht as resolveViteHubProjectRoot, jt as withStdoutOnStderr, kt as getStableStdoutWrite, lt as operationCliPath, mt as setupCommandNames, nt as withViteStageEnvironment, ot as createOperationRegistry, pt as reservedOperationNamespaces, rt as callOperation, st as operationCall, t as createProvisionNamespace, tt as loadAllEnv, ut as operationsOf, v as consoleClient } from "./provision-YzxNsbhs.js";
1
+ import { A as getStableStdoutWrite, C as setupCommandNames, D as createCliDiscoveryNitroCloser, E as collectViteHubCliContribution, M as rethrowCliViteImportError, N as viteCliProjectConfig, O as createNuxtConfigImport, P as withStdoutOnStderr, S as reservedOperationNamespaces, T as appUrlError, _ as operationCliOptions, b as parseOperationInput, f as callOperation, g as operationCall, h as createOperationRegistry, j as isCliViteMissing, k as findViteHubDevServerUrl, m as collectOperationContributions, s as PROVISION_STATE_FILE, t as createProvisionNamespace, u as readProvisionStateSync, v as operationCliPath, w as resolveViteHubProjectRoot, x as operationInputJsonSchema, y as operationsOf } from "./provision-Fiosv3Un.js";
2
+ import { S as quoteSupportedInstallSpecifier, T as isRecordOrFunction, d as cliErrorDiagnostics, f as loadAllEnv, p as withViteStageEnvironment, w as isRecord } from "./provision-9QsGgeiq.js";
2
3
  import { spawn } from "node:child_process";
3
4
  import { existsSync, readFileSync, statSync } from "node:fs";
4
5
  import process$1 from "node:process";
6
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
7
  import { basename, dirname, relative, resolve } from "pathe";
8
+ import { isAbsolute, resolve as resolve$1 } from "node:path";
6
9
  import { createInterface } from "node:readline/promises";
7
- import { formatRuntimeDiagnosticError } from "@vite-hub/runtime";
8
10
  // ../internal/dist/inspect.js
9
11
  async function collectContributors(plugins) {
10
12
  const contributors = [];
@@ -573,23 +575,94 @@ async function flattenPluginOptions(plugins) {
573
575
  await flattenPlugins(plugins ?? [], flattened, /* @__PURE__ */ new Set());
574
576
  return flattened;
575
577
  }
578
+ // ../internal/dist/operations-vite.js
579
+ /**
580
+ * Reads the operations of each contribution. Without `resolution`, Node imports each module. With it, Vite loads
581
+ * TypeScript source with the resolution of the app, so imports without an extension, aliases, and tsconfig paths work.
582
+ * Node imports the other modules, such as CommonJS or a built package, and Vite loads those that Node cannot.
583
+ */
584
+ async function loadOperationContributions(contributions, resolution) {
585
+ const modules = await importOperationModules([...new Set(contributions.filter((contribution) => !contribution.load).map((contribution) => contribution.module))], resolution);
586
+ return await Promise.allSettled(contributions.map(async (contribution) => {
587
+ if (contribution.load) return operationsOf(await contribution.load());
588
+ const loaded = modules.get(contribution.module);
589
+ if (loaded?.status === "rejected") throw loaded.reason;
590
+ return operationsOf(Reflect.get(Object(loaded?.value), contribution.export));
591
+ }));
592
+ }
593
+ async function importOperationModules(modules, resolution) {
594
+ const source = resolution ? modules.filter((module) => /\.(?:cts|mts|ts|tsx)$/.test(module)) : [];
595
+ const loaded = /* @__PURE__ */ new Map();
596
+ for (const module of modules.filter((module) => !source.includes(module))) {
597
+ const [result] = await Promise.allSettled([isAbsolute(module) ? import(pathToFileURL(module).href) : import(module)]);
598
+ loaded.set(module, result);
599
+ }
600
+ if (!resolution) return loaded;
601
+ const retried = [...source, ...modules.filter((module) => loaded.get(module)?.status === "rejected" && !module.endsWith(".cjs"))];
602
+ if (retried.length) for (const [module, result] of await importWithVite(retried, resolution)) loaded.set(module, result);
603
+ return loaded;
604
+ }
605
+ async function importWithVite(modules, resolution) {
606
+ const entry = resolve$1(resolution.root, ".vitehub/operations/modules.mjs");
607
+ const code = `export default await Promise.allSettled([${modules.map((module) => `import(${JSON.stringify(module)})`).join(", ")}])`;
608
+ const { runnerImport } = await import("vite");
609
+ try {
610
+ const { dependencies, module } = await runnerImport(entry, {
611
+ configFile: false,
612
+ logLevel: "silent",
613
+ plugins: [{
614
+ name: "vitehub:operation-modules",
615
+ load: (id) => id === entry ? code : void 0,
616
+ resolveId: (id) => id === entry ? entry : void 0
617
+ }],
618
+ resolve: {
619
+ alias: resolution.alias,
620
+ tsconfigPaths: resolution.tsconfigPaths
621
+ },
622
+ root: resolution.root
623
+ });
624
+ resolution.onViteDependencies?.(dependencies);
625
+ return new Map(modules.map((name, index) => [name, module.default[index]]));
626
+ } catch (reason) {
627
+ return new Map(modules.map((name) => [name, {
628
+ reason,
629
+ status: "rejected"
630
+ }]));
631
+ }
632
+ }
576
633
  // src/operations.ts
577
- /** Reads every contributed operation of the resolved plugins. A module that fails to load is reported on stderr. */
578
- async function loadCliOperations(plugins, stderr) {
634
+ /**
635
+ * Reads every contributed operation of the resolved plugins. Node imports each module first. When Node cannot load it,
636
+ * Vite loads it with the resolution of the app, so relative imports without an extension, the aliases, and the tsconfig
637
+ * paths of the Vite config work. A module that fails to load is reported on stderr.
638
+ */
639
+ async function loadCliOperations(plugins, resolution, stderr) {
640
+ const contributions = await collectOperationContributions(await flattenPluginOptions(plugins));
641
+ const loaded = await loadOperationContributions(contributions, resolution);
579
642
  const sources = [];
580
- for (const contribution of await collectOperationContributions(await flattenPluginOptions(plugins))) try {
581
- const exported = contribution.load ? await contribution.load() : Reflect.get(Object(await import(
582
- /* @vite-ignore */
583
- contribution.module
584
- )), contribution.export);
585
- sources.push({
586
- operations: operationsOf(exported),
587
- plugin: contribution.plugin
588
- });
589
- } catch (error) {
590
- stderr.write(`Could not load the operations of ${contribution.plugin} from ${contribution.module}: ${error instanceof Error ? error.message : String(error)}\n`);
643
+ let complete = true;
644
+ for (const [index, contribution] of contributions.entries()) {
645
+ const result = loaded[index];
646
+ if (result.status === "fulfilled") {
647
+ sources.push({
648
+ operations: result.value,
649
+ plugin: contribution.plugin
650
+ });
651
+ continue;
652
+ }
653
+ complete = false;
654
+ const reason = result.reason instanceof Error ? result.reason.message : String(result.reason);
655
+ stderr.write(`${(await import("@vite-hub/runtime")).formatRuntimeDiagnosticError(cliErrorDiagnostics.CLI_OPERATIONS_LOAD_FAILED({
656
+ export: contribution.export,
657
+ module: contribution.module,
658
+ plugin: contribution.plugin,
659
+ reason
660
+ }))}\n`);
591
661
  }
592
- return createOperationRegistry(sources).list();
662
+ return {
663
+ complete,
664
+ operations: createOperationRegistry(sources).list()
665
+ };
593
666
  }
594
667
  function kebab(key) {
595
668
  return key.replace(/[A-Z]/g, (letter) => `-${letter.toLowerCase()}`);
@@ -597,9 +670,6 @@ function kebab(key) {
597
670
  function camel(flag) {
598
671
  return flag.replace(/-([a-z])/g, (_match, letter) => letter.toUpperCase());
599
672
  }
600
- function isObject(value) {
601
- return value !== null && Object(value) === value && !Array.isArray(value);
602
- }
603
673
  const scalarTypes = /* @__PURE__ */ new Set([
604
674
  "boolean",
605
675
  "integer",
@@ -607,7 +677,7 @@ const scalarTypes = /* @__PURE__ */ new Set([
607
677
  "string"
608
678
  ]);
609
679
  function readType(schema) {
610
- if (!isObject(schema)) return {
680
+ if (!isRecordOrFunction(schema)) return {
611
681
  alternatives: [],
612
682
  nullable: false,
613
683
  type: "json"
@@ -615,8 +685,8 @@ function readType(schema) {
615
685
  const options = Array.isArray(schema.anyOf) ? schema.anyOf : Array.isArray(schema.oneOf) ? schema.oneOf : void 0;
616
686
  if (options) {
617
687
  const parts = options.map(readType);
618
- const nulls = options.filter((option) => isObject(option) && option.type === "null").length;
619
- const present = parts.filter((_part, index) => !(isObject(options[index]) && options[index].type === "null"));
688
+ const nulls = options.filter((option) => isRecordOrFunction(option) && option.type === "null").length;
689
+ const present = parts.filter((_part, index) => !(isRecordOrFunction(options[index]) && options[index].type === "null"));
620
690
  const nullable = nulls > 0 || parts.some((part) => part.nullable);
621
691
  if (present.length === 1) return {
622
692
  ...present[0],
@@ -686,9 +756,9 @@ function readType(schema) {
686
756
  }
687
757
  function flagsOf(operation) {
688
758
  const schema = operationInputJsonSchema(operation);
689
- const shapes = (Array.isArray(schema.anyOf) ? schema.anyOf : [schema]).filter(isObject);
690
- return [...new Map(shapes.flatMap((shape) => isObject(shape.properties) ? Object.entries(shape.properties) : []))].map(([key, property]) => {
691
- const description = isObject(property) ? property.description : void 0;
759
+ const shapes = (Array.isArray(schema.anyOf) ? schema.anyOf : [schema]).filter(isRecordOrFunction);
760
+ return [...new Map(shapes.flatMap((shape) => isRecordOrFunction(shape.properties) ? Object.entries(shape.properties) : []))].map(([key, property]) => {
761
+ const description = isRecordOrFunction(property) ? property.description : void 0;
692
762
  const required = shapes.every((shape) => Array.isArray(shape.required) && shape.required.includes(key));
693
763
  return {
694
764
  ...readType(property),
@@ -795,9 +865,18 @@ function readWholeInput(raw, cwd) {
795
865
  throw usageError(`--input could not read ${raw.slice(1)}: ${error instanceof Error ? error.message : String(error)}`);
796
866
  }
797
867
  const value = parseJson(text, "input");
798
- if (!isObject(value)) throw usageError("--input must be a JSON object.");
868
+ if (!isRecordOrFunction(value)) throw usageError("--input must be a JSON object.");
799
869
  return value;
800
870
  }
871
+ function positionalKeysSkippingLeadingOptionals(positional, flags, named, count) {
872
+ const keys = [];
873
+ for (const [index, key] of positional.entries()) {
874
+ const requiredAfter = positional.slice(index + 1).filter((next) => !named.has(next) && flags.find((flag) => flag.key === next)?.required !== false).length;
875
+ if (flags.find((flag) => flag.key === key)?.required === false && count - keys.length <= requiredAfter) continue;
876
+ keys.push(key);
877
+ }
878
+ return keys;
879
+ }
801
880
  function parseCall(operation, flags, args, cwd) {
802
881
  const parsed = {
803
882
  help: false,
@@ -805,17 +884,15 @@ function parseCall(operation, flags, args, cwd) {
805
884
  json: false,
806
885
  yes: false
807
886
  };
808
- const positional = [...operationCliOptions(operation)?.positional ?? []];
887
+ const positional = operationCliOptions(operation)?.positional ?? [];
888
+ const assignments = [];
889
+ const named = /* @__PURE__ */ new Set();
809
890
  const { command, namespace } = operationCliPath(operation);
810
891
  let whole = {};
811
892
  for (let index = 0; index < args.length; index++) {
812
893
  const arg = args[index];
813
894
  if (arg === "--") {
814
- for (const rest of args.slice(index + 1)) {
815
- const key = positional.shift();
816
- if (!key) throw usageError(`Unexpected argument ${JSON.stringify(rest)}.`);
817
- assign(parsed.input, flags.find((flag) => flag.key === key), key, kebab(key), rest);
818
- }
895
+ assignments.push(...args.slice(index + 1));
819
896
  break;
820
897
  }
821
898
  if (arg === "-h" || arg === "--help") parsed.help = true;
@@ -843,17 +920,28 @@ function parseCall(operation, flags, args, cwd) {
843
920
  const key = camel(negated ? name.slice(3) : name);
844
921
  const flag = flags.find((entry) => entry.key === key);
845
922
  if (!flag) throw usageError(`Unknown option --${name}. Run \`vitehub ${namespace} ${command} --help\` for the input.`);
923
+ named.add(key);
846
924
  if (flag.type === "boolean") {
847
925
  const next = args[index + 1];
848
926
  const value = inline !== void 0 ? convertScalar("boolean", name, inline) : !negated && (next === "true" || next === "false") ? (index++, next === "true") : true;
849
- parsed.input[key] = negated ? false : value;
850
- } else assign(parsed.input, flag, key, name, take());
927
+ assignments.push(() => {
928
+ parsed.input[key] = negated ? false : value;
929
+ });
930
+ } else {
931
+ const raw = take();
932
+ assignments.push(() => assign(parsed.input, flag, key, name, raw));
933
+ }
851
934
  }
852
- } else {
853
- const key = positional.shift();
854
- if (!key) throw usageError(`Unexpected argument ${JSON.stringify(arg)}.`);
855
- assign(parsed.input, flags.find((flag) => flag.key === key), key, kebab(key), arg);
856
- }
935
+ } else assignments.push(arg);
936
+ }
937
+ for (const key of Object.keys(whole)) named.add(key);
938
+ const keys = positionalKeysSkippingLeadingOptionals(positional, flags, named, assignments.filter((value) => typeof value === "string").length);
939
+ let position = 0;
940
+ for (const assignment of assignments) if (typeof assignment !== "string") assignment();
941
+ else {
942
+ const key = keys[position++];
943
+ if (key === void 0) throw usageError(`Unexpected argument ${JSON.stringify(assignment)}.`);
944
+ assign(parsed.input, flags.find((flag) => flag.key === key), key, kebab(key), assignment);
857
945
  }
858
946
  parsed.input = {
859
947
  ...whole,
@@ -905,13 +993,15 @@ async function confirm(operation, target) {
905
993
  function acceptedRoots(rootDir) {
906
994
  return [.../* @__PURE__ */ new Set([rootDir, resolveViteHubProjectRoot(rootDir)])];
907
995
  }
996
+ /** The Console route for a call on `url` after `vitehub login`, or nothing when the CLI calls the app directly. Never throws. */
908
997
  async function throughConsole(url, context, signal) {
909
998
  if (Object.keys(context.env).some((name) => name.startsWith("VITEHUB_CONSOLE_PRIVATE_KEY_") && context.env[name])) return;
910
999
  const warnDiscoveryFailed = () => {
911
1000
  context.stderr.write("Warning: Console discovery failed. The CLI will call the app directly if time remains.\n");
912
1001
  };
913
1002
  try {
914
- const credential = await readConsoleCredential(context.env, void 0, signal);
1003
+ const [{ selectConsole }, { consoleClient }] = await Promise.all([import("./console-auth-cCodgT_T.js").then((n) => n.a), import("./console-apps-BQX-Np9Q.js").then((n) => n.o)]);
1004
+ const { credential } = await selectConsole(context, void 0, signal);
915
1005
  if (!credential) return;
916
1006
  const { body } = await consoleClient(context, credential, signal).request("/api/projects");
917
1007
  signal.throwIfAborted();
@@ -1393,13 +1483,14 @@ function createSeedNamespace(seeds) {
1393
1483
  const BUILTIN_NAMESPACE_NAMES = new Set(reservedOperationNamespaces);
1394
1484
  const ROOT_HELP_WITHOUT_CONFIG = "[vitehub] The project config did not load. Project namespaces are missing. Of the commands below, only `deploy`, `provision run`, and `provision status` load the config. Fix the error above to use those three commands and the project namespaces.";
1395
1485
  const ENV_HELP_WITHOUT_CONFIG = "[vitehub] The project config did not load. The list below shows only the env commands that do not load the config. Fix the error above to see the project env commands.";
1486
+ const HELP_WITHOUT_VITE = "[vitehub] Vite is not installed here, so the list below shows only the commands that need no project. Run vitehub in a Vite or Nuxt app with its dependencies installed to see the project commands.";
1396
1487
  const hostEnvFeatures = {
1397
1488
  description: "Compare, push, and pull the env names of the app on a host.",
1398
1489
  features: [
1399
1490
  {
1400
1491
  description: "Compare the env names of the last build with the names on the linked host. Exits with 1 when a required name is missing. Never reads values.",
1401
1492
  name: "diff",
1402
- run: async (args, context) => await (await import("./env-DzYHxq9A.js").then((n) => n.n)).runEnvCommand({
1493
+ run: async (args, context) => await (await import("./env-D_CN5DyX.js").then((n) => n.n)).runEnvCommand({
1403
1494
  ...hostEnvFeatures.features[0],
1404
1495
  name: "diff"
1405
1496
  }, args, context),
@@ -1408,7 +1499,7 @@ const hostEnvFeatures = {
1408
1499
  {
1409
1500
  description: "Set the host variables of the build's env names from the shell and .env.<stage>, with the host CLI. Prints names, never values. Never deletes a host variable.",
1410
1501
  name: "push",
1411
- run: async (args, context) => await (await import("./env-DzYHxq9A.js").then((n) => n.n)).runEnvCommand({
1502
+ run: async (args, context) => await (await import("./env-D_CN5DyX.js").then((n) => n.n)).runEnvCommand({
1412
1503
  ...hostEnvFeatures.features[1],
1413
1504
  name: "push"
1414
1505
  }, args, context),
@@ -1417,14 +1508,14 @@ const hostEnvFeatures = {
1417
1508
  {
1418
1509
  description: "Write the env values of a stage from a self-hosted Console to .env.<stage>. Needs `vitehub login` and the owner or admin role.",
1419
1510
  name: "pull",
1420
- run: async (args, context) => await (await import("./console-env-lQ3_eMOy.js")).envPullFeature.run(args, context),
1511
+ run: async (args, context) => await (await import("./console-env-eXdVI6kw.js").then((n) => n.t)).envPullFeature.run(args, context),
1421
1512
  usage: "vitehub env pull --from console [--stage <name>] [--project <id>] [--console <url>] [--yes] [--json]"
1422
1513
  }
1423
1514
  ],
1424
1515
  name: "env"
1425
1516
  };
1426
1517
  async function loadSetupCommands() {
1427
- return (await import("./commands-FOmqEZUi.js").then((n) => n.t)).setupCommands;
1518
+ return (await import("./commands-w7tEEJph.js").then((n) => n.t)).setupCommands;
1428
1519
  }
1429
1520
  async function loadNuxtViteConfig(rootDir, command, mode) {
1430
1521
  if (![
@@ -1442,9 +1533,11 @@ async function loadNuxtViteConfig(rootDir, command, mode) {
1442
1533
  } catch {
1443
1534
  throw cliErrorDiagnostics.CLI_R0001({ message: "[vitehub] Nuxt config was found, but Nuxt could not be loaded for CLI discovery." });
1444
1535
  }
1536
+ const importConfig = await createNuxtConfigImport(rootDir, fileURLToPath(import.meta.resolve("nuxt/kit")));
1445
1537
  const options = {
1446
1538
  cwd: rootDir,
1447
1539
  dev: command === "serve",
1540
+ ...importConfig ? { import: importConfig.import } : {},
1448
1541
  envName: mode ?? (command === "build" ? "production" : "development"),
1449
1542
  overrides: {
1450
1543
  devtools: { enabled: false },
@@ -1480,6 +1573,7 @@ async function loadNuxtViteConfig(rootDir, command, mode) {
1480
1573
  vitehubCliDiscovery: true
1481
1574
  }, command, mode ?? (command === "build" ? "production" : "development"));
1482
1575
  return {
1576
+ inputs: [...nuxt.options._layers.map((layer) => layer.config.rootDir), ...importConfig?.files ?? []],
1483
1577
  nitro: { handlers: [...resolveRouteHandlers({
1484
1578
  ...Object(Reflect.get(config, "nitro")),
1485
1579
  alias: {
@@ -1496,6 +1590,7 @@ async function loadNuxtViteConfig(rootDir, command, mode) {
1496
1590
  handlers: [...nitroHandlers(nuxt.options.nitro), ...nuxt.options.serverHandlers]
1497
1591
  }, nuxt.options.rootDir || rootDir)] },
1498
1592
  plugins: config.plugins,
1593
+ resolve: config.resolve,
1499
1594
  root: config.root
1500
1595
  };
1501
1596
  } finally {
@@ -1549,18 +1644,26 @@ function defaultSpawn(command, args, options = {}) {
1549
1644
  ]
1550
1645
  });
1551
1646
  const stdout = [];
1552
- child.stdout?.on("data", (chunk) => stdout.push(chunk));
1553
- child.stderr?.resume();
1647
+ const stderr = [];
1648
+ const onOutput = options.onOutput;
1649
+ if (onOutput) {
1650
+ child.stdout?.setEncoding("utf8").on("data", (text) => onOutput(text, "stdout"));
1651
+ child.stderr?.setEncoding("utf8").on("data", (text) => onOutput(text, "stderr"));
1652
+ } else {
1653
+ child.stdout?.on("data", (chunk) => stdout.push(chunk));
1654
+ child.stderr?.on("data", (chunk) => stderr.push(chunk));
1655
+ }
1554
1656
  child.on("error", reject);
1555
1657
  child.on("close", (exitCode, signal) => resolveResult({
1556
1658
  exitCode,
1557
1659
  signal,
1558
- ...child.stdout ? { stdout: Buffer.concat(stdout).toString("utf8") } : {}
1660
+ ...child.stdout && !onOutput ? { stdout: Buffer.concat(stdout).toString("utf8") } : {},
1661
+ ...child.stderr && !onOutput ? { stderr: Buffer.concat(stderr).toString("utf8") } : {}
1559
1662
  }));
1560
1663
  });
1561
1664
  }
1562
1665
  async function loadViteConfig(rootDir, command, mode) {
1563
- const { resolveConfig } = await import("vite");
1666
+ const { resolveConfig } = await import("vite").catch((error) => rethrowCliViteImportError(error, import.meta.filename));
1564
1667
  const resolvedMode = mode ?? (command === "build" ? "production" : "development");
1565
1668
  const project = viteCliProjectConfig(rootDir);
1566
1669
  const nitro = createCliDiscoveryNitroCloser();
@@ -1571,7 +1674,11 @@ async function loadViteConfig(rootDir, command, mode) {
1571
1674
  vitehubCliDiscovery: true
1572
1675
  };
1573
1676
  try {
1574
- return await resolveConfig(inlineConfig, command, resolvedMode);
1677
+ const config = await resolveConfig(inlineConfig, command, resolvedMode);
1678
+ return {
1679
+ ...config,
1680
+ inputs: config.configFileDependencies
1681
+ };
1575
1682
  } finally {
1576
1683
  await nitro.close();
1577
1684
  }
@@ -1613,6 +1720,12 @@ function isRootHelp(args) {
1613
1720
  function isHelpFlag(arg) {
1614
1721
  return arg === "-h" || arg === "--help";
1615
1722
  }
1723
+ function isDiscoveryHelp(args) {
1724
+ const [namespace, feature, option] = args;
1725
+ if (!namespace || isRootHelp(args)) return true;
1726
+ if (namespace.startsWith("-")) return false;
1727
+ return isHelpFlag(feature) || feature !== void 0 && !feature.startsWith("-") && isHelpFlag(option);
1728
+ }
1616
1729
  async function loadHelpNamespace(args, helpNamespaces) {
1617
1730
  const [name, feature, ...rest] = args;
1618
1731
  if (!name || !helpNamespaces || !Object.hasOwn(helpNamespaces, name) || BUILTIN_NAMESPACE_NAMES.has(name)) return;
@@ -1655,18 +1768,31 @@ async function runViteHubCli(options = {}) {
1655
1768
  }
1656
1769
  const spawn = options.spawn || defaultSpawn;
1657
1770
  const stage = args[0] === "channels" && (args[1] === "sync" || args[1] === "history") || args[0] === "seed" ? readStageArg(args) : void 0;
1658
- const loadProject = (command) => withStdoutOnStderr(async () => {
1771
+ const loadProject = (command, recordHelpInputs = false) => withStdoutOnStderr(async () => {
1659
1772
  const loadConfig = options.loadConfig || loadViteConfig;
1660
1773
  const loadNuxtConfig = options.loadNuxtViteConfig || loadNuxtViteConfig;
1661
1774
  const config = await (stage ? loadConfig(cwd, command, stage) : loadConfig(cwd, command));
1662
1775
  const nuxtConfig = config.vitehubConfigResolved ? void 0 : await (stage ? loadNuxtConfig(cwd, command, stage) : loadNuxtConfig(cwd, command));
1663
1776
  const plugins = nuxtConfig?.plugins ?? config.plugins;
1777
+ const rootDir = resolve(nuxtConfig?.root || config.root || cwd);
1778
+ const { alias, tsconfigPaths } = (nuxtConfig ?? config).resolve ?? {};
1779
+ const inputs = [
1780
+ ...config.inputs ?? [],
1781
+ ...nuxtConfig?.inputs ?? [],
1782
+ rootDir
1783
+ ];
1664
1784
  return {
1785
+ inputs,
1665
1786
  contribution: await collectViteHubCliContribution(plugins),
1666
1787
  handlers: resolveRouteHandlers(nuxtConfig ? nuxtConfig.nitro : config.nitro, nuxtConfig?.root || config.root || cwd),
1667
- operations: await loadCliOperations(plugins, stderr),
1788
+ discovery: await loadCliOperations(plugins, {
1789
+ alias,
1790
+ ...recordHelpInputs ? { onViteDependencies: (files) => inputs.push(...files) } : {},
1791
+ root: rootDir,
1792
+ tsconfigPaths
1793
+ }, stderr),
1668
1794
  plugins,
1669
- rootDir: resolve(nuxtConfig?.root || config.root || cwd)
1795
+ rootDir
1670
1796
  };
1671
1797
  }, stderr);
1672
1798
  const loadProvision = options.loadProvision ?? (async (host) => {
@@ -1674,7 +1800,8 @@ async function runViteHubCli(options = {}) {
1674
1800
  return await withViteStageEnvironment({
1675
1801
  ...discoveryEnv,
1676
1802
  VITEHUB_HOST: host,
1677
- VITEHUB_HOST_SOURCE: "cli"
1803
+ VITEHUB_HOST_SOURCE: "cli",
1804
+ VITEHUB_LINK_ROOT: resolve(cwd)
1678
1805
  }, async () => {
1679
1806
  const loaded = await loadProject("build");
1680
1807
  return {
@@ -1713,7 +1840,14 @@ async function runViteHubCli(options = {}) {
1713
1840
  stdout
1714
1841
  });
1715
1842
  const runtimeNamespace = options.runtimeNamespaces?.find((namespace) => namespace.name === args[0] && !BUILTIN_NAMESPACE_NAMES.has(namespace.name));
1843
+ const consoleRoute = async (url, signal) => await throughConsole(url, {
1844
+ cwd,
1845
+ env,
1846
+ ...options.fetch ? { fetch: options.fetch } : {},
1847
+ stderr
1848
+ }, signal);
1716
1849
  if (runtimeNamespace) return await runNamespace(runtimeNamespace, args, {
1850
+ consoleRoute,
1717
1851
  cwd,
1718
1852
  env,
1719
1853
  rootDir: cwd,
@@ -1723,6 +1857,7 @@ async function runViteHubCli(options = {}) {
1723
1857
  });
1724
1858
  const runtimeFeatures = [...options.runtimeFeatures ?? [], hostEnvFeatures].find((namespace) => !BUILTIN_NAMESPACE_NAMES.has(namespace.name) && namespace.name === args[0] && namespace.features.some((feature) => feature.name === args[1]));
1725
1859
  if (runtimeFeatures && (await options.runtimeFeatureGuard?.(args[0], args[1], cwd) ?? true)) return await runNamespace(runtimeFeatures, args, {
1860
+ consoleRoute,
1726
1861
  cwd,
1727
1862
  env,
1728
1863
  ...options.fetch ? { fetch: options.fetch } : {},
@@ -1741,29 +1876,39 @@ async function runViteHubCli(options = {}) {
1741
1876
  stderr,
1742
1877
  stdout
1743
1878
  });
1879
+ const helpCache = options.helpCache && !stage && (!args.length || isRootHelp(args) || args.length === 2 && isHelpFlag(args[1])) ? await import("./help-cache-BI6y5pN8.js") : void 0;
1880
+ const cached = helpCache?.readHelpCache(cwd, env);
1881
+ if (cached && args.length < 2) {
1882
+ writeRootHelp(cached.namespaces, cached.commands, stdout);
1883
+ return 0;
1884
+ }
1885
+ const cachedNamespace = cached?.namespaces.find((namespace) => namespace.name === args[0]);
1886
+ if (cachedNamespace && !(cachedNamespace.defaultFeature === cachedNamespace.name && cachedNamespace.features.length === 1)) {
1887
+ writeNamespaceHelp(cachedNamespace, stdout);
1888
+ return 0;
1889
+ }
1890
+ const helpRecording = cached ? void 0 : helpCache?.recordHelpCache(cwd, env);
1744
1891
  const command = args[0] === "inspect" && (args[1] === "output" || args[1] === "resources" || args[1] === "routes") ? "build" : "serve";
1745
1892
  const runtimeNamespaces = (options.runtimeNamespaces ?? []).filter((namespace) => !BUILTIN_NAMESPACE_NAMES.has(namespace.name));
1746
1893
  let project;
1747
1894
  try {
1748
- project = await (stage ? withViteStageEnvironment(env, () => loadProject(command)) : loadProject(command));
1895
+ project = await (stage ? withViteStageEnvironment(env, () => loadProject(command)) : loadProject(command, !!helpRecording));
1749
1896
  } catch (error) {
1897
+ helpRecording?.stop();
1750
1898
  const envHelp = args[0] === hostEnvFeatures.name && isHelpFlag(args[1]);
1751
- if (args.length && !isRootHelp(args) && !envHelp) throw error;
1752
- stderr.write(`${formatRuntimeDiagnosticError(error)}\n`);
1753
- if (envHelp) {
1754
- stderr.write(`${ENV_HELP_WITHOUT_CONFIG}\n\n`);
1755
- writeNamespaceHelp(hostEnvFeatures, stdout);
1756
- return 1;
1757
- }
1758
- stderr.write(`${ROOT_HELP_WITHOUT_CONFIG}\n\n`);
1759
- writeRootHelp([
1899
+ const helpWithoutVite = isCliViteMissing(error) && isDiscoveryHelp(args);
1900
+ if (!helpWithoutVite && args.length && !isRootHelp(args) && !envHelp) throw error;
1901
+ stderr.write(helpWithoutVite ? `${HELP_WITHOUT_VITE}\n\n` : `${(await import("@vite-hub/runtime")).formatRuntimeDiagnosticError(error)}\n${envHelp ? ENV_HELP_WITHOUT_CONFIG : ROOT_HELP_WITHOUT_CONFIG}\n\n`);
1902
+ if (envHelp) writeNamespaceHelp(hostEnvFeatures, stdout);
1903
+ else writeRootHelp([
1760
1904
  provisionNamespace,
1761
1905
  ...runtimeNamespaces,
1762
1906
  hostEnvFeatures
1763
1907
  ], await loadCommands(), stdout);
1764
- return 1;
1908
+ return helpWithoutVite ? 0 : 1;
1765
1909
  }
1766
- const { contribution, handlers, operations, plugins, rootDir } = project;
1910
+ const { contribution, discovery: { complete, operations }, handlers, inputs, plugins, rootDir } = project;
1911
+ if (!complete) helpRecording?.stop();
1767
1912
  const runtimeNames = new Set(runtimeNamespaces.map((namespace) => namespace.name));
1768
1913
  const namespaces = [
1769
1914
  ...mergeOperationNamespaces(contribution.namespaces, createOperationNamespaces(operations)).filter((namespace) => !BUILTIN_NAMESPACE_NAMES.has(namespace.name) && !runtimeNames.has(namespace.name)),
@@ -1780,6 +1925,7 @@ async function runViteHubCli(options = {}) {
1780
1925
  };
1781
1926
  else namespaces.push(hostEnvFeatures);
1782
1927
  const context = {
1928
+ consoleRoute,
1783
1929
  cwd,
1784
1930
  env,
1785
1931
  ...options.fetch ? { fetch: options.fetch } : {},
@@ -1790,6 +1936,10 @@ async function runViteHubCli(options = {}) {
1790
1936
  stderr,
1791
1937
  stdout
1792
1938
  };
1939
+ if (complete) helpRecording?.write(namespaces, (await loadCommands()).map(({ description, name }) => ({
1940
+ description,
1941
+ name
1942
+ })), inputs);
1793
1943
  if (!args.length || isRootHelp(args)) {
1794
1944
  writeRootHelp(namespaces, await loadCommands(), stdout);
1795
1945
  return 0;
@@ -1877,13 +2027,14 @@ function runViteHubCliEntrypoint(options = {}) {
1877
2027
  let exitCode;
1878
2028
  try {
1879
2029
  exitCode = await runViteHubCli({
2030
+ helpCache: true,
1880
2031
  ...options,
1881
2032
  stderr: stderr.stream,
1882
2033
  stdout: stdout.stream
1883
2034
  });
1884
2035
  } catch (error) {
1885
2036
  try {
1886
- stderr.stream.write(`${formatRuntimeDiagnosticError(error)}\n`);
2037
+ stderr.stream.write(`${(await import("@vite-hub/runtime")).formatRuntimeDiagnosticError(error)}\n`);
1887
2038
  } catch {}
1888
2039
  exitCode = 1;
1889
2040
  }