@vite-hub/cli 0.3.1 → 0.4.1

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.
@@ -2,13 +2,14 @@ import { createRequire } from "node:module";
2
2
  import { spawn } from "node:child_process";
3
3
  import { readFileSync, statSync } from "node:fs";
4
4
  import { dirname, resolve } from "pathe";
5
+ import { defineDiagnostics } from "nostics";
5
6
  import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
6
7
  import { basename as basename$1, dirname as dirname$1, join as join$1, parse, resolve as resolve$1 } from "node:path";
7
8
  import "node:readline/promises";
8
- import { defineDiagnostics } from "nostics";
9
9
  import "node:url";
10
10
  import { tmpdir } from "node:os";
11
11
  import { createBirpc } from "birpc";
12
+ import { formatRuntimeDiagnosticError } from "@vite-hub/runtime";
12
13
  //#region ../internal/dist/object.js
13
14
  /** A non-null object that is not an array. Functions do not pass. */
14
15
  function isRecord(value) {
@@ -19,149 +20,7 @@ function isRecordOrFunction(value) {
19
20
  return Object(value) === value && !Array.isArray(value);
20
21
  }
21
22
  //#endregion
22
- //#region ../internal/dist/cli.js
23
- const stdoutRedirectQueueKey = Symbol.for("vite-hub.internal.stdout-redirect-queue");
24
- const stdoutRedirectWriterKey = Symbol.for("vite-hub.internal.stdout-redirect-writer");
25
- const stdoutRedirectSourceKey = Symbol.for("vite-hub.internal.stdout-redirect-source");
26
- const stdoutRedirectActiveKey = Symbol.for("vite-hub.internal.stdout-redirect-active");
27
- const stdoutRedirectGlobal = globalThis;
28
- /**
29
- * Sends `process.stdout` writes to stderr while `run` loads project config.
30
- * Vite, Nitro, Nuxt, and their plugins log info lines to stdout. Those lines must not mix with JSON or raw command output.
31
- */
32
- async function withStdoutOnStderr(run, stderr = process.stderr) {
33
- getStableStdoutWrite();
34
- const previous = stdoutRedirectGlobal[stdoutRedirectQueueKey] ?? Promise.resolve();
35
- let release;
36
- stdoutRedirectGlobal[stdoutRedirectQueueKey] = new Promise((resolve) => {
37
- release = resolve;
38
- });
39
- await previous;
40
- const write = process.stdout.write;
41
- if (stdoutRedirectGlobal[stdoutRedirectWriterKey] === void 0) {
42
- stdoutRedirectGlobal[stdoutRedirectSourceKey] = write;
43
- stdoutRedirectGlobal[stdoutRedirectWriterKey] = write.bind(process.stdout);
44
- }
45
- stdoutRedirectGlobal[stdoutRedirectActiveKey] = true;
46
- process.stdout.write = ((chunk, encoding, callback) => {
47
- const done = typeof encoding === "function" ? encoding : callback;
48
- let called = false;
49
- const onComplete = (error) => {
50
- if (called) return;
51
- called = true;
52
- done?.(error);
53
- };
54
- const result = typeof encoding === "function" ? stderr.write(chunk, onComplete) : stderr.write(chunk, encoding, onComplete);
55
- if (done && !called) {
56
- if (result && typeof result.then === "function") Promise.resolve(result).then(() => onComplete(), (error) => onComplete(error instanceof Error ? error : new Error(String(error))));
57
- else if (stderr.write.length < 2) onComplete();
58
- }
59
- return result;
60
- });
61
- try {
62
- return await run();
63
- } finally {
64
- process.stdout.write = write;
65
- stdoutRedirectGlobal[stdoutRedirectActiveKey] = false;
66
- release();
67
- }
68
- }
69
- /**
70
- * A Vite plugin for CLI discovery that collects the Nitro instances that Vite's config hooks create, and `close()` to stop them.
71
- * Nitro's Vite plugin starts its dev env runner (a worker thread, or Miniflare for Cloudflare) while Vite resolves a `serve`
72
- * config. Discovery never uses that runner. If it stays open, the process does not exit by itself, and when the CLI
73
- * then calls `process.exit()`, a StackBlitz WebContainer stops running later processes such as `vite`.
74
- */
75
- function createCliDiscoveryNitroCloser() {
76
- const instances = [];
77
- return {
78
- close: async () => {
79
- await Promise.all(instances.splice(0).map((nitro) => nitro.close()));
80
- },
81
- plugin: {
82
- name: "vite-hub/cli-discovery-nitro",
83
- nitro: { setup: (nitro) => {
84
- instances.push(nitro);
85
- } }
86
- }
87
- };
88
- }
89
- /** Returns the unredirected process stdout writer for payload output. */
90
- function getStableStdoutWrite() {
91
- const current = process.stdout.write;
92
- if (!stdoutRedirectGlobal[stdoutRedirectActiveKey] && stdoutRedirectGlobal[stdoutRedirectSourceKey] !== current) {
93
- stdoutRedirectGlobal[stdoutRedirectSourceKey] = current;
94
- stdoutRedirectGlobal[stdoutRedirectWriterKey] = current.bind(process.stdout);
95
- }
96
- return stdoutRedirectGlobal[stdoutRedirectWriterKey] ?? current.bind(process.stdout);
97
- }
98
- async function resolveContributor(value) {
99
- return typeof value === "function" ? await value() : value;
100
- }
101
- /** Resolves command namespaces and Provision Steps from one contribution per plugin. */
102
- async function collectViteHubCliContribution(plugins) {
103
- const namespaces = /* @__PURE__ */ new Map();
104
- const steps = /* @__PURE__ */ new Map();
105
- const seeds = /* @__PURE__ */ new Map();
106
- let publicUrl;
107
- for (const plugin of plugins) {
108
- if (!plugin || typeof plugin !== "object" || !Object.hasOwn(plugin, "vitehub")) continue;
109
- const metadata = plugin.vitehub;
110
- const contributor = await resolveContributor(metadata?.cli);
111
- if (!contributor) continue;
112
- publicUrl ??= contributor.publicUrl;
113
- for (const namespace of contributor.namespaces) {
114
- const existing = namespaces.get(namespace.name);
115
- if (!existing) {
116
- namespaces.set(namespace.name, {
117
- ...namespace,
118
- features: [...namespace.features]
119
- });
120
- continue;
121
- }
122
- const features = new Map(existing.features.map((feature) => [feature.name, feature]));
123
- for (const feature of namespace.features) features.set(feature.name, feature);
124
- existing.features = [...features.values()];
125
- }
126
- for (const step of contributor.provision ?? []) steps.set(step.id, step);
127
- for (const seed of contributor.seeds ?? []) seeds.set(seed.name, seed);
128
- }
129
- return {
130
- namespaces: [...namespaces.values()],
131
- provision: [...steps.values()],
132
- seeds: [...seeds.values()],
133
- ...publicUrl ? { publicUrl } : {}
134
- };
135
- }
136
- /** File in the project root where the running dev server tells commands where it listens. */
137
- const viteHubDevServerFile = ".vitehub/dev-server.json";
138
- /** The dev server that runs in `root`, or undefined when there is no file or it is not valid. */
139
- function readViteHubDevServerFile(root) {
140
- try {
141
- const value = JSON.parse(readFileSync(join$1(root, viteHubDevServerFile), "utf8"));
142
- const url = isRecord(value) ? value.url : void 0;
143
- const served = isRecord(value) ? value.root : void 0;
144
- return typeof url === "string" && url && typeof served === "string" && served ? {
145
- root: served,
146
- url
147
- } : void 0;
148
- } catch {
149
- return;
150
- }
151
- }
152
- /**
153
- * Where a command finds the dev server of its project: the file that the server wrote in a project root, else
154
- * `VITEHUB_DEV_SERVER_URL`. It never guesses a port, since another project may use it.
155
- */
156
- function findViteHubDevServerUrl(roots, env) {
157
- for (const root of roots) {
158
- const file = readViteHubDevServerFile(root);
159
- if (file && roots.some((candidate) => candidate.replace(/\/+$/, "") === file.root.replace(/\/+$/, ""))) return file.url;
160
- }
161
- return env["VITEHUB_DEV_SERVER_URL"] || void 0;
162
- }
163
- //#endregion
164
- //#region ../internal/dist/error-diagnostics-NFLF9k-4.js
23
+ //#region ../internal/dist/error-diagnostics-D7txO3cV.js
165
24
  const dynamicError$1 = { why: ({ message }) => message === void 0 ? "" : String(message) };
166
25
  const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
167
26
  docsBase: "https://vitehub.dev/docs/development/diagnostics",
@@ -332,7 +191,7 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
332
191
  },
333
192
  INTERNAL_R0004: {
334
193
  ...dynamicError$1,
335
- fix: "Set a larger `maxResponseBytes` on the HTTP request, such as the `fetch()` Source options, or ask the server for a smaller response."
194
+ fix: "Set a larger `maxResponseBytes` on the HTTP request, such as the `url()` Source options, or ask the server for a smaller response."
336
195
  },
337
196
  INTERNAL_R0005: {
338
197
  ...dynamicError$1,
@@ -378,6 +237,10 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
378
237
  why: ({ variable }) => `[vitehub] ${variable} must be the 43-character private key that \`vitehub secret console-key\` prints, and its name 1 to 64 of A-Z, 0-9, and _.`,
379
238
  fix: "Set the variable that the message names to the private key that `vitehub secret console-key` prints, and name it `VITEHUB_CONSOLE_PRIVATE_KEY_<NAME>` with A-Z, 0-9, and _ in `<NAME>`."
380
239
  },
240
+ INTERNAL_DEV_SERVER_NOT_FOUND: {
241
+ why: ({ command }) => `[vitehub] No dev server of this project is running, and --url is not set, so \`vitehub ${command}\` has no app to call.`,
242
+ fix: "Start the dev server of this project, such as with `pnpm dev`, or pass --url with the app URL, such as --url http://localhost:3000."
243
+ },
381
244
  INTERNAL_FORGE_NOT_INSTALLED: {
382
245
  why: ({ feature }) => `${feature} needs @vite-hub/forge, and the app did not install it.`,
383
246
  fix: "Install Forge in your app with `pnpm add @vite-hub/forge`, then build again."
@@ -425,6 +288,148 @@ const internalErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
425
288
  }
426
289
  });
427
290
  //#endregion
291
+ //#region ../internal/dist/cli.js
292
+ const stdoutRedirectQueueKey = Symbol.for("vite-hub.internal.stdout-redirect-queue");
293
+ const stdoutRedirectWriterKey = Symbol.for("vite-hub.internal.stdout-redirect-writer");
294
+ const stdoutRedirectSourceKey = Symbol.for("vite-hub.internal.stdout-redirect-source");
295
+ const stdoutRedirectActiveKey = Symbol.for("vite-hub.internal.stdout-redirect-active");
296
+ const stdoutRedirectGlobal = globalThis;
297
+ /**
298
+ * Sends `process.stdout` writes to stderr while `run` loads project config.
299
+ * Vite, Nitro, Nuxt, and their plugins log info lines to stdout. Those lines must not mix with JSON or raw command output.
300
+ */
301
+ async function withStdoutOnStderr(run, stderr = process.stderr) {
302
+ getStableStdoutWrite();
303
+ const previous = stdoutRedirectGlobal[stdoutRedirectQueueKey] ?? Promise.resolve();
304
+ let release;
305
+ stdoutRedirectGlobal[stdoutRedirectQueueKey] = new Promise((resolve) => {
306
+ release = resolve;
307
+ });
308
+ await previous;
309
+ const write = process.stdout.write;
310
+ if (stdoutRedirectGlobal[stdoutRedirectWriterKey] === void 0) {
311
+ stdoutRedirectGlobal[stdoutRedirectSourceKey] = write;
312
+ stdoutRedirectGlobal[stdoutRedirectWriterKey] = write.bind(process.stdout);
313
+ }
314
+ stdoutRedirectGlobal[stdoutRedirectActiveKey] = true;
315
+ process.stdout.write = ((chunk, encoding, callback) => {
316
+ const done = typeof encoding === "function" ? encoding : callback;
317
+ let called = false;
318
+ const onComplete = (error) => {
319
+ if (called) return;
320
+ called = true;
321
+ done?.(error);
322
+ };
323
+ const result = typeof encoding === "function" ? stderr.write(chunk, onComplete) : stderr.write(chunk, encoding, onComplete);
324
+ if (done && !called) {
325
+ if (result && typeof result.then === "function") Promise.resolve(result).then(() => onComplete(), (error) => onComplete(error instanceof Error ? error : new Error(String(error))));
326
+ else if (stderr.write.length < 2) onComplete();
327
+ }
328
+ return result;
329
+ });
330
+ try {
331
+ return await run();
332
+ } finally {
333
+ process.stdout.write = write;
334
+ stdoutRedirectGlobal[stdoutRedirectActiveKey] = false;
335
+ release();
336
+ }
337
+ }
338
+ /**
339
+ * A Vite plugin for CLI discovery that collects the Nitro instances that Vite's config hooks create, and `close()` to stop them.
340
+ * Nitro's Vite plugin starts its dev env runner (a worker thread, or Miniflare for Cloudflare) while Vite resolves a `serve`
341
+ * config. Discovery never uses that runner. If it stays open, the process does not exit by itself, and when the CLI
342
+ * then calls `process.exit()`, a StackBlitz WebContainer stops running later processes such as `vite`.
343
+ */
344
+ function createCliDiscoveryNitroCloser() {
345
+ const instances = [];
346
+ return {
347
+ close: async () => {
348
+ await Promise.all(instances.splice(0).map((nitro) => nitro.close()));
349
+ },
350
+ plugin: {
351
+ name: "vite-hub/cli-discovery-nitro",
352
+ nitro: { setup: (nitro) => {
353
+ instances.push(nitro);
354
+ } }
355
+ }
356
+ };
357
+ }
358
+ /** Returns the unredirected process stdout writer for payload output. */
359
+ function getStableStdoutWrite() {
360
+ const current = process.stdout.write;
361
+ if (!stdoutRedirectGlobal[stdoutRedirectActiveKey] && stdoutRedirectGlobal[stdoutRedirectSourceKey] !== current) {
362
+ stdoutRedirectGlobal[stdoutRedirectSourceKey] = current;
363
+ stdoutRedirectGlobal[stdoutRedirectWriterKey] = current.bind(process.stdout);
364
+ }
365
+ return stdoutRedirectGlobal[stdoutRedirectWriterKey] ?? current.bind(process.stdout);
366
+ }
367
+ async function resolveContributor(value) {
368
+ return typeof value === "function" ? await value() : value;
369
+ }
370
+ /** Resolves command namespaces and Provision Steps from one contribution per plugin. */
371
+ async function collectViteHubCliContribution(plugins) {
372
+ const namespaces = /* @__PURE__ */ new Map();
373
+ const steps = /* @__PURE__ */ new Map();
374
+ const seeds = /* @__PURE__ */ new Map();
375
+ let publicUrl;
376
+ for (const plugin of plugins) {
377
+ if (!plugin || typeof plugin !== "object" || !Object.hasOwn(plugin, "vitehub")) continue;
378
+ const metadata = plugin.vitehub;
379
+ const contributor = await resolveContributor(metadata?.cli);
380
+ if (!contributor) continue;
381
+ publicUrl ??= contributor.publicUrl;
382
+ for (const namespace of contributor.namespaces) {
383
+ const existing = namespaces.get(namespace.name);
384
+ if (!existing) {
385
+ namespaces.set(namespace.name, {
386
+ ...namespace,
387
+ features: [...namespace.features]
388
+ });
389
+ continue;
390
+ }
391
+ const features = new Map(existing.features.map((feature) => [feature.name, feature]));
392
+ for (const feature of namespace.features) features.set(feature.name, feature);
393
+ existing.features = [...features.values()];
394
+ }
395
+ for (const step of contributor.provision ?? []) steps.set(step.id, step);
396
+ for (const seed of contributor.seeds ?? []) seeds.set(seed.name, seed);
397
+ }
398
+ return {
399
+ namespaces: [...namespaces.values()],
400
+ provision: [...steps.values()],
401
+ seeds: [...seeds.values()],
402
+ ...publicUrl ? { publicUrl } : {}
403
+ };
404
+ }
405
+ /** File in the project root where the running dev server tells commands where it listens. */
406
+ const viteHubDevServerFile = ".vitehub/dev-server.json";
407
+ /** The dev server that runs in `root`, or undefined when there is no file or it is not valid. */
408
+ function readViteHubDevServerFile(root) {
409
+ try {
410
+ const value = JSON.parse(readFileSync(join$1(root, viteHubDevServerFile), "utf8"));
411
+ const url = isRecord(value) ? value.url : void 0;
412
+ const served = isRecord(value) ? value.root : void 0;
413
+ return typeof url === "string" && url && typeof served === "string" && served ? {
414
+ root: served,
415
+ url
416
+ } : void 0;
417
+ } catch {
418
+ return;
419
+ }
420
+ }
421
+ /**
422
+ * Where a command finds the dev server of its project: the file that the server wrote in a project root, else
423
+ * `VITEHUB_DEV_SERVER_URL`. It never guesses a port, since another project may use it.
424
+ */
425
+ function findViteHubDevServerUrl(roots, env) {
426
+ for (const root of roots) {
427
+ const file = readViteHubDevServerFile(root);
428
+ if (file && roots.some((candidate) => candidate.replace(/\/+$/, "") === file.root.replace(/\/+$/, ""))) return file.url;
429
+ }
430
+ return env["VITEHUB_DEV_SERVER_URL"] || void 0;
431
+ }
432
+ //#endregion
428
433
  //#region ../internal/dist/console-signature.js
429
434
  /**
430
435
  * Signed requests to the Console endpoint of an app, `POST /_vitehub/rpc`. Each caller, such as one Console link or one
@@ -693,6 +698,7 @@ const setupCommandNames = [
693
698
  "drain",
694
699
  "login",
695
700
  "logout",
701
+ "update",
696
702
  "whoami"
697
703
  ];
698
704
  /** CLI namespaces owned by built-in commands. */
@@ -1212,7 +1218,7 @@ function sortKeys(value) {
1212
1218
  //#region src/error-diagnostics.ts
1213
1219
  const dynamicError = { why: ({ message }) => message === void 0 ? "" : String(message) };
1214
1220
  const cliErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
1215
- docsBase: "https://vitehub.dev/docs/development/diagnostics",
1221
+ docsBase: "https://vitehub.dev/docs/cli/diagnostics",
1216
1222
  codes: {
1217
1223
  CLI_CONSOLE_LOGIN_FAILED: {
1218
1224
  fix: "Run `vitehub login` again, and approve the code in the browser within 15 minutes. Pass --console <url> for a self-hosted Console.",
@@ -1260,10 +1266,30 @@ const cliErrorDiagnostics = /*#__PURE__*/ defineDiagnostics({
1260
1266
  fix: "Fix the cause that the message names, then run the command again.",
1261
1267
  why: ({ message }) => message
1262
1268
  },
1269
+ CLI_UPDATE_INSTALL_FAILED: {
1270
+ fix: ({ command }) => `The package files already name the new versions. Fix the cause that the package manager printed, then run \`${String(command)}\`. To undo the update, restore the changed files with git.`,
1271
+ why: ({ command, exitCode }) => `\`${String(command)}\` exited with code ${String(exitCode)}.`
1272
+ },
1273
+ CLI_UPDATE_NO_PACKAGES: {
1274
+ fix: "Run `vitehub update` in the folder of the app or of the workspace that installs `vite-hub`. To start, run `pnpm add vite-hub`.",
1275
+ why: ({ root }) => `No package.json in ${String(root)} or its workspace packages names \`vite-hub\` or an \`@vite-hub/*\` package with a version or a pkg.pr.new URL.`
1276
+ },
1277
+ CLI_UPDATE_PACKAGE_MISSING: {
1278
+ fix: ({ target }) => String(target) === "npm" ? "Pass --preview <commit> to use a pkg.pr.new build that has these packages, or remove them from package.json." : "Pass the commit of a build that has these packages, such as a newer commit of main, or remove them from package.json.",
1279
+ why: ({ packages, target }) => `The project depends on ${String(packages)}, which ${String(target)} does not have. Nothing was changed.`
1280
+ },
1281
+ CLI_UPDATE_REQUEST_FAILED: {
1282
+ fix: "Check the network and the npm registry in `npm_config_registry`, then run `vitehub update` again.",
1283
+ why: ({ status, url }) => `The request to ${String(url)} failed (${String(status)}). Nothing was changed.`
1284
+ },
1263
1285
  SETUP_CONFIG_NOT_LITERAL: {
1264
1286
  fix: "Write the options as an object literal, such as `vitehub({ kv: true })`, or edit the config by hand.",
1265
1287
  why: ({ file, reason }) => `The vitehub() options in ${String(file)} cannot be read without running the config (${String(reason)}).`
1266
1288
  },
1289
+ SETUP_LOGS_OPTION_MOVED: {
1290
+ why: "`observability.logs` is no longer a ViteHub option.",
1291
+ fix: "Remove the option from the command. Configure the top-level `logs` key by hand, for example `logs: { source: './server/logs.ts' }` to set `logs.source`."
1292
+ },
1267
1293
  SETUP_NOT_A_PROJECT: {
1268
1294
  fix: "Run the command in the folder of your Vite or Nuxt app, where its package.json is.",
1269
1295
  why: ({ root }) => `${String(root)} has no package.json, vite.config, or nuxt.config file.`
@@ -1922,8 +1948,8 @@ const HOST_CREDENTIALS = {
1922
1948
  vercel: "VERCEL_TOKEN"
1923
1949
  };
1924
1950
  const USAGE = {
1925
- run: "vitehub provision run --host <cloudflare|vercel> [--dry-run] [--json]",
1926
- status: "vitehub provision status --host <cloudflare|vercel> [--json]"
1951
+ run: "vitehub provision run [--host <cloudflare|vercel>] [--dry-run] [--json]",
1952
+ status: "vitehub provision status [--host <cloudflare|vercel>] [--json]"
1927
1953
  };
1928
1954
  /** Whether ViteHub can provision resources on `host`. Only Cloudflare and Vercel have Provision Steps. */
1929
1955
  function isProvisionHost(value) {
@@ -1937,8 +1963,7 @@ function setVariable(env, name, value) {
1937
1963
  }
1938
1964
  /**
1939
1965
  * The environment of a Provision Step: `env` with the host credentials that `resolveHostCredentials` found, such as a
1940
- * `wrangler login` token, and the account and project ids of the host link. The selected deploy link wins over
1941
- * environment scope; standalone provision has no link.
1966
+ * `wrangler login` token, and the account and project ids of the host link. The selected link wins over environment scope.
1942
1967
  */
1943
1968
  function provisionEnv(env, credentials, link = {}) {
1944
1969
  if (!credentials.ok) return env;
@@ -2003,7 +2028,8 @@ function writeUsage(command, stream) {
2003
2028
  "Never deletes resources. Changes an existing resource only for a planned update, such as D1 read replication.",
2004
2029
  "",
2005
2030
  "Options:",
2006
- " --host <name> Target host: cloudflare or vercel (required).",
2031
+ " --host <name> Target host: cloudflare or vercel. Without it, the host of `vitehub deploy`:",
2032
+ " the default target of .vitehub/link.json, else the only one, else `host` in vitehub().",
2007
2033
  " --dry-run Print the plan without applying it.",
2008
2034
  " --json Print one JSON result to stdout.",
2009
2035
  " -h, --help Show this help."
@@ -2015,13 +2041,13 @@ function writeUsage(command, stream) {
2015
2041
  "Never creates or deletes provider resources, and never writes Provision State.",
2016
2042
  "",
2017
2043
  "Options:",
2018
- " --host <name> Target host: cloudflare or vercel (required).",
2044
+ " --host <name> Target host: cloudflare or vercel. Without it, the host of `vitehub deploy`.",
2019
2045
  " --json Print one JSON result to stdout.",
2020
2046
  " -h, --help Show this help."
2021
2047
  ];
2022
2048
  stream.write(`${lines.join("\n")}\n\n`);
2023
2049
  }
2024
- function resolveHost(command, parsed, context) {
2050
+ async function resolveHost(command, parsed, context) {
2025
2051
  if (parsed.help) {
2026
2052
  writeUsage(command, context.stdout);
2027
2053
  return { exitCode: 0 };
@@ -2031,18 +2057,38 @@ function resolveHost(command, parsed, context) {
2031
2057
  writeUsage(command, context.stderr);
2032
2058
  return { exitCode: 1 };
2033
2059
  }
2034
- if (!isProvisionHost(parsed.host)) {
2060
+ let host = parsed.host;
2061
+ let link;
2062
+ if (host === void 0) {
2063
+ const { resolveDefaultDeployTarget } = await import("./deploy-C0RdI5OK.js").then((n) => n.n);
2064
+ try {
2065
+ const target = await resolveDefaultDeployTarget(resolveViteHubProjectRoot(context.rootDir), context.env, `vitehub provision ${command}`);
2066
+ host = target.host;
2067
+ link = target.link;
2068
+ } catch (error) {
2069
+ context.stderr.write(`${formatRuntimeDiagnosticError(error)}\n`);
2070
+ return { exitCode: 1 };
2071
+ }
2072
+ if (!isProvisionHost(host)) {
2073
+ context.stderr.write(`The host of this project is ${host}, and provision supports cloudflare and vercel. Pass --host cloudflare|vercel to provision another host.\n`);
2074
+ return { exitCode: 1 };
2075
+ }
2076
+ }
2077
+ if (!isProvisionHost(host)) {
2035
2078
  context.stderr.write("Provision requires --host cloudflare|vercel.\n");
2036
2079
  writeUsage(command, context.stderr);
2037
2080
  return { exitCode: 1 };
2038
2081
  }
2039
- return { host: parsed.host };
2082
+ return {
2083
+ host,
2084
+ ...link ? { link } : {}
2085
+ };
2040
2086
  }
2041
2087
  function hasHostCredentials(host, env) {
2042
2088
  return Boolean(host === "cloudflare" ? resolveCloudflareProvisionConfig(env) : resolveVercelProvisionConfig(env));
2043
2089
  }
2044
2090
  /** The context with the credentials of `resolveHostCredentials` in its env, so a `wrangler login` works as in deploy. */
2045
- async function withHostCredentials(host, context) {
2091
+ async function withHostCredentials(host, context, link) {
2046
2092
  const credentials = await resolveHostCredentials(host, {
2047
2093
  cwd: context.rootDir,
2048
2094
  env: context.env,
@@ -2050,11 +2096,14 @@ async function withHostCredentials(host, context) {
2050
2096
  });
2051
2097
  return {
2052
2098
  ...context,
2053
- env: provisionEnv(context.env, credentials)
2099
+ env: provisionEnv(context.env, credentials, {
2100
+ ...link?.account?.id ? { accountId: link.account.id } : {},
2101
+ ...link?.project.id ? { projectId: link.project.id } : {}
2102
+ })
2054
2103
  };
2055
2104
  }
2056
- async function planProvision(provider, context, options, json) {
2057
- return await planProvisionSteps(provider, await options.collectSteps(), {
2105
+ async function planProvision(provider, context, steps, json) {
2106
+ return await planProvisionSteps(provider, [...steps], {
2058
2107
  env: context.env,
2059
2108
  fetch: globalThis.fetch,
2060
2109
  logger: {
@@ -2145,18 +2194,23 @@ function writeProvisionActions(actions, stdout) {
2145
2194
  stdout.write(`${provisionActionStatus(planned)}\t${action.kind}\t${action.name}${action.update ? `\t${action.update}` : ""}\n`);
2146
2195
  }
2147
2196
  }
2148
- async function runProvision(args, cliContext, options) {
2197
+ async function runProvision(args, cliContext, load) {
2149
2198
  const parsed = parseArgs("run", args);
2150
- const resolved = resolveHost("run", parsed, cliContext);
2199
+ const resolved = await resolveHost("run", parsed, cliContext);
2151
2200
  if ("exitCode" in resolved) return resolved.exitCode;
2152
2201
  const { host: provider } = resolved;
2153
- const context = await withHostCredentials(provider, cliContext);
2202
+ const { env = cliContext.env, rootDir, steps } = await load(provider);
2203
+ const context = await withHostCredentials(provider, {
2204
+ ...cliContext,
2205
+ env,
2206
+ rootDir
2207
+ }, resolved.link);
2154
2208
  if (!parsed.dryRun && !hasHostCredentials(provider, context.env)) {
2155
2209
  context.stderr.write(`Provision requires ${HOST_CREDENTIALS[provider]}. Dry-run preview does not require credentials (--dry-run).\n`);
2156
2210
  return 1;
2157
2211
  }
2158
2212
  if (!parsed.dryRun) await readProvisionState(context.rootDir);
2159
- const { actions, checked, warnings } = await planProvision(provider, context, options, parsed.json);
2213
+ const { actions, checked, warnings } = await planProvision(provider, context, steps, parsed.json);
2160
2214
  const blocked = !checked && !parsed.dryRun;
2161
2215
  if (!parsed.json) {
2162
2216
  if (!checked) context.stdout.write("provision: plan not checked.\n");
@@ -2192,16 +2246,21 @@ async function runProvision(args, cliContext, options) {
2192
2246
  } else if (wroteState) context.stdout.write(`provision: wrote ids to ${PROVISION_STATE_FILE}\n`);
2193
2247
  return blocked ? 1 : 0;
2194
2248
  }
2195
- async function runProvisionStatus(args, cliContext, options) {
2249
+ async function runProvisionStatus(args, cliContext, load) {
2196
2250
  const parsed = parseArgs("status", args);
2197
- const resolved = resolveHost("status", parsed, cliContext);
2251
+ const resolved = await resolveHost("status", parsed, cliContext);
2198
2252
  if ("exitCode" in resolved) return resolved.exitCode;
2199
2253
  const { host: provider } = resolved;
2200
- const context = await withHostCredentials(provider, cliContext);
2254
+ const { env = cliContext.env, rootDir, steps } = await load(provider);
2255
+ const context = await withHostCredentials(provider, {
2256
+ ...cliContext,
2257
+ env,
2258
+ rootDir
2259
+ }, resolved.link);
2201
2260
  const recorded = (await readProvisionState(context.rootDir))[provider] ?? {};
2202
- const undeclared = findUndeclaredEntries(provider, recorded, await options.collectSteps(), context.env);
2261
+ const undeclared = findUndeclaredEntries(provider, recorded, steps, context.env);
2203
2262
  const hasCredentials = hasHostCredentials(provider, context.env);
2204
- const { actions, checked, warnings } = hasCredentials ? await planProvision(provider, context, options, parsed.json) : {
2263
+ const { actions, checked, warnings } = hasCredentials ? await planProvision(provider, context, steps, parsed.json) : {
2205
2264
  actions: [],
2206
2265
  checked: false,
2207
2266
  warnings: [`provision: plan not checked, missing ${HOST_CREDENTIALS[provider]}.`]
@@ -2239,24 +2298,26 @@ async function runProvisionStatus(args, cliContext, options) {
2239
2298
  context.stdout.write(pending ? `plan: ${pending} pending ${pending === 1 ? "action" : "actions"}. Run \`vitehub provision run --host ${provider}\` to apply.\n` : "plan: no pending actions\n");
2240
2299
  return 0;
2241
2300
  }
2242
- /** Built-in namespace that orchestrates package-contributed Provision Steps. */
2243
- function createProvisionNamespace(steps) {
2244
- const options = { collectSteps: async () => [...steps] };
2301
+ /**
2302
+ * Built-in namespace that orchestrates package-contributed Provision Steps. `load` reads the steps of a build for the
2303
+ * `--host` of the command, so `provision run --host cloudflare` plans what `vitehub deploy --host cloudflare` creates.
2304
+ */
2305
+ function createProvisionNamespace(load) {
2245
2306
  return {
2246
2307
  description: "Idempotently create missing provider resources.",
2247
2308
  features: [{
2248
2309
  description: "Create missing provider resources for the app's Definitions.",
2249
2310
  name: "run",
2250
- run: (args, context) => runProvision(args, context, options),
2311
+ run: (args, context) => runProvision(args, context, load),
2251
2312
  usage: USAGE.run
2252
2313
  }, {
2253
2314
  description: "Show recorded provider ids and pending plan actions.",
2254
2315
  name: "status",
2255
- run: (args, context) => runProvisionStatus(args, context, options),
2316
+ run: (args, context) => runProvisionStatus(args, context, load),
2256
2317
  usage: USAGE.status
2257
2318
  }],
2258
2319
  name: "provision"
2259
2320
  };
2260
2321
  }
2261
2322
  //#endregion
2262
- export { operationInputJsonSchema as A, isRecord as B, callOperationFromCli as C, operationCliPath as D, operationCall as E, collectViteHubCliContribution as F, createCliDiscoveryNitroCloser as I, findViteHubDevServerUrl as L, setupCommandNames as M, resolveViteHubProjectRoot as N, operationsOf as O, internalErrorDiagnostics as P, getStableStdoutWrite as R, callOperation as S, createOperationRegistry as T, readProvisionState as _, writeProvisionActions as a, loadAllEnv as b, createNetlifyApiClient as c, planProvisionSteps as d, resolveHostCredentials as f, mergeProvisionState as g, PROVISION_STATE_FILE as h, provisionEnv as i, reservedOperationNamespaces as j, parseOperationInput as k, createVercelProvisionClient as l, cliErrorDiagnostics as m, isProvisionHost as n, createCloudflareApiClient as o, runHostCli as p, provisionActionStatus as r, createCloudflareProvisionClient as s, createProvisionNamespace as t, isProvisionRequestError as u, readProvisionStateSync as v, collectOperationContributions as w, withViteStageEnvironment as x, writeProvisionState as y, withStdoutOnStderr as z };
2323
+ export { operationInputJsonSchema as A, isRecord as B, callOperationFromCli as C, operationCliPath as D, operationCall as E, createCliDiscoveryNitroCloser as F, findViteHubDevServerUrl as I, getStableStdoutWrite as L, setupCommandNames as M, resolveViteHubProjectRoot as N, operationsOf as O, collectViteHubCliContribution as P, withStdoutOnStderr as R, callOperation as S, createOperationRegistry as T, readProvisionState as _, writeProvisionActions as a, loadAllEnv as b, createNetlifyApiClient as c, planProvisionSteps as d, resolveHostCredentials as f, mergeProvisionState as g, PROVISION_STATE_FILE as h, provisionEnv as i, reservedOperationNamespaces as j, parseOperationInput as k, createVercelProvisionClient as l, cliErrorDiagnostics as m, isProvisionHost as n, createCloudflareApiClient as o, runHostCli as p, provisionActionStatus as r, createCloudflareProvisionClient as s, createProvisionNamespace as t, isProvisionRequestError as u, readProvisionStateSync as v, collectOperationContributions as w, withViteStageEnvironment as x, writeProvisionState as y, internalErrorDiagnostics as z };