@vite-hub/cli 0.6.1 → 0.7.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.d.ts CHANGED
@@ -1,17 +1,4 @@
1
- import { a as ProvisionProvider, c as HostCliRun, i as ViteHubCliProvision, n as ViteHubCliCommandNamespace, t as ViteHubCliCommand } from "./provision-kiD8Emd7.js";
2
- interface ViteHubCliSpawnResult {
3
- exitCode: number | null;
4
- signal?: NodeJS.Signals | null;
5
- stdout?: string;
6
- }
7
- interface ViteHubCliSpawnOptions {
8
- cwd?: string;
9
- env?: NodeJS.ProcessEnv;
10
- stderr?: "inherit" | "pipe";
11
- stdin?: "ignore" | "inherit";
12
- stdout?: "inherit" | "pipe" | "stderr";
13
- }
14
- type ViteHubCliSpawn = (command: string, args: string[], options?: ViteHubCliSpawnOptions) => Promise<ViteHubCliSpawnResult>;
1
+ import { a as ViteHubCliSpawn, i as ViteHubCliProvision, l as HostCliRun, n as ViteHubCliCommandNamespace, o as ProvisionProvider, t as ViteHubCliCommand } from "./provision-ByxmUa19.js";
15
2
  interface ViteHubCliStreams {
16
3
  stderr: ViteHubCliStream;
17
4
  stdout: ViteHubCliStream;
@@ -27,9 +14,17 @@ type ViteHubCliEntrypointStream = {
27
14
  flush?: never;
28
15
  write: (chunk: string | Uint8Array) => void | PromiseLike<unknown>;
29
16
  };
17
+ interface OperationResolveConfig {
18
+ alias?: Readonly<Record<string, string>> | readonly {
19
+ find: string | RegExp;
20
+ replacement: string;
21
+ }[];
22
+ tsconfigPaths?: boolean;
23
+ }
30
24
  interface ViteHubCliLoadedConfig {
31
25
  nitro?: unknown;
32
26
  plugins: readonly unknown[];
27
+ resolve?: OperationResolveConfig;
33
28
  root: string;
34
29
  vitehubConfigResolved?: true;
35
30
  }
@@ -64,6 +59,7 @@ export interface RunViteHubCliOptions {
64
59
  loadNuxtViteConfig?: (rootDir: string, command: "build" | "serve", mode?: string) => Promise<{
65
60
  nitro?: unknown;
66
61
  plugins: readonly unknown[];
62
+ resolve?: OperationResolveConfig;
67
63
  root?: string;
68
64
  } | undefined>;
69
65
  spawn?: ViteHubCliSpawn;
package/dist/index.js CHANGED
@@ -1,9 +1,11 @@
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 { $ as consoleClient, $t as operationCall, Cn as withStdoutOnStderr, Gt as readProvisionStateSync, Ht as PROVISION_STATE_FILE, Jt as withViteStageEnvironment, Qt as createOperationRegistry, Sn as viteCliProjectConfig, Yt as callOperation, Zt as collectOperationContributions, _n as createCliDiscoveryNitroCloser, an as reservedOperationNamespaces, bn as isCliViteMissing, en as operationCliOptions, gn as collectViteHubCliContribution, hn as appUrlError, in as operationInputJsonSchema, mn as quoteSupportedInstallSpecifier, nn as operationsOf, on as setupCommandNames, qt as loadAllEnv, rn as parseOperationInput, sn as resolveViteHubProjectRoot, t as createProvisionNamespace, tn as operationCliPath, vn as findViteHubDevServerUrl, wn as isRecord, xn as rethrowCliViteImportError, xt as selectConsole, yn as getStableStdoutWrite, zt as cliErrorDiagnostics } from "./provision-DWEZYLWJ.js";
2
2
  import { spawn } from "node:child_process";
3
3
  import { existsSync, readFileSync, statSync } from "node:fs";
4
4
  import process$1 from "node:process";
5
5
  import { basename, dirname, relative, resolve } from "pathe";
6
+ import { isAbsolute, resolve as resolve$1 } from "node:path";
6
7
  import { createInterface } from "node:readline/promises";
8
+ import { pathToFileURL } from "node:url";
7
9
  import { formatRuntimeDiagnosticError } from "@vite-hub/runtime";
8
10
  // ../internal/dist/inspect.js
9
11
  async function collectContributors(plugins) {
@@ -573,21 +575,86 @@ 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 { 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
+ return new Map(modules.map((name, index) => [name, module.default[index]]));
625
+ } catch (reason) {
626
+ return new Map(modules.map((name) => [name, {
627
+ reason,
628
+ status: "rejected"
629
+ }]));
630
+ }
631
+ }
576
632
  // 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) {
633
+ /**
634
+ * Reads every contributed operation of the resolved plugins. Node imports each module first. When Node cannot load it,
635
+ * Vite loads it with the resolution of the app, so relative imports without an extension, the aliases, and the tsconfig
636
+ * paths of the Vite config work. A module that fails to load is reported on stderr.
637
+ */
638
+ async function loadCliOperations(plugins, resolution, stderr) {
639
+ const contributions = await collectOperationContributions(await flattenPluginOptions(plugins));
640
+ const loaded = await loadOperationContributions(contributions, resolution);
579
641
  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`);
642
+ for (const [index, contribution] of contributions.entries()) {
643
+ const result = loaded[index];
644
+ if (result.status === "fulfilled") {
645
+ sources.push({
646
+ operations: result.value,
647
+ plugin: contribution.plugin
648
+ });
649
+ continue;
650
+ }
651
+ const reason = result.reason instanceof Error ? result.reason.message : String(result.reason);
652
+ stderr.write(`${formatRuntimeDiagnosticError(cliErrorDiagnostics.CLI_OPERATIONS_LOAD_FAILED({
653
+ export: contribution.export,
654
+ module: contribution.module,
655
+ plugin: contribution.plugin,
656
+ reason
657
+ }))}\n`);
591
658
  }
592
659
  return createOperationRegistry(sources).list();
593
660
  }
@@ -798,6 +865,15 @@ function readWholeInput(raw, cwd) {
798
865
  if (!isObject(value)) throw usageError("--input must be a JSON object.");
799
866
  return value;
800
867
  }
868
+ function positionalKeysSkippingLeadingOptionals(positional, flags, named, count) {
869
+ const keys = [];
870
+ for (const [index, key] of positional.entries()) {
871
+ const requiredAfter = positional.slice(index + 1).filter((next) => !named.has(next) && flags.find((flag) => flag.key === next)?.required !== false).length;
872
+ if (flags.find((flag) => flag.key === key)?.required === false && count - keys.length <= requiredAfter) continue;
873
+ keys.push(key);
874
+ }
875
+ return keys;
876
+ }
801
877
  function parseCall(operation, flags, args, cwd) {
802
878
  const parsed = {
803
879
  help: false,
@@ -805,17 +881,15 @@ function parseCall(operation, flags, args, cwd) {
805
881
  json: false,
806
882
  yes: false
807
883
  };
808
- const positional = [...operationCliOptions(operation)?.positional ?? []];
884
+ const positional = operationCliOptions(operation)?.positional ?? [];
885
+ const assignments = [];
886
+ const named = /* @__PURE__ */ new Set();
809
887
  const { command, namespace } = operationCliPath(operation);
810
888
  let whole = {};
811
889
  for (let index = 0; index < args.length; index++) {
812
890
  const arg = args[index];
813
891
  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
- }
892
+ assignments.push(...args.slice(index + 1));
819
893
  break;
820
894
  }
821
895
  if (arg === "-h" || arg === "--help") parsed.help = true;
@@ -843,17 +917,28 @@ function parseCall(operation, flags, args, cwd) {
843
917
  const key = camel(negated ? name.slice(3) : name);
844
918
  const flag = flags.find((entry) => entry.key === key);
845
919
  if (!flag) throw usageError(`Unknown option --${name}. Run \`vitehub ${namespace} ${command} --help\` for the input.`);
920
+ named.add(key);
846
921
  if (flag.type === "boolean") {
847
922
  const next = args[index + 1];
848
923
  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());
924
+ assignments.push(() => {
925
+ parsed.input[key] = negated ? false : value;
926
+ });
927
+ } else {
928
+ const raw = take();
929
+ assignments.push(() => assign(parsed.input, flag, key, name, raw));
930
+ }
851
931
  }
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
- }
932
+ } else assignments.push(arg);
933
+ }
934
+ for (const key of Object.keys(whole)) named.add(key);
935
+ const keys = positionalKeysSkippingLeadingOptionals(positional, flags, named, assignments.filter((value) => typeof value === "string").length);
936
+ let position = 0;
937
+ for (const assignment of assignments) if (typeof assignment !== "string") assignment();
938
+ else {
939
+ const key = keys[position++];
940
+ if (key === void 0) throw usageError(`Unexpected argument ${JSON.stringify(assignment)}.`);
941
+ assign(parsed.input, flags.find((flag) => flag.key === key), key, kebab(key), assignment);
857
942
  }
858
943
  parsed.input = {
859
944
  ...whole,
@@ -905,13 +990,14 @@ async function confirm(operation, target) {
905
990
  function acceptedRoots(rootDir) {
906
991
  return [.../* @__PURE__ */ new Set([rootDir, resolveViteHubProjectRoot(rootDir)])];
907
992
  }
993
+ /** The Console route for a call on `url` after `vitehub login`, or nothing when the CLI calls the app directly. Never throws. */
908
994
  async function throughConsole(url, context, signal) {
909
995
  if (Object.keys(context.env).some((name) => name.startsWith("VITEHUB_CONSOLE_PRIVATE_KEY_") && context.env[name])) return;
910
996
  const warnDiscoveryFailed = () => {
911
997
  context.stderr.write("Warning: Console discovery failed. The CLI will call the app directly if time remains.\n");
912
998
  };
913
999
  try {
914
- const credential = await readConsoleCredential(context.env, void 0, signal);
1000
+ const { credential } = await selectConsole(context, void 0, signal);
915
1001
  if (!credential) return;
916
1002
  const { body } = await consoleClient(context, credential, signal).request("/api/projects");
917
1003
  signal.throwIfAborted();
@@ -1393,13 +1479,14 @@ function createSeedNamespace(seeds) {
1393
1479
  const BUILTIN_NAMESPACE_NAMES = new Set(reservedOperationNamespaces);
1394
1480
  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
1481
  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.";
1482
+ 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
1483
  const hostEnvFeatures = {
1397
1484
  description: "Compare, push, and pull the env names of the app on a host.",
1398
1485
  features: [
1399
1486
  {
1400
1487
  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
1488
  name: "diff",
1402
- run: async (args, context) => await (await import("./env-DzYHxq9A.js").then((n) => n.n)).runEnvCommand({
1489
+ run: async (args, context) => await (await import("./env-DSPUdOVC.js").then((n) => n.n)).runEnvCommand({
1403
1490
  ...hostEnvFeatures.features[0],
1404
1491
  name: "diff"
1405
1492
  }, args, context),
@@ -1408,7 +1495,7 @@ const hostEnvFeatures = {
1408
1495
  {
1409
1496
  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
1497
  name: "push",
1411
- run: async (args, context) => await (await import("./env-DzYHxq9A.js").then((n) => n.n)).runEnvCommand({
1498
+ run: async (args, context) => await (await import("./env-DSPUdOVC.js").then((n) => n.n)).runEnvCommand({
1412
1499
  ...hostEnvFeatures.features[1],
1413
1500
  name: "push"
1414
1501
  }, args, context),
@@ -1417,14 +1504,14 @@ const hostEnvFeatures = {
1417
1504
  {
1418
1505
  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
1506
  name: "pull",
1420
- run: async (args, context) => await (await import("./console-env-lQ3_eMOy.js")).envPullFeature.run(args, context),
1507
+ run: async (args, context) => await (await import("./console-env-MPzeOLqu.js").then((n) => n.t)).envPullFeature.run(args, context),
1421
1508
  usage: "vitehub env pull --from console [--stage <name>] [--project <id>] [--console <url>] [--yes] [--json]"
1422
1509
  }
1423
1510
  ],
1424
1511
  name: "env"
1425
1512
  };
1426
1513
  async function loadSetupCommands() {
1427
- return (await import("./commands-FOmqEZUi.js").then((n) => n.t)).setupCommands;
1514
+ return (await import("./commands-o_CHzNS9.js").then((n) => n.t)).setupCommands;
1428
1515
  }
1429
1516
  async function loadNuxtViteConfig(rootDir, command, mode) {
1430
1517
  if (![
@@ -1496,6 +1583,7 @@ async function loadNuxtViteConfig(rootDir, command, mode) {
1496
1583
  handlers: [...nitroHandlers(nuxt.options.nitro), ...nuxt.options.serverHandlers]
1497
1584
  }, nuxt.options.rootDir || rootDir)] },
1498
1585
  plugins: config.plugins,
1586
+ resolve: config.resolve,
1499
1587
  root: config.root
1500
1588
  };
1501
1589
  } finally {
@@ -1549,18 +1637,26 @@ function defaultSpawn(command, args, options = {}) {
1549
1637
  ]
1550
1638
  });
1551
1639
  const stdout = [];
1552
- child.stdout?.on("data", (chunk) => stdout.push(chunk));
1553
- child.stderr?.resume();
1640
+ const stderr = [];
1641
+ const onOutput = options.onOutput;
1642
+ if (onOutput) {
1643
+ child.stdout?.setEncoding("utf8").on("data", (text) => onOutput(text, "stdout"));
1644
+ child.stderr?.setEncoding("utf8").on("data", (text) => onOutput(text, "stderr"));
1645
+ } else {
1646
+ child.stdout?.on("data", (chunk) => stdout.push(chunk));
1647
+ child.stderr?.on("data", (chunk) => stderr.push(chunk));
1648
+ }
1554
1649
  child.on("error", reject);
1555
1650
  child.on("close", (exitCode, signal) => resolveResult({
1556
1651
  exitCode,
1557
1652
  signal,
1558
- ...child.stdout ? { stdout: Buffer.concat(stdout).toString("utf8") } : {}
1653
+ ...child.stdout && !onOutput ? { stdout: Buffer.concat(stdout).toString("utf8") } : {},
1654
+ ...child.stderr && !onOutput ? { stderr: Buffer.concat(stderr).toString("utf8") } : {}
1559
1655
  }));
1560
1656
  });
1561
1657
  }
1562
1658
  async function loadViteConfig(rootDir, command, mode) {
1563
- const { resolveConfig } = await import("vite");
1659
+ const { resolveConfig } = await import("vite").catch((error) => rethrowCliViteImportError(error, import.meta.filename));
1564
1660
  const resolvedMode = mode ?? (command === "build" ? "production" : "development");
1565
1661
  const project = viteCliProjectConfig(rootDir);
1566
1662
  const nitro = createCliDiscoveryNitroCloser();
@@ -1613,6 +1709,12 @@ function isRootHelp(args) {
1613
1709
  function isHelpFlag(arg) {
1614
1710
  return arg === "-h" || arg === "--help";
1615
1711
  }
1712
+ function isDiscoveryHelp(args) {
1713
+ const [namespace, feature, option] = args;
1714
+ if (!namespace || isRootHelp(args)) return true;
1715
+ if (namespace.startsWith("-")) return false;
1716
+ return isHelpFlag(feature) || feature !== void 0 && !feature.startsWith("-") && isHelpFlag(option);
1717
+ }
1616
1718
  async function loadHelpNamespace(args, helpNamespaces) {
1617
1719
  const [name, feature, ...rest] = args;
1618
1720
  if (!name || !helpNamespaces || !Object.hasOwn(helpNamespaces, name) || BUILTIN_NAMESPACE_NAMES.has(name)) return;
@@ -1661,12 +1763,18 @@ async function runViteHubCli(options = {}) {
1661
1763
  const config = await (stage ? loadConfig(cwd, command, stage) : loadConfig(cwd, command));
1662
1764
  const nuxtConfig = config.vitehubConfigResolved ? void 0 : await (stage ? loadNuxtConfig(cwd, command, stage) : loadNuxtConfig(cwd, command));
1663
1765
  const plugins = nuxtConfig?.plugins ?? config.plugins;
1766
+ const rootDir = resolve(nuxtConfig?.root || config.root || cwd);
1767
+ const { alias, tsconfigPaths } = (nuxtConfig ?? config).resolve ?? {};
1664
1768
  return {
1665
1769
  contribution: await collectViteHubCliContribution(plugins),
1666
1770
  handlers: resolveRouteHandlers(nuxtConfig ? nuxtConfig.nitro : config.nitro, nuxtConfig?.root || config.root || cwd),
1667
- operations: await loadCliOperations(plugins, stderr),
1771
+ operations: await loadCliOperations(plugins, {
1772
+ alias,
1773
+ root: rootDir,
1774
+ tsconfigPaths
1775
+ }, stderr),
1668
1776
  plugins,
1669
- rootDir: resolve(nuxtConfig?.root || config.root || cwd)
1777
+ rootDir
1670
1778
  };
1671
1779
  }, stderr);
1672
1780
  const loadProvision = options.loadProvision ?? (async (host) => {
@@ -1674,7 +1782,8 @@ async function runViteHubCli(options = {}) {
1674
1782
  return await withViteStageEnvironment({
1675
1783
  ...discoveryEnv,
1676
1784
  VITEHUB_HOST: host,
1677
- VITEHUB_HOST_SOURCE: "cli"
1785
+ VITEHUB_HOST_SOURCE: "cli",
1786
+ VITEHUB_LINK_ROOT: resolve(cwd)
1678
1787
  }, async () => {
1679
1788
  const loaded = await loadProject("build");
1680
1789
  return {
@@ -1713,7 +1822,14 @@ async function runViteHubCli(options = {}) {
1713
1822
  stdout
1714
1823
  });
1715
1824
  const runtimeNamespace = options.runtimeNamespaces?.find((namespace) => namespace.name === args[0] && !BUILTIN_NAMESPACE_NAMES.has(namespace.name));
1825
+ const consoleRoute = async (url, signal) => await throughConsole(url, {
1826
+ cwd,
1827
+ env,
1828
+ ...options.fetch ? { fetch: options.fetch } : {},
1829
+ stderr
1830
+ }, signal);
1716
1831
  if (runtimeNamespace) return await runNamespace(runtimeNamespace, args, {
1832
+ consoleRoute,
1717
1833
  cwd,
1718
1834
  env,
1719
1835
  rootDir: cwd,
@@ -1723,6 +1839,7 @@ async function runViteHubCli(options = {}) {
1723
1839
  });
1724
1840
  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
1841
  if (runtimeFeatures && (await options.runtimeFeatureGuard?.(args[0], args[1], cwd) ?? true)) return await runNamespace(runtimeFeatures, args, {
1842
+ consoleRoute,
1726
1843
  cwd,
1727
1844
  env,
1728
1845
  ...options.fetch ? { fetch: options.fetch } : {},
@@ -1748,20 +1865,16 @@ async function runViteHubCli(options = {}) {
1748
1865
  project = await (stage ? withViteStageEnvironment(env, () => loadProject(command)) : loadProject(command));
1749
1866
  } catch (error) {
1750
1867
  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([
1868
+ const helpWithoutVite = isCliViteMissing(error) && isDiscoveryHelp(args);
1869
+ if (!helpWithoutVite && args.length && !isRootHelp(args) && !envHelp) throw error;
1870
+ stderr.write(helpWithoutVite ? `${HELP_WITHOUT_VITE}\n\n` : `${formatRuntimeDiagnosticError(error)}\n${envHelp ? ENV_HELP_WITHOUT_CONFIG : ROOT_HELP_WITHOUT_CONFIG}\n\n`);
1871
+ if (envHelp) writeNamespaceHelp(hostEnvFeatures, stdout);
1872
+ else writeRootHelp([
1760
1873
  provisionNamespace,
1761
1874
  ...runtimeNamespaces,
1762
1875
  hostEnvFeatures
1763
1876
  ], await loadCommands(), stdout);
1764
- return 1;
1877
+ return helpWithoutVite ? 0 : 1;
1765
1878
  }
1766
1879
  const { contribution, handlers, operations, plugins, rootDir } = project;
1767
1880
  const runtimeNames = new Set(runtimeNamespaces.map((namespace) => namespace.name));
@@ -1780,6 +1893,7 @@ async function runViteHubCli(options = {}) {
1780
1893
  };
1781
1894
  else namespaces.push(hostEnvFeatures);
1782
1895
  const context = {
1896
+ consoleRoute,
1783
1897
  cwd,
1784
1898
  env,
1785
1899
  ...options.fetch ? { fetch: options.fetch } : {},
@@ -86,6 +86,7 @@ interface ProvisionStep {
86
86
  id: string;
87
87
  provider: ProvisionProvider;
88
88
  plan: (context: ProvisionContext) => Promise<ProvisionAction[]>;
89
+ hasResources?: (context: Pick<ProvisionContext, "env">) => boolean;
89
90
  /** Describes the Provision State this step records. Runs without network access, also without credentials. */
90
91
  recordedState?: (context: Pick<ProvisionContext, "env">) => ProvisionStateCategory[];
91
92
  }
@@ -102,10 +103,13 @@ interface ViteHubCliSpawnResult {
102
103
  signal?: NodeJS.Signals | null;
103
104
  /** The output of the child when `stdout` is `pipe`. */
104
105
  stdout?: string;
106
+ /** The error output of the child when `stderr` is `pipe`. */
107
+ stderr?: string;
105
108
  }
106
109
  interface ViteHubCliSpawnOptions {
107
110
  cwd?: string;
108
111
  env?: NodeJS.ProcessEnv;
112
+ onOutput?: (text: string, stream: "stdout" | "stderr") => void;
109
113
  stderr?: "inherit" | "pipe";
110
114
  /** `ignore` gives the child no terminal input, so a tool that asks questions on a terminal does not ask. */
111
115
  stdin?: "ignore" | "inherit";
@@ -113,7 +117,17 @@ interface ViteHubCliSpawnOptions {
113
117
  stdout?: "inherit" | "pipe" | "stderr";
114
118
  }
115
119
  type ViteHubCliSpawn = (command: string, args: string[], options?: ViteHubCliSpawnOptions) => Promise<ViteHubCliSpawnResult>;
120
+ /** Where a call to an app goes through the Console: the operation endpoint of the app's Console project, and the token of `vitehub login`. */
121
+ interface ViteHubCliConsoleRoute {
122
+ authorization: string;
123
+ target: string;
124
+ }
116
125
  interface ViteHubCliContext extends ViteHubCliStreams {
126
+ /**
127
+ * Finds the app at `url` in the Console of `vitehub login` and returns the route that lets the Console sign the call.
128
+ * Returns nothing when the command must call the app directly, such as when a `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` is set.
129
+ */
130
+ consoleRoute?: (url: string, signal: AbortSignal) => Promise<ViteHubCliConsoleRoute | undefined>;
117
131
  cwd: string;
118
132
  env: NodeJS.ProcessEnv;
119
133
  /** Replaces `fetch` for commands that call a running app, so tests need no server. */
@@ -132,6 +146,7 @@ interface ViteHubCliContext extends ViteHubCliStreams {
132
146
  spawn: ViteHubCliSpawn;
133
147
  }
134
148
  interface ViteHubCliProvision {
149
+ env?: NodeJS.ProcessEnv;
135
150
  rootDir: string;
136
151
  steps: readonly ProvisionStep[];
137
152
  }
@@ -159,4 +174,4 @@ interface ViteHubCliCommandNamespace {
159
174
  name: string;
160
175
  }
161
176
  type StdoutWriteCallback = (error?: Error | null) => void;
162
- export { ProvisionProvider as a, HostCliRun as c, ViteHubCliProvision as i, HostCredentials as l, ViteHubCliCommandNamespace as n, CredentialHost as o, ViteHubCliContext as r, CredentialSource as s, ViteHubCliCommand as t, HostCredentialsDescription as u };
177
+ export { ViteHubCliSpawn as a, CredentialSource as c, HostCredentialsDescription as d, ViteHubCliProvision as i, HostCliRun as l, ViteHubCliCommandNamespace as n, ProvisionProvider as o, ViteHubCliContext as r, CredentialHost as s, ViteHubCliCommand as t, HostCredentials as u };