@vite-hub/cli 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,24 +1,43 @@
1
- import { A as readDeployCommit, B as featureIds, C as denoOrganization, D as build, E as listCloudflareDeployments, F as uninstallArgs, G as impliedInline, H as featureSupport, I as hostFromNitroPreset, J as locateViteHubConfig, K as editViteHubConfig, L as detectPackageManager, M as installCommand, N as setsOption, O as readBuildOutput, P as setupStatus, R as readSetupProject, S as denoAdapter, T as cloudflareAdapter, U as features, V as featurePackages, W as impliedFeatures, Y as __exportAll, _ as listVercelDeployments, a as ensureViteHubGitignore, b as netlifyAdapter, c as linkSetupProject, f as readSetupLinks, g as hasVercelLogin, h as writeSeparateResourcesNote, i as addSetupLink, j as installArgs, k as createDeployRun, l as readLinkHostOption, m as unlinkSetupProject, o as gitignoreWithViteHub, p as selectSetupLink, q as insertViteHubConfig, r as SETUP_LINK_FILE, s as hostRequired, t as checkDeployEnv, u as readSetupLinkState, v as vercelAdapter, w as listDenoDeployments, x as abortable, y as listNetlifyDeployments, z as featureHosts } from "./env-DzoVtVJO.js";
2
- import { C as callOperationFromCli, _ as readProvisionState, a as writeProvisionActions, d as planProvisionSteps, f as resolveHostCredentials, g as mergeProvisionState, h as PROVISION_STATE_FILE, i as provisionEnv, m as cliErrorDiagnostics, n as isProvisionHost, r as provisionActionStatus, y as writeProvisionState } from "./provision-D8OvBBzi.js";
3
- import { a as table, i as setupFailure, n as readSetupArgs, o as writeSetupError, r as setupExitCodes, s as writeSetupJson, t as isSetupFailure } from "./envelope-Cf56AJLa.js";
4
- import { l as whoamiCommand, o as loginCommand, s as logoutCommand } from "./console-auth-xl7kLQNt.js";
1
+ import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.js";
2
+ import { F as featureHosts, H as installSpecifier, I as featureIds, L as featurePackages, R as featureSupport, V as impliedFeatures, m as cliErrorDiagnostics, z as features } from "./provision-DgT_lpyn.js";
3
+ import { B as listMatchingFiles, F as setupStatus, G as insertViteHubConfig, H as readSetupProject, I as shellQuote, K as locateViteHubConfig, L as uninstallArgs, M as installArgs, N as installCommand, P as missingProviderOption, U as setupLockfiles, V as detectPackageManager, W as editViteHubConfig, c as linkSetupProject, j as formatInstallCommand, l as readLinkHostOption, m as unlinkSetupProject, o as gitignoreWithViteHub, r as SETUP_LINK_FILE, u as readSetupLinkState, z as hasDefinitionFiles } from "./env-MtXhP7A7.js";
4
+ import { a as table, i as setupFailure, n as readSetupArgs, o as writeSetupError, r as setupExitCodes, s as writeSetupJson, t as isSetupFailure } from "./envelope-C7e408hm.js";
5
+ import { l as whoamiCommand, o as loginCommand, s as logoutCommand } from "./console-auth-Dz9HHP2G.js";
6
+ import { a as deploymentsCommand, i as STATUS_HOST_TIMEOUT_MS, o as liveLabel, s as readSetupLive, t as deployCommand } from "./deploy-CHW75le_.js";
5
7
  import { createRequire } from "node:module";
6
- import { existsSync, readFileSync, readdirSync } from "node:fs";
8
+ import { existsSync, readFileSync } from "node:fs";
7
9
  import process from "node:process";
8
10
  import { basename, dirname, join, relative, resolve } from "pathe";
9
- import { mkdir, readFile, readdir, rm, rmdir, writeFile } from "node:fs/promises";
11
+ import { glob, mkdir, readFile, readdir, rm, rmdir, writeFile } from "node:fs/promises";
10
12
  import { join as join$1 } from "node:path";
11
13
  import { createInterface } from "node:readline/promises";
12
14
  import { pathToFileURL } from "node:url";
13
15
  import { createTwoFilesPatch } from "diff";
14
- import { parseArgs } from "node:util";
15
- import { Range, minVersion, subset, validRange } from "semver";
16
+ import { isDeepStrictEqual, parseArgs } from "node:util";
17
+ import semver, { Range, minVersion, subset, validRange } from "semver";
18
+ //#region ../internal/dist/feature-inputs.js
19
+ function isLocaleTag(value) {
20
+ try {
21
+ return Intl.getCanonicalLocales(value).length === 1;
22
+ } catch {
23
+ return false;
24
+ }
25
+ }
26
+ function i18nLocaleListProblem(locales) {
27
+ if (!Array.isArray(locales) || locales.length === 0) return "`i18n.locales` is empty.";
28
+ const seen = /* @__PURE__ */ new Set();
29
+ for (const locale of locales) {
30
+ if (typeof locale !== "string" || !isLocaleTag(locale)) return `\`${String(locale)}\` is not a BCP 47 language tag.`;
31
+ if (seen.has(locale.toLowerCase())) return `\`${locale}\` is listed twice.`;
32
+ seen.add(locale.toLowerCase());
33
+ }
34
+ }
35
+ function mcpPublicRouteNeedsSignedAuth(publicRoute, auth) {
36
+ return !!publicRoute && auth !== true;
37
+ }
38
+ //#endregion
16
39
  //#region src/setup/add.ts
17
- const usage$4 = "vitehub add <feature...> [--name <definition>] [--option <key=value>]... [--dry-run] [--yes] [--no-install] [--json]";
18
- /**
19
- * Values that `--option` can choose for an `explicit` host, first the one that `rerun` uses, and the feature that the
20
- * value needs. Options without an entry, such as `database.connection`, need a value that only the developer knows.
21
- */
40
+ const usage$3 = "vitehub add <feature...> [--name <definition>] [--option <key=value>]... [--dry-run] [--yes] [--no-install] [--json]";
22
41
  const optionChoices = {
23
42
  "cache.driver": {
24
43
  requires: "kv",
@@ -30,7 +49,6 @@ const optionChoices = {
30
49
  "sandboxTask.driver": { values: ["vercel"] },
31
50
  "workflow.driver": { values: ["openworkflow"] }
32
51
  };
33
- /** Option keys that select a provider or a store. A feature that sets one does not use the host default. */
34
52
  const providerKeys = ["driver", "store"];
35
53
  function selectsProvider(id, value, host) {
36
54
  if (!isRecord$1(value)) return false;
@@ -40,15 +58,12 @@ function selectsProvider(id, value, host) {
40
58
  }
41
59
  return providerKeys.some((key) => value[key] !== void 0);
42
60
  }
43
- /** How `host` supports `id`, with the override that `env` selects, such as BLOB_READ_WRITE_TOKEN for the Vercel Workspace. */
44
61
  function hostSupport(id, host, env) {
45
62
  const support = featureSupport(id, host);
46
63
  if (support.level !== "native") return support;
47
64
  return support.envOverrides?.find((override) => env[override.env]?.trim())?.support ?? support;
48
65
  }
49
- /** The value that turns a feature on, when `true` is not valid for its key. */
50
66
  const enabledValues = { env: {} };
51
- /** Keep owner packages on the running CLI's pkg.pr.new preview. */
52
67
  function installSpecifiers(packages) {
53
68
  const manifest = JSON.parse(readFileSync(new URL(import.meta.resolve("@vite-hub/cli/package.json")), "utf8"));
54
69
  const dependencies = isRecord$1(manifest) && isRecord$1(manifest.dependencies) ? manifest.dependencies : {};
@@ -60,19 +75,24 @@ function installSpecifiers(packages) {
60
75
  ref
61
76
  }] : [];
62
77
  })[0];
63
- return packages.map((name) => preview && name.startsWith("@vite-hub/") ? `${preview.base}/${name}@${preview.ref}` : name);
78
+ return packages.map((name) => preview && name.startsWith("@vite-hub/") ? `${preview.base}/${name}@${preview.ref}` : installSpecifier(name));
64
79
  }
65
- function invalid$2(message, commandUsage = usage$4) {
80
+ function invalid$3(message, commandUsage = usage$3) {
66
81
  return cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${message} Usage: ${commandUsage}` });
67
82
  }
68
83
  /** The feature id of a command argument, such as `rate-limit` for `rateLimit`. Throws `CLI_R0003` for an unknown feature. */
69
- function readFeatureId(value, commandUsage = usage$4) {
84
+ function readFeatureId(value, commandUsage = usage$3) {
70
85
  const key = value.replaceAll("-", "").toLowerCase();
71
86
  const id = featureIds.find((item) => item.toLowerCase() === key);
72
- if (!id) throw invalid$2(`Unknown feature ${JSON.stringify(value)}. Run \`vitehub catalog\` to list the features.`, commandUsage);
87
+ if (!id) throw invalid$3(`Unknown feature ${JSON.stringify(value)}. Run \`vitehub catalog\` to list the features.`, commandUsage);
73
88
  return id;
74
89
  }
75
- function optionValue(value) {
90
+ function optionValue(value, key) {
91
+ if (key === "i18n.locales" && value.trimStart().startsWith("[")) try {
92
+ return JSON.parse(value);
93
+ } catch {
94
+ throw invalid$3(`--option ${key} must contain a valid JSON array.`);
95
+ }
76
96
  if (value === "true" || value === "false" || value === "null" || /^-?\d+(?:\.\d+)?$/u.test(value)) return JSON.parse(value);
77
97
  return value;
78
98
  }
@@ -107,7 +127,7 @@ function readAddArgs(args) {
107
127
  const [flag, inline] = arg.startsWith("--") && arg.includes("=") ? [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)] : [arg, void 0];
108
128
  const value = () => {
109
129
  const next = inline ?? args[++index];
110
- if (next === void 0 || inline === void 0 && next.startsWith("--")) throw invalid$2(`${flag} needs a value.`);
130
+ if (next === void 0 || inline === void 0 && next.startsWith("--")) throw invalid$3(`${flag} needs a value.`);
111
131
  return next;
112
132
  };
113
133
  if (flag === "--json") parsed.json = true;
@@ -117,34 +137,29 @@ function readAddArgs(args) {
117
137
  else if (flag === "-h" || flag === "--help") parsed.help = true;
118
138
  else if (flag === "--name") parsed.name = value();
119
139
  else if (flag === "--option") rawOptions.push(value());
120
- else if (arg.startsWith("-")) throw invalid$2(`Unknown argument ${JSON.stringify(arg)}.`);
140
+ else if (arg.startsWith("-")) throw invalid$3(`Unknown argument ${JSON.stringify(arg)}.`);
121
141
  else if (!parsed.features.includes(readFeatureId(arg))) parsed.features.push(readFeatureId(arg));
122
142
  }
123
- if (parsed.name !== void 0 && !/^[a-z0-9][a-z0-9-]*$/u.test(parsed.name)) throw invalid$2(`--name ${JSON.stringify(parsed.name)} must use lowercase letters, digits, and dashes, such as \`welcome-email\`.`);
143
+ if (parsed.name !== void 0 && !/^[a-z0-9][a-z0-9-]*$/u.test(parsed.name)) throw invalid$3(`--name ${JSON.stringify(parsed.name)} must use lowercase letters, digits, and dashes, such as \`welcome-email\`.`);
124
144
  for (const option of rawOptions) {
125
145
  const separator = option.indexOf("=");
126
- if (separator <= 0) throw invalid$2(`--option ${JSON.stringify(option)} must be key=value, such as \`email.driver=resend\`.`);
146
+ if (separator <= 0) throw invalid$3(`--option ${JSON.stringify(option)} must be key=value, such as \`email.driver=resend\`.`);
127
147
  const path = option.slice(0, separator).split(".");
128
148
  const head = featureIds.find((id) => id === path[0]);
129
149
  const id = head ?? (parsed.features.length === 1 ? parsed.features[0] : void 0);
130
150
  const keys = head ? path.slice(1) : path;
131
- if (!id || !keys.length || keys.some((key) => !key)) throw invalid$2(`--option ${JSON.stringify(option)} must start with one of the features, such as \`${parsed.features[0] ?? "email"}.driver=resend\`.`);
132
- setPath(parsed.options[id] ??= {}, keys, optionValue(option.slice(separator + 1)));
151
+ if (!id || !keys.length || keys.some((key) => !key)) throw invalid$3(`--option ${JSON.stringify(option)} must start with one of the features, such as \`${parsed.features[0] ?? "email"}.driver=resend\`.`);
152
+ setPath(parsed.options[id] ??= {}, keys, optionValue(option.slice(separator + 1), `${id}.${keys.join(".")}`));
133
153
  }
134
154
  return parsed;
135
155
  }
136
- /** Quotes `value` for a POSIX shell when it needs quotes. */
137
- function shellQuote(value) {
138
- return /^[\w@%+=:,./-]+$/u.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
139
- }
140
156
  /** `value` as `--option` values under `prefix`, such as `["email.driver=resend"]`. */
141
157
  function flattenOptions(prefix, value, out = []) {
142
158
  if (isRecord$1(value)) for (const [key, child] of Object.entries(value)) flattenOptions(`${prefix}.${key}`, child, out);
143
159
  else out.push(`${prefix}=${value === null || typeof value !== "object" ? String(value) : JSON.stringify(value)}`);
144
160
  return out;
145
161
  }
146
- /** The `vitehub add` command for `args`, with `extra` options and `--yes` unless it is a dry run. */
147
- function rerunCommand$2(args, extra = {}, extraFeatures = []) {
162
+ function rerunCommand$1(args, extra = {}, extraFeatures = []) {
148
163
  const ids = [...args.features, ...extraFeatures.filter((id) => !args.features.includes(id))];
149
164
  const options = [.../* @__PURE__ */ new Set([
150
165
  ...ids,
@@ -188,10 +203,6 @@ function toSource(value) {
188
203
  function setupDiff(path, before, after) {
189
204
  return createTwoFilesPatch(before ? `a/${path}` : "/dev/null", after ? `b/${path}` : "/dev/null", before, after, void 0, void 0, { context: 3 }).replace(/^=+\n/u, "");
190
205
  }
191
- /**
192
- * The config value that `add` writes for `id`, `undefined` when the config already turns it on, or `expression` when
193
- * the key is an expression that only a person can edit.
194
- */
195
206
  function nextValue(id, status, project, options) {
196
207
  const current = project.config?.ok ? project.config.site.keys[id] : void 0;
197
208
  if (current?.kind === "expression") return "expression";
@@ -201,7 +212,8 @@ function nextValue(id, status, project, options) {
201
212
  return sameValue(literal, merged) ? void 0 : { value: merged };
202
213
  }
203
214
  /** Plans `vitehub add` without writing anything. Throws `SetupFailure` when the change needs input or is not possible. */
204
- async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
215
+ async function planSetupAdd(project, args, env, rerun = rerunCommand$1) {
216
+ if (args.options.observability && Object.hasOwn(args.options.observability, "logs")) throw setupFailure(cliErrorDiagnostics.SETUP_LOGS_OPTION_MOVED(), setupExitCodes.conflict);
205
217
  const status = setupStatus(project, env);
206
218
  const host = status.host.name;
207
219
  if (host === "unknown") {
@@ -223,6 +235,11 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
223
235
  feature: id,
224
236
  host
225
237
  }), setupExitCodes.conflict);
238
+ if (id === "email" && driver === "smtp" && host === "cloudflare") throw setupFailure(cliErrorDiagnostics.SETUP_FEATURE_UNSUPPORTED({
239
+ detail: "The \"smtp\" driver opens TCP connections with nodemailer, and Cloudflare Workers cannot run it. On Cloudflare, use the \"cloudflare\" or \"resend\" driver, or a driver module that sends over HTTP.",
240
+ feature: id,
241
+ host
242
+ }), setupExitCodes.conflict);
226
243
  if (support.level === "unsupported") throw setupFailure(cliErrorDiagnostics.SETUP_FEATURE_UNSUPPORTED({
227
244
  detail: support.detail,
228
245
  feature: id,
@@ -230,6 +247,7 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
230
247
  }), setupExitCodes.conflict);
231
248
  }
232
249
  const missing = [];
250
+ const inputFixes = [];
233
251
  const defaults = {};
234
252
  const requires = [];
235
253
  let rerunnable = true;
@@ -238,17 +256,16 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
238
256
  const current = project.config?.ok ? project.config.site.keys[id] : void 0;
239
257
  return mergeValue(current?.kind === "literal" ? current.value : void 0, args.options[id]);
240
258
  };
241
- const inputFeatures = [...args.features, ...impliedFeatures(args.features, host, keep.filter((id) => id !== "database"))];
259
+ const inputFeatures = [...args.features, ...impliedFeatures(args.features, keep.filter((id) => id !== "database"))];
242
260
  if (inputFeatures.includes("database") && keep.includes("database")) requires.push("database");
243
261
  const requireFeature = (required) => {
244
- for (const id of [required, ...impliedFeatures([required], host, keep.filter((id) => id !== "database"))]) {
262
+ for (const id of [required, ...impliedFeatures([required], keep.filter((id) => id !== "database"))]) {
245
263
  if (!inputFeatures.includes(id)) inputFeatures.push(id);
246
264
  if ((id === required || keep.includes(id)) && !args.features.includes(id) && !requires.includes(id) && status.features.find((item) => item.id === id)?.enabled !== "on") requires.push(id);
247
265
  }
248
266
  };
249
267
  for (const id of inputFeatures) {
250
268
  const support = featureSupport(id, host);
251
- const options = args.options[id];
252
269
  const current = project.config?.ok ? project.config.site.keys[id] : void 0;
253
270
  const value = valueFor(id);
254
271
  if (id === "observability" && isRecord$1(value) && value.papercuts) {
@@ -302,17 +319,16 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
302
319
  host
303
320
  }), setupExitCodes.conflict);
304
321
  if (invocations === "database" || isRecord$1(invocations) && invocations.store === "database") requireFeature("database");
305
- const inlineOnly = !args.features.includes(id) && !requires.includes(id) && impliedInline(id, inputFeatures, host);
306
322
  const storageSelected = id === "workflow" && host !== "netlify" && selectsProvider(id, value, host);
307
- if (support.level === "explicit" && !inlineOnly && !storageSelected) {
308
- const key = support.option.slice(id.length + 1);
309
- if (!(options && key in options) && !setsOption(project, support.option)) {
323
+ if (support.level === "explicit" && !storageSelected) {
324
+ const field = missingProviderOption(project, support.option, value);
325
+ if (field) {
310
326
  const choices = optionChoices[support.option];
311
327
  missing.push({
312
- field: support.option,
328
+ field,
313
329
  ...choices ? { choices: choices.values } : {}
314
330
  });
315
- if (choices) setPath(defaults[id] ??= {}, [key], choices.values[0]);
331
+ if (choices) setPath(defaults[id] ??= {}, field.split(".").slice(1), choices.values[0]);
316
332
  else rerunnable = false;
317
333
  }
318
334
  }
@@ -331,7 +347,7 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
331
347
  });
332
348
  setPath(defaults.schedule ??= {}, ["providerOutput"], "auto");
333
349
  }
334
- if (!isRecord$1(value) || !isRecord$1(value.runtime) || value.runtime.driver !== "process") {
350
+ if (isRecord$1(value) && value.runtime !== void 0 && (!isRecord$1(value.runtime) || value.runtime.driver !== "process")) {
335
351
  missing.push({
336
352
  choices: ["process"],
337
353
  field: "schedule.runtime.driver"
@@ -349,10 +365,68 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
349
365
  feature: "observability",
350
366
  host
351
367
  }), setupExitCodes.conflict);
352
- for (const id of Object.keys(args.options)) if (!inputFeatures.includes(id)) throw invalid$2(`${id} is not requested or required by ${args.features.join(", ")}.`);
368
+ for (const id of Object.keys(args.options)) if (!inputFeatures.includes(id)) throw invalid$3(`${id} is not requested or required by ${args.features.join(", ")}.`);
369
+ const site = project.config?.ok ? project.config.site : void 0;
370
+ if (inputFeatures.includes("i18n") && site?.keys.i18n?.kind !== "expression") {
371
+ const i18n = valueFor("i18n");
372
+ const problem = i18nLocaleListProblem(isRecord$1(i18n) ? i18n.locales : void 0);
373
+ if (problem) {
374
+ missing.push({ field: "i18n.locales" });
375
+ inputFixes.push(`${problem} Pass a nonempty JSON array, such as \`--option 'i18n.locales=["en","es"]'\`.`);
376
+ rerunnable = false;
377
+ }
378
+ }
379
+ const mcpOAuthSetup = "Include `mcpOAuth()` from `vite-hub/auth/mcp` in the `plugins` of `defineAuth()` in the Auth Definition";
380
+ let needsMcpOAuth = false;
381
+ if (inputFeatures.includes("mcp") && site?.keys.mcp?.kind !== "expression") {
382
+ const configuredAuth = site?.keys.auth;
383
+ const authStatus = status.features.find((item) => item.id === "auth");
384
+ const discoveredAuth = authStatus?.enabled === "on" && authStatus.reason === "default";
385
+ const selectedAuth = args.features.includes("auth") && (!configuredAuth || configuredAuth.kind === "expression" || configuredAuth.value === false);
386
+ const authEnabled = !args.options.auth && (selectedAuth || configuredAuth?.kind === "literal" && configuredAuth.value === true || discoveredAuth);
387
+ const mcp = valueFor("mcp");
388
+ const mode = isRecord$1(mcp) && Object.hasOwn(mcp, "auth") ? mcp.auth : void 0;
389
+ const publicRoute = isRecord$1(mcp) && typeof mcp.publicRoute === "string" ? mcp.publicRoute : void 0;
390
+ if ((typeof mode === "boolean" || mode === "optional") && mcpPublicRouteNeedsSignedAuth(publicRoute, mode)) {
391
+ missing.push({ field: "mcp.publicRoute" });
392
+ inputFixes.push("Remove `mcp.publicRoute`, or enable Auth, set `mcp.auth=true`, and add `mcpOAuth()` to the Auth Definition.");
393
+ rerunnable = false;
394
+ } else if (!authEnabled && authStatus?.enabled === "unknown" && (mode === void 0 || mode === true || mode === "optional")) {
395
+ const file = project.configFile ?? "vite.config.ts";
396
+ const snippet = `mcp: ${toSource(isRecord$1(mcp) ? mcp : true)},`;
397
+ const fix = `Confirm Auth is enabled in the app. ${mcpOAuthSetup}. Add this key to the vitehub() options by hand:\n${snippet}`;
398
+ throw setupFailure(cliErrorDiagnostics.SETUP_CONFIG_MANUAL({
399
+ file,
400
+ fix,
401
+ reason: "Auth cannot be determined statically"
402
+ }), setupExitCodes.conflict, { data: { snippet } });
403
+ } else if (mode === true || mode === "optional" || mode === void 0 && authEnabled) {
404
+ if (authEnabled) needsMcpOAuth = true;
405
+ else {
406
+ missing.push({ field: "auth" });
407
+ inputFixes.push(`Select the \`auth\` feature or enable Auth in the app config. ${mcpOAuthSetup}.`);
408
+ rerunnable = false;
409
+ }
410
+ } else if (mode !== false) {
411
+ missing.push({
412
+ choices: [
413
+ "true",
414
+ "optional",
415
+ "false"
416
+ ],
417
+ field: "mcp.auth"
418
+ });
419
+ inputFixes.push("Enable Auth for signed requests and use `mcp.auth=true` or `mcp.auth=optional`, or omit `mcp.auth` to require sign-in by default. Pass `--option mcp.auth=false` only when anyone may call every tool.");
420
+ rerunnable = false;
421
+ }
422
+ }
353
423
  if (missing.length) {
354
424
  const fields = missing.map((item) => `\`${item.field}\``).join(", ");
355
- throw setupFailure(cliErrorDiagnostics.SETUP_INPUT_NEEDED({ message: `[vitehub] Set ${fields} to add ${args.features.join(", ")} on the ${host} host.` }), setupExitCodes.inputNeeded, {
425
+ const fix = inputFixes.length ? inputFixes.join(" ") : void 0;
426
+ throw setupFailure(cliErrorDiagnostics.SETUP_INPUT_NEEDED({
427
+ fix,
428
+ message: `[vitehub] Set ${fields} to add ${args.features.join(", ")} on the ${host} host.`
429
+ }), setupExitCodes.inputNeeded, {
356
430
  missing,
357
431
  ...rerunnable ? { rerun: rerun(args, defaults, requires) } : {}
358
432
  });
@@ -363,6 +437,7 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
363
437
  for (const id of /* @__PURE__ */ new Set([...addedFeatures, ...inputFeatures.filter((id) => args.options[id])])) {
364
438
  const next = nextValue(id, status, project, args.options[id]);
365
439
  expression ||= next === "expression";
440
+ if (next !== "expression" && next?.value === true && site && !site.spread && !site.keys[id] && args.name !== void 0 && args.features.includes(id) && features[id].definition && features[id].enabledByDiscovery) continue;
366
441
  if (next !== void 0) edits.push({
367
442
  key: id,
368
443
  op: "set",
@@ -371,13 +446,14 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
371
446
  }
372
447
  const changes = [];
373
448
  const files = [];
449
+ let addsDiscovery = false;
374
450
  let configFile;
375
451
  const serverDir = relative(project.root, project.serverDirs?.[0] ?? join(project.root, "server"));
376
452
  const nuxtRoot = project.config?.ok ? project.config.site.nuxt?.keys.rootDir : void 0;
377
453
  const definitionRoot = nuxtRoot?.kind === "literal" && typeof nuxtRoot.value === "string" ? resolve(project.root, nuxtRoot.value) : project.root;
378
454
  if (args.name !== void 0) {
379
455
  const withStarter = args.features.filter((id) => features[id].definition);
380
- if (!withStarter.length) throw invalid$2(`${args.features.join(", ")} has no Definition files, so --name has no effect. Features with Definitions: ${featureIds.filter((id) => features[id].definition).join(", ")}.`);
456
+ if (!withStarter.length) throw invalid$3(`${args.features.join(", ")} has no Definition files, so --name has no effect. Features with Definitions: ${featureIds.filter((id) => features[id].definition).join(", ")}.`);
381
457
  if (project.framework === "nuxt" && !project.serverDirs?.length) throw setupFailure(cliErrorDiagnostics.SETUP_SERVER_DIR_MANUAL(), setupExitCodes.conflict);
382
458
  for (const id of withStarter) {
383
459
  const starter = features[id].definition;
@@ -404,6 +480,8 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
404
480
  kind: "create",
405
481
  path
406
482
  });
483
+ const previous = status.features.find((item) => item.id === id);
484
+ if (features[id].enabledByDiscovery && site && !site.spread && !site.keys[id] && (previous?.enabled !== "on" || previous.reason === "implied")) addsDiscovery = true;
407
485
  }
408
486
  }
409
487
  if (edits.length) {
@@ -433,7 +511,7 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
433
511
  });
434
512
  }
435
513
  const alreadyOn = new Set(status.features.filter((item) => item.enabled === "on").map((item) => item.id));
436
- const implied = impliedFeatures([.../* @__PURE__ */ new Set([...alreadyOn, ...addedFeatures])], host, keep.filter((id) => !requires.includes(id))).filter((id) => !addedFeatures.includes(id));
514
+ const implied = impliedFeatures([.../* @__PURE__ */ new Set([...alreadyOn, ...addedFeatures])], keep.filter((id) => !requires.includes(id))).filter((id) => !addedFeatures.includes(id));
437
515
  const enabled = /* @__PURE__ */ new Set([
438
516
  ...alreadyOn,
439
517
  ...addedFeatures,
@@ -453,14 +531,29 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
453
531
  install.prod = installSpecifiers(install.prod);
454
532
  install.dev = installSpecifiers(install.dev);
455
533
  const command = installCommand(project.packageManager, install.prod, install.dev);
456
- const nextSteps = [];
534
+ const restartRequired = addsDiscovery && !configFile;
535
+ const nextSteps = restartRequired ? ["Restart the dev server to load the new feature configuration."] : [];
536
+ if (needsMcpOAuth) {
537
+ const [appServerDir, ...layers] = project.serverDirs ?? [];
538
+ const authFiles = features.auth.enabledByDiscovery ?? [];
539
+ const appFiles = appServerDir ? authFiles.map((name) => join(appServerDir, name)) : [];
540
+ const definition = appServerDir && [
541
+ ...appFiles,
542
+ ...authFiles.map((name) => join(definitionRoot, `server.${name}`)),
543
+ ...layers.flatMap((dir) => authFiles.map((name) => join(dir, name)))
544
+ ].find(existsSync);
545
+ const target = definition ? ` in \`${relative(project.root, definition)}\`` : "";
546
+ if (!definition && appServerDir) nextSteps.push(`Create an Auth Definition at \`${join(serverDir, "auth.ts")}\` if the app has none.`);
547
+ nextSteps.push(`${mcpOAuthSetup}${target}. https://vitehub.dev/docs/mcp/configure#sign-in-with-mcp-oauth`);
548
+ }
457
549
  if (command && !args.install) nextSteps.push(`Install the packages: ${command}`);
458
550
  for (const id of implied) {
459
551
  const support = featureSupport(id, host);
460
552
  if (support.level === "unsupported") nextSteps.push(`${id} is turned on by ${args.features.join(", ")} but is not supported on ${host}: ${support.detail} Set \`${id}: false\` to turn it off.`);
461
- else if (support.level === "explicit" && impliedInline(id, [...enabled], host)) {
462
- if (!selectsProvider(id, valueFor(id), host) && !setsOption(project, support.option)) nextSteps.push(`${features[id].title} that ${args.features.join(", ")} turns on runs inline in the request process on ${host}, and a restart loses its runs. Set \`${support.option}\` for durable runs. ${support.detail}`);
463
- } else if (support.level === "explicit" && !setsOption(project, support.option) && !(args.options[id] && support.option.slice(id.length + 1) in args.options[id])) nextSteps.push(`${id} is turned on by ${args.features.join(", ")}. Set \`${support.option}\` on ${host}, or set \`${id}: false\`. ${support.detail}`);
553
+ else if (support.level === "explicit") {
554
+ const option = missingProviderOption(project, support.option, valueFor(id));
555
+ if (option) nextSteps.push(`${id} is turned on by ${args.features.join(", ")}. Set \`${option}\` on ${host}, or set \`${id}: false\`. ${support.detail}`);
556
+ }
464
557
  }
465
558
  for (const id of [...addedFeatures, ...implied]) {
466
559
  if (selectsProvider(id, valueFor(id))) continue;
@@ -488,6 +581,7 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
488
581
  root: project.root,
489
582
  status: changes.length || command && args.install ? "planned" : "unchanged"
490
583
  },
584
+ restartRequired,
491
585
  ...configFile ? { configFile } : {}
492
586
  };
493
587
  }
@@ -503,7 +597,7 @@ async function applySetupAdd(project, planned, args, context) {
503
597
  stdout: "stderr"
504
598
  });
505
599
  if (result.exitCode !== 0) throw setupFailure(cliErrorDiagnostics.SETUP_INSTALL_FAILED({
506
- command: [project.packageManager, ...commandArgs].join(" "),
600
+ command: formatInstallCommand(project.packageManager, commandArgs),
507
601
  exitCode: result.exitCode ?? result.signal
508
602
  }), setupExitCodes.error);
509
603
  }
@@ -549,7 +643,7 @@ async function runAdd(args, context) {
549
643
  try {
550
644
  parsed = readAddArgs(args);
551
645
  if (parsed.help) {
552
- context.stdout.write(`Usage: ${usage$4}\n\n${addCommand.description}\n`);
646
+ context.stdout.write(`Usage: ${usage$3}\n\n${addCommand.description}\n`);
553
647
  return setupExitCodes.done;
554
648
  }
555
649
  if (!parsed.features.length) throw setupFailure(cliErrorDiagnostics.SETUP_INPUT_NEEDED({ message: "[vitehub] Name at least one feature, such as `vitehub add kv`." }), setupExitCodes.inputNeeded, { missing: [{
@@ -570,7 +664,7 @@ async function runAdd(args, context) {
570
664
  if (!parsed.json) writePlan$2(plan, context);
571
665
  throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] `vitehub add` changes files and was not confirmed. Without a terminal, pass --yes." }), setupExitCodes.inputNeeded, {
572
666
  data: plan,
573
- rerun: rerunCommand$2(parsed)
667
+ rerun: rerunCommand$1(parsed)
574
668
  });
575
669
  }
576
670
  writePlan$2(plan, context);
@@ -593,7 +687,7 @@ const addCommand = {
593
687
  description: "Turn on features: edit vitehub() options, install packages, and create starter Definitions. Reads the config without running it.",
594
688
  name: "add",
595
689
  run: runAdd,
596
- usage: usage$4
690
+ usage: usage$3
597
691
  };
598
692
  //#endregion
599
693
  //#region src/setup/catalog.ts
@@ -606,1132 +700,166 @@ function setupCatalog() {
606
700
  };
607
701
  }
608
702
  //#endregion
609
- //#region src/setup/deploy/after.ts
610
- /** Waits between the attempts of one path: a new version can take a few seconds to reach every edge location. */
611
- const checkRetryDelaysMs = [
612
- 1e3,
613
- 2e3,
614
- 4e3
615
- ];
616
- const checkTimeoutMs = 1e4;
617
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
618
- function reason(error) {
619
- if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) return `no answer within ${checkTimeoutMs / 1e3} seconds`;
620
- return error instanceof Error ? error.cause instanceof Error ? error.cause.message : error.message : String(error);
621
- }
622
- /**
623
- * Requests each path on the deployed URL until it answers with a 2xx status, with a few retries. Redirects are
624
- * followed, so the final answer counts. The request asks the cache to skip, so a cached answer of the previous version
625
- * does not pass the check.
626
- */
627
- async function runDeployChecks(baseUrl, paths, fetchImpl, delays = checkRetryDelaysMs) {
628
- const origin = new URL(baseUrl);
629
- return await Promise.all(paths.map(async (path) => {
630
- const url = new URL(path, origin).href;
631
- let last = {
632
- ok: false,
633
- path,
634
- url
635
- };
636
- for (let attempt = 0; attempt <= delays.length; attempt++) {
637
- if (attempt) await sleep(delays[attempt - 1]);
638
- try {
639
- const response = await fetchImpl(url, {
640
- cache: "no-store",
641
- headers: {
642
- "cache-control": "no-cache",
643
- "user-agent": "vitehub-deploy-check"
644
- },
645
- redirect: "follow",
646
- signal: AbortSignal.timeout(checkTimeoutMs)
647
- });
648
- await response.body?.cancel();
649
- last = {
650
- ok: response.ok,
651
- path,
652
- status: response.status,
653
- url
654
- };
655
- } catch (error) {
656
- last = {
657
- error: reason(error),
658
- ok: false,
659
- path,
660
- url
661
- };
662
- }
663
- if (last.ok) break;
664
- }
665
- return last;
666
- }));
667
- }
668
- /** One line per failed check, such as `/api/health: 503` or `/: fetch failed`. */
669
- function formatFailedChecks(checks) {
670
- return checks.filter((check) => !check.ok).map((check) => `${check.path}: ${check.status ?? check.error ?? "no answer"}`).join(", ");
671
- }
672
- function quote(value) {
673
- return /^[\w./:@=-]+$/u.test(value) ? value : `'${value.replaceAll("'", "'\\''")}'`;
674
- }
675
- /**
676
- * The rollback of each host, from its CLI help in test/fixtures/host-cli-help/:
677
- * - Wrangler 4.158 `wrangler rollback <version-id> --name <worker> --yes`.
678
- * - Vercel CLI 65.16 `vercel rollback <deployment> --yes`.
679
- * - Netlify CLI 27.11 `netlify api restoreSiteDeploy`, the `POST /sites/{site_id}/deploys/{deploy_id}/restore` API.
680
- * - Deno Deploy CLI 0.0.9909 has no rollback command.
681
- */
682
- function rollbackFor(host, input) {
683
- const { previous } = input;
684
- if (!previous) return { note: input.lookupFailed ? `The previous production deployment is not known: ${input.lookupFailed} Run \`vitehub deployments\` to find it.` : "This was the first production deploy, so there is no earlier deployment to roll back to." };
685
- const described = {
686
- deploymentId: previous.id,
687
- ...previous.version ? { version: previous.version } : {}
688
- };
689
- switch (host) {
690
- case "cloudflare": return {
691
- command: `npx wrangler rollback ${quote(previous.version ?? previous.id)} --name ${quote(input.projectName)} --yes`,
692
- previous: described
693
- };
694
- case "vercel": return {
695
- command: `npx vercel rollback ${quote(previous.id)} --yes`,
696
- previous: described
697
- };
698
- case "netlify": return input.siteId ? {
699
- command: `npx netlify api restoreSiteDeploy --data ${quote(JSON.stringify({
700
- deploy_id: previous.id,
701
- site_id: input.siteId
702
- }))}`,
703
- previous: described
704
- } : {
705
- note: `Publish deploy ${previous.id} again in the Netlify dashboard, under Deploys.`,
706
- previous: described
707
- };
708
- case "deno": return {
709
- note: `The Deno Deploy CLI has no rollback command. Promote revision ${previous.id} to production in the Deno Deploy dashboard.`,
710
- previous: described
711
- };
712
- }
713
- }
714
- const xmlEntities = {
715
- amp: "&",
716
- apos: "'",
717
- gt: ">",
718
- lt: "<",
719
- quot: "\""
720
- };
721
- /** Text of an XML element: CDATA kept as it is, named and numeric character references decoded. */
722
- function decodeXml(text) {
723
- return text.split(/(<!\[CDATA\[[\s\S]*?\]\]>)/u).map((part) => part.startsWith("<![CDATA[") ? part.slice(9, -3) : part.replace(/&(?:#x([\da-f]+)|#(\d+)|(amp|lt|gt|quot|apos));/giu, (match, hex, decimal, name) => {
724
- if (name) return xmlEntities[name];
725
- const code = hex ? Number.parseInt(hex, 16) : Number(decimal);
726
- return code <= 1114111 ? String.fromCodePoint(code) : match;
727
- })).join("").trim();
728
- }
729
- function locations(xml) {
730
- return [...xml.matchAll(/<loc>([\s\S]*?)<\/loc>/gu)].map((match) => decodeXml(match[1])).filter(Boolean);
731
- }
732
- /** IndexNow takes at most 10,000 URLs in one request. */
733
- const indexNowBatch = 1e4;
734
- /** A sitemap index may list sitemaps on other paths. Read at most this many. */
735
- const nestedSitemapLimit = 50;
736
- /**
737
- * Reads `<url>/sitemap.xml`, one level of a sitemap index included, and sends every URL of the site to IndexNow.
738
- * https://www.indexnow.org/documentation: 200 and 202 accept the URLs, 403 means the key file was not found.
739
- */
740
- async function submitIndexNow(indexNow, fetchImpl) {
741
- const origin = new URL(indexNow.url);
742
- const read = async (url) => {
743
- const response = await fetchImpl(url, {
744
- headers: { "user-agent": "vitehub-deploy" },
745
- signal: AbortSignal.timeout(checkTimeoutMs)
746
- });
747
- if (!response.ok) throw Object.assign(/* @__PURE__ */ new Error(`${url} answered ${response.status}.`), { status: response.status });
748
- return await response.text();
749
- };
750
- const sameSite = (url) => URL.canParse(url) && new URL(url).origin === origin.origin;
751
- let urls;
752
- try {
753
- const sitemap = await read(new URL("/sitemap.xml", origin).href);
754
- urls = /<sitemapindex[\s>]/u.test(sitemap) ? (await Promise.all(locations(sitemap).filter(sameSite).slice(0, nestedSitemapLimit).map(read))).flatMap(locations) : locations(sitemap);
755
- } catch (error) {
756
- const status = error instanceof Error ? Reflect.get(error, "status") : void 0;
757
- return {
758
- error: `The sitemap could not be read: ${reason(error)}`,
759
- ...typeof status === "number" ? { status } : {}
760
- };
761
- }
762
- const urlList = [...new Set(urls.filter(sameSite))];
763
- if (!urlList.length) return { error: `${origin.origin}/sitemap.xml lists no URL of ${origin.host}.` };
764
- let status = 0;
765
- for (let start = 0; start < urlList.length; start += indexNowBatch) {
766
- const response = await fetchImpl("https://api.indexnow.org/indexnow", {
767
- body: JSON.stringify({
768
- host: origin.host,
769
- key: indexNow.key,
770
- keyLocation: `${origin.origin}/${indexNow.key}.txt`,
771
- urlList: urlList.slice(start, start + indexNowBatch)
772
- }),
773
- headers: { "content-type": "application/json; charset=utf-8" },
774
- method: "POST",
775
- signal: AbortSignal.timeout(checkTimeoutMs)
776
- }).catch((error) => error instanceof Error ? error : new Error(String(error)));
777
- if (response instanceof Error) return { error: `IndexNow did not answer: ${reason(response)}` };
778
- await response.body?.cancel();
779
- status = response.status;
780
- if (status === 403) return {
781
- error: `IndexNow did not find the key file at ${origin.origin}/${indexNow.key}.txt.`,
782
- status
783
- };
784
- if (!response.ok) return {
785
- error: `IndexNow answered ${status}.`,
786
- status
787
- };
788
- }
789
- return {
790
- status,
791
- submitted: urlList.length
792
- };
793
- }
794
- //#endregion
795
- //#region src/setup/deploy/checkouts.ts
796
- /** The lock file of `vitehub pull` and `vitehub push`, at the project root. */
797
- const lockFile = "vitehub.lock";
798
- function isCheckoutModule(value) {
799
- return Object(value) === value && typeof Reflect.get(Object(value), "localCheckoutStatus") === "function" && typeof Reflect.get(Object(value), "pullWorkspaces") === "function" && typeof Reflect.get(Object(value), "pushWorkspaces") === "function";
800
- }
801
- /** The checkout module of the Workspace package. */
802
- const checkoutSpecifiers = ["@vite-hub/workspace/checkout", "vite-hub/workspace/checkout"];
803
- /** True when `specifier` itself does not resolve: the package is not installed, or it has no `./checkout` export. */
804
- function isNotInstalled(error, specifier) {
805
- const code = error instanceof Error ? Reflect.get(error, "code") : void 0;
806
- if (code === "ERR_PACKAGE_PATH_NOT_EXPORTED") return true;
807
- return code === "MODULE_NOT_FOUND" && error instanceof Error && error.message.includes(`'${specifier}'`);
808
- }
809
- /**
810
- * The checkout module of the Workspace package that the project installs. Undefined only when no specifier resolves.
811
- * A module that resolves but does not load stops the deploy, because a silent skip would deploy without the push.
812
- */
813
- async function importCheckoutModule(root) {
814
- const require = createRequire(join(root, "package.json"));
815
- for (const specifier of checkoutSpecifiers) {
816
- let file;
817
- try {
818
- file = require.resolve(specifier);
819
- } catch (error) {
820
- if (isNotInstalled(error, specifier)) continue;
821
- throw moduleFailure(specifier, specifier, error);
822
- }
823
- let module;
824
- try {
825
- module = await import(pathToFileURL(file).href);
826
- } catch (error) {
827
- throw moduleFailure(specifier, file, error);
828
- }
829
- if (!isCheckoutModule(module)) throw moduleFailure(specifier, file, /* @__PURE__ */ new TypeError("It does not export localCheckoutStatus, pullWorkspaces and pushWorkspaces."));
830
- return module;
831
- }
832
- }
833
- function moduleFailure(specifier, file, error) {
834
- const message = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
835
- return setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_CHECKOUT_MODULE_FAILED({
836
- file,
837
- message,
838
- specifier
839
- }), setupExitCodes.error);
840
- }
841
- /**
842
- * True when `vitehub.lock` lists at least one checkout folder. False without a lock. A lock that is not JSON, such as
843
- * one with a Git conflict, counts, so the checkout module reports it.
844
- */
845
- async function lockHasCheckouts(root) {
846
- let source;
703
+ //#region src/setup/stack.ts
704
+ function replayOption(id, keys, value) {
705
+ if (keys.some((key) => !key || /[.=\0]/u.test(key) || [
706
+ "__proto__",
707
+ "constructor",
708
+ "prototype"
709
+ ].includes(key))) return;
710
+ const raw = typeof value === "object" ? JSON.stringify(value) : String(value);
711
+ if (raw.includes("\0")) return;
712
+ const flag = `${id}.${keys.join(".")}=${raw}`;
847
713
  try {
848
- source = await readFile(join(root, lockFile), "utf8");
849
- } catch (error) {
850
- if (error instanceof Error && Reflect.get(error, "code") === "ENOENT") return false;
851
- throw error;
852
- }
853
- let lock;
854
- try {
855
- lock = JSON.parse(source);
714
+ const parsed = readAddArgs([
715
+ id,
716
+ "--option",
717
+ flag
718
+ ]).options[id];
719
+ const expected = keys.reduceRight((child, key) => ({ [key]: child }), value);
720
+ if (isDeepStrictEqual(parsed, expected)) return flag;
856
721
  } catch {
857
- return true;
858
- }
859
- const workspaces = Object(lock) === lock ? Reflect.get(Object(lock), "workspaces") : void 0;
860
- return Object(workspaces) === workspaces && Object.keys(Object(workspaces)).length > 0;
861
- }
862
- /**
863
- * Pulls the checkout folders of `vitehub.lock` before the build. Undefined when the project has no lock file,
864
- * no checkout, or no Workspace package to read them: then deploy does not push. Without a checkout, deploy does not
865
- * load the Workspace package. Without the package, a lock with checkouts gets one warning on `stderr`. Throws when the
866
- * package does not load, the pull fails, or a checkout has an open conflict before or after the pull.
867
- */
868
- async function prepareDeployCheckouts(root, context) {
869
- if (!await lockHasCheckouts(root)) return void 0;
870
- const module = await importCheckoutModule(root);
871
- if (!module) {
872
- context.stderr.write("[vitehub] vitehub.lock has checkout folders, but the deploy does not push them because the Workspace package is not installed. Install @vite-hub/workspace or vite-hub.\n");
873
722
  return;
874
723
  }
875
- const statuses = await module.localCheckoutStatus(root);
876
- if (!statuses?.length) return void 0;
877
- assertNoConflicts(statuses);
878
- const before = await readLock(root);
879
- const pulled = await module.pullWorkspaces(checkoutContext(root, context));
880
- assertNoConflicts(await module.localCheckoutStatus(root) ?? []);
881
- return {
882
- before,
883
- module,
884
- pulls: new Map(pulled.map((result) => [result.workspace, result])),
885
- root,
886
- statuses
887
- };
888
- }
889
- function assertNoConflicts(statuses) {
890
- const conflicts = statuses.flatMap((status) => status.local.conflicted.map((path) => `${status.dir}/${path}`));
891
- if (conflicts.length) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_CHECKOUT_CONFLICT({ files: conflicts.join(", ") }), setupExitCodes.error);
892
- }
893
- async function readLock(root) {
894
- return await readFile(join(root, lockFile), "utf8").catch(() => void 0);
895
- }
896
- function checkoutContext(root, context) {
897
- const call = async (operation, input, remote) => await callOperationFromCli({
898
- env: context.env,
899
- ...context.fetch ? { fetch: context.fetch } : {},
900
- rootDir: root,
901
- timeout: 12e4,
902
- ...remote ? { url: remote } : {}
903
- }, operation, input);
904
- return {
905
- call,
906
- rootDir: root
907
- };
908
- }
909
- /**
910
- * Pushes every checkout folder, as `vitehub push` does. The `remote` of each lock entry decides where it goes. Returns
911
- * the results and the files changed since the pre-build pull: `vitehub.lock`, and the files that either pull wrote.
912
- */
913
- async function pushDeployCheckouts(checkouts, context) {
914
- const results = (await checkouts.module.pushWorkspaces(checkoutContext(checkouts.root, context))).map((result) => {
915
- const before = checkouts.pulls.get(result.workspace);
916
- return before ? {
917
- ...result,
918
- pull: {
919
- ...result.pull,
920
- files: [...before.files, ...result.pull.files],
921
- from: before.from
922
- }
923
- } : result;
924
- });
925
- const dirs = new Map(checkouts.statuses.map((status) => [status.workspace, status.dir]));
926
- const pulled = results.flatMap((result) => [...result.pull.files, ...result.after?.files ?? []].filter((file) => file.action !== "kept").map((file) => `${dirs.get(result.workspace) ?? result.workspace}/${file.path}`));
927
- return {
928
- changed: [.../* @__PURE__ */ new Set([...checkouts.before === await readLock(checkouts.root) ? [] : [lockFile], ...pulled])],
929
- results
930
- };
931
- }
932
- /** The code, message, and fix of a failed push, as `vitehub push --json` prints them. */
933
- function checkoutPushError(error) {
934
- const code = error instanceof Error ? Reflect.get(error, "code") : void 0;
935
- const fix = error instanceof Error ? Reflect.get(error, "fix") : void 0;
936
- return {
937
- code: typeof code === "string" ? code : "WORKSPACE_CHECKOUT_FAILED",
938
- message: error instanceof Error ? error.message : String(error),
939
- ...typeof fix === "string" ? { fix } : {}
940
- };
941
- }
942
- function formatPull(result, workspace) {
943
- if (result.from === result.head && !result.files.length) return "";
944
- const lines = [`${workspace}: pulled ${result.ref} ${result.from ?? "(empty)"} -> ${result.head ?? "(empty)"}`];
945
- for (const file of result.files) lines.push(` ${file.action.padEnd(8)} ${file.path}${file.note ? `\n ${file.note}` : ""}`);
946
- return `${lines.join("\n")}\n`;
947
- }
948
- /** The text of `vitehub push`, then the files to commit. */
949
- function formatDeployCheckouts(pushed) {
950
- const text = pushed.results.map((result) => {
951
- const pulled = formatPull(result.pull, result.workspace);
952
- if (!result.revision) return `${pulled}${result.workspace}: nothing to push.\n`;
953
- return `${pulled}${result.workspace}: pushed ${result.pushed.length} ${result.pushed.length === 1 ? "file" : "files"} to ${result.ref} (${result.revision})\n${result.pushed.map((path) => ` ${path}`).join("\n")}\n${result.after ? formatPull(result.after, result.workspace) : ""}`;
954
- }).join("");
955
- if (!pushed.changed.length) return text;
956
- return `${text}The push changed these files. Commit them:\n${pushed.changed.map((path) => ` ${path}`).join("\n")}\n`;
957
724
  }
958
- //#endregion
959
- //#region src/setup/deployments.ts
960
- const usage$3 = "vitehub deployments [--host <host>] [--limit <n>] [--json]";
961
- const listers = {
962
- cloudflare: listCloudflareDeployments,
963
- deno: listDenoDeployments,
964
- netlify: listNetlifyDeployments,
965
- vercel: listVercelDeployments
966
- };
967
- /** How long `vitehub deployments` waits for the host. */
968
- const DEPLOYMENTS_TIMEOUT_MS = 3e4;
969
- /** How long `vitehub status` waits for the host before it reports `liveReason: "timeout"`. */
970
- const STATUS_HOST_TIMEOUT_MS = 5e3;
971
- /** A fetch that gives up after `ms`, so a slow host cannot hold the command. */
972
- function fetchWithTimeout(fetchImpl, ms, signal) {
973
- return async (input, init) => {
974
- signal?.throwIfAborted();
975
- return await fetchImpl(input, {
976
- ...init,
977
- signal: signal ?? AbortSignal.timeout(ms)
978
- });
979
- };
725
+ function credentialKey(key) {
726
+ return /(?:token|secret|password|passphrase|apikey|privatekey|accesskey(?:id)?|connectionstring|credentials?|authorization|cookie|dsn)$/iu.test(key.replaceAll(/[-_]/gu, "")) || /^(?:pass|auth|headers)$/iu.test(key);
980
727
  }
981
- function deploymentsContext(root, link, credentials, context, run, timeoutMs, signal) {
982
- return {
983
- credentials,
984
- env: context.env,
985
- fetch: fetchWithTimeout(context.fetch ?? globalThis.fetch, timeoutMs, signal),
986
- link,
987
- root,
988
- run: signal ? (command, args, options) => run(command, args, {
989
- ...options,
990
- signal
991
- }) : run,
992
- timeoutMs
993
- };
994
- }
995
- function readLimit(value) {
996
- if (value === void 0) return 10;
997
- const limit = Number(value);
998
- if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] --limit must be a whole number from 1 to 100, not ${JSON.stringify(value)}. Usage: ${usage$3}` });
999
- return limit;
1000
- }
1001
- function readDeploymentsArgs(args) {
1002
- try {
1003
- const { values } = parseArgs({
1004
- args: [...args],
1005
- options: {
1006
- help: {
1007
- short: "h",
1008
- type: "boolean",
1009
- default: false
1010
- },
1011
- host: { type: "string" },
1012
- json: {
1013
- type: "boolean",
1014
- default: false
1015
- },
1016
- limit: { type: "string" }
1017
- },
1018
- strict: true
1019
- });
1020
- return {
1021
- help: values.help,
1022
- host: readLinkHostOption(values.host),
1023
- json: values.json,
1024
- limit: readLimit(values.limit)
1025
- };
1026
- } catch (error) {
1027
- if (isSetupFailure(error) || error instanceof Error && "why" in error) throw error;
1028
- throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${error instanceof Error ? error.message : String(error)} Usage: ${usage$3}` });
728
+ function containsCredentials(value) {
729
+ if (typeof value === "string") {
730
+ const url = URL.parse(value.startsWith("//") ? `https:${value}` : value);
731
+ return !!(url && (url.username || url.password || url.search || url.hash));
1029
732
  }
733
+ if (Array.isArray(value)) return value.some(containsCredentials);
734
+ return isRecord$1(value) && Object.entries(value).some(([key, child]) => credentialKey(key) || containsCredentials(child));
1030
735
  }
1031
- function shortCommit(commit) {
1032
- return commit ? `${commit.sha.slice(0, 7)}${commit.dirty ? " (dirty)" : ""}` : "-";
1033
- }
1034
- function writeDeployments(output, context) {
1035
- if (!output.deployments.length) {
1036
- context.stdout.write(`${output.project.name} on ${output.host} has no deployments.\n`);
1037
- return;
1038
- }
1039
- context.stdout.write(`${table([[
1040
- "",
1041
- "id",
1042
- "target",
1043
- "state",
1044
- "commit",
1045
- "created",
1046
- "url"
1047
- ], ...output.deployments.map((item) => [
1048
- item.live ? "live" : "",
1049
- item.id,
1050
- item.target,
1051
- item.state,
1052
- shortCommit(item.commit),
1053
- item.createdAt,
1054
- item.url ?? "-"
1055
- ])])}\n`);
1056
- }
1057
- async function runDeployments(host, limit, json, context) {
1058
- const project = await readSetupProject(context.rootDir, context.env);
1059
- const selected = selectSetupLink(await readSetupLinks(project.root), host);
1060
- if ("ambiguous" in selected) throw hostRequired(selected.ambiguous, "vitehub deployments");
1061
- const link = selected.link;
1062
- if (!link) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOYMENTS_NOT_LINKED({ host }), setupExitCodes.inputNeeded, {
1063
- missing: [{ field: "link" }],
1064
- rerun: host ? `vitehub link --host ${host}` : "vitehub link"
1065
- });
1066
- const credentials = await resolveHostCredentials(link.host, {
1067
- cwd: project.root,
1068
- env: context.env,
1069
- ...context.runHostCli ? { run: context.runHostCli } : {}
1070
- });
1071
- if (!credentials.ok) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOYMENTS_CREDENTIALS_MISSING({
1072
- fix: credentials.fix,
1073
- host: link.host
1074
- }), setupExitCodes.inputNeeded, { missing: credentials.missing.map((field) => ({ field })) });
1075
- const run = createDeployRun(context.stderr, []);
1076
- const output = {
1077
- deployments: await listers[link.host](deploymentsContext(project.root, link, credentials, context, run, DEPLOYMENTS_TIMEOUT_MS), { limit }),
1078
- host: link.host,
1079
- project: link.project
736
+ function setupStackLabels(stack) {
737
+ return {
738
+ command: stack.command ?? "Unavailable",
739
+ omissions: stack.omits.map(({ path, reason }) => `${path} (${reason})`).join(", ")
1080
740
  };
1081
- if (json) writeSetupJson(context, output);
1082
- else writeDeployments(output, context);
1083
- return setupExitCodes.done;
1084
741
  }
1085
- const deploymentsCommand = {
1086
- description: "List the deployments of the linked project, read from the host each time. Marks the one that receives production traffic. --host picks a linked host other than the default.",
1087
- name: "deployments",
1088
- run: async (args, context) => {
1089
- const json = args.includes("--json");
1090
- try {
1091
- const parsed = readDeploymentsArgs(args);
1092
- if (parsed.help) {
1093
- context.stdout.write(`Usage: ${usage$3}\n\n${deploymentsCommand.description}\n`);
1094
- return setupExitCodes.done;
1095
- }
1096
- return await runDeployments(parsed.host, parsed.limit, parsed.json, context);
1097
- } catch (error) {
1098
- return writeSetupError(context, json, error);
742
+ async function deriveSetupStack(project, status, validate) {
743
+ const site = project.config?.ok ? project.config.site : void 0;
744
+ const omits = [];
745
+ const options = [];
746
+ const selected = [];
747
+ const collect = (id, keys, value) => {
748
+ const path = [id, ...keys].join(".");
749
+ if (!(path === "mcp.auth" && keys.length === 1 && (typeof value === "boolean" || value === "optional")) && keys.some(credentialKey)) {
750
+ omits.push({
751
+ path,
752
+ reason: "credential-option"
753
+ });
754
+ return;
1099
755
  }
1100
- },
1101
- usage: usage$3
1102
- };
1103
- /**
1104
- * Compares the live commit with HEAD: `git rev-list --left-right --count <sha>...HEAD` prints the commits that only
1105
- * the deployment has, then the commits that only HEAD has.
1106
- */
1107
- async function compareWithHead(run, root, env, sha) {
1108
- const git = async (args) => {
1109
- try {
1110
- return await run("git", args, {
1111
- cwd: root,
1112
- env,
1113
- timeoutMs: STATUS_HOST_TIMEOUT_MS
756
+ if (isRecord$1(value) && Object.keys(value).length) {
757
+ for (const [key, child] of Object.entries(value)) collect(id, [...keys, key], child);
758
+ return;
759
+ }
760
+ if (containsCredentials(value)) {
761
+ omits.push({
762
+ path,
763
+ reason: "credential-option"
1114
764
  });
1115
- } catch {
1116
765
  return;
1117
766
  }
767
+ const flag = keys.length ? replayOption(id, keys, value) : void 0;
768
+ if (flag === void 0) omits.push({
769
+ path,
770
+ reason: "non-replayable-option"
771
+ });
772
+ else options.push(flag);
1118
773
  };
1119
- const inside = await git(["rev-parse", "--is-inside-work-tree"]);
1120
- if (inside?.exitCode !== 0 || inside.stdout.trim() !== "true") return { unknownReason: "no-git" };
1121
- if ((await git([
1122
- "cat-file",
1123
- "-e",
1124
- `${sha}^{commit}`
1125
- ]))?.exitCode !== 0) return { unknownReason: "commit-not-local" };
1126
- const counts = await git([
1127
- "rev-list",
1128
- "--left-right",
1129
- "--count",
1130
- `${sha}...HEAD`
1131
- ]);
1132
- const match = counts?.exitCode === 0 ? /^(\d+)\s+(\d+)/u.exec(counts.stdout.trim()) : void 0;
1133
- if (!match) return { unknownReason: "no-git" };
1134
- return {
1135
- ahead: Number(match[1]),
1136
- behind: Number(match[2])
1137
- };
1138
- }
1139
- function isTimeout(error) {
1140
- if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) return true;
1141
- return error instanceof Error && error.cause instanceof Error && isTimeout(error.cause);
1142
- }
1143
- /**
1144
- * The deployment that receives production traffic, for `vitehub status`. It asks the host only when the project is
1145
- * linked and the credentials resolved. The signal shares status's deadline with credential discovery; standalone
1146
- * callers get `STATUS_HOST_TIMEOUT_MS`. It never throws: a failure is a `liveReason`.
1147
- */
1148
- async function readSetupLive(root, link, credentials, context, options) {
1149
- if (options.offline) return {
1150
- live: null,
1151
- liveReason: "offline"
1152
- };
1153
- if (!link) return {
1154
- live: null,
1155
- liveReason: "not-linked"
1156
- };
1157
- const signal = options.signal ?? AbortSignal.timeout(5e3);
1158
- if (signal.aborted) return {
1159
- live: null,
1160
- liveReason: "timeout"
1161
- };
1162
- if (!credentials?.ok || credentials.host !== link.host) return {
1163
- live: null,
1164
- liveReason: "no-credentials"
1165
- };
1166
- const run = createDeployRun(context.stderr, []);
1167
- try {
1168
- const deployment = (await abortable(signal, "Host deployment lookup timed out", () => listers[link.host](deploymentsContext(root, link, credentials, context, run, STATUS_HOST_TIMEOUT_MS, signal), {
1169
- includeLive: true,
1170
- limit: 10
1171
- }))).find((item) => item.live);
1172
- if (!deployment) return {
1173
- live: null,
1174
- liveReason: "no-live-deployment"
1175
- };
1176
- const base = {
1177
- deploymentId: deployment.id,
1178
- ...deployment.url ? { url: deployment.url } : {}
1179
- };
1180
- if (!deployment.commit) return {
1181
- live: {
1182
- ...base,
1183
- unknownReason: "no-marker"
1184
- },
1185
- liveReason: null
1186
- };
1187
- const commit = {
1188
- dirty: deployment.commit.dirty,
1189
- sha: deployment.commit.sha
1190
- };
1191
- return {
1192
- live: {
1193
- ...base,
1194
- commit,
1195
- ...await compareWithHead(run, root, context.env, commit.sha)
1196
- },
1197
- liveReason: null
1198
- };
1199
- } catch (error) {
1200
- return {
1201
- live: null,
1202
- liveReason: isTimeout(error) ? "timeout" : "host-error"
1203
- };
1204
- }
1205
- }
1206
- /** How long `vitehub deploy` waits for the host when it reads the deployment that a failed check rolls back to. */
1207
- const DEPLOY_PREVIOUS_TIMEOUT_MS = 1e4;
1208
- /**
1209
- * The deployment that receives production traffic now, read before `vitehub deploy` replaces it. It throws when the
1210
- * host request fails, so the caller can say why the rollback target is not known.
1211
- */
1212
- async function readLiveDeployment(root, link, credentials, context, run) {
1213
- const signal = AbortSignal.timeout(DEPLOY_PREVIOUS_TIMEOUT_MS);
1214
- return (await abortable(signal, "Host deployment lookup timed out", () => listers[link.host](deploymentsContext(root, link, credentials, context, run, DEPLOY_PREVIOUS_TIMEOUT_MS, signal), {
1215
- includeLive: true,
1216
- limit: 1
1217
- }))).find((item) => item.live);
1218
- }
1219
- const reasonLabels = {
1220
- "host-error": "unknown (the host request failed; run `vitehub deployments` for the error)",
1221
- "no-credentials": "unknown (no host credentials)",
1222
- "no-live-deployment": "none (nothing receives production traffic)",
1223
- "not-linked": "unknown (not linked)",
1224
- "offline": "not checked (--offline)",
1225
- "timeout": "unknown (the host did not answer in time)"
1226
- };
1227
- const unknownLabels = {
1228
- "commit-not-local": "commit not in this repository",
1229
- "no-git": "no git repository",
1230
- "no-marker": "no commit marker"
1231
- };
1232
- function plural(count, word) {
1233
- return `${count} ${word}${count === 1 ? "" : "s"}`;
1234
- }
1235
- /** The `live` line of `vitehub status`, such as `abc1234 (3 commits behind)`. */
1236
- function liveLabel(status) {
1237
- const { live } = status;
1238
- if (!live) return reasonLabels[status.liveReason ?? "no-live-deployment"];
1239
- const name = live.commit ? live.commit.sha.slice(0, 7) : live.deploymentId;
1240
- const notes = [];
1241
- if (live.unknownReason) notes.push(unknownLabels[live.unknownReason]);
1242
- else if (live.ahead || live.behind) notes.push([live.behind ? `${plural(live.behind, "commit")} behind` : "", live.ahead ? `${plural(live.ahead, "commit")} ahead` : ""].filter(Boolean).join(", "));
1243
- else notes.push("up to date");
1244
- if (live.commit?.dirty) notes.push("with uncommitted changes");
1245
- return `${name} (${notes.join(", ")})${live.url ? ` ${live.url}` : ""}`;
1246
- }
1247
- //#endregion
1248
- //#region src/setup/deploy/provision.ts
1249
- /** A step whose recorded state declares nothing has no resource to create, so deploy does not ask the host. */
1250
- function declaresResources(step, env) {
1251
- const described = step.recordedState?.({ env });
1252
- return described === void 0 || described.some((category) => category.declared.length > 0);
1253
- }
1254
- /** Says which credential the steps miss, for the reason of SETUP_DEPLOY_PROVISION_UNCHECKED. */
1255
- function missingCredential(host, env) {
1256
- if (host === "cloudflare" && !env.CLOUDFLARE_ACCOUNT_ID?.trim()) return "Set CLOUDFLARE_ACCOUNT_ID, or run `vitehub link --host cloudflare --account <id>`. A `wrangler login` with several accounts does not say which one to use.";
1257
- if (host === "vercel" && !env.VERCEL_TOKEN?.trim()) return "A saved `vercel login` cannot create Vercel resources. Set VERCEL_TOKEN to a token from https://vercel.com/account/tokens.";
1258
- if (host === "vercel" && !env.VERCEL_PROJECT_ID?.trim()) return "Run `vitehub link --host vercel` to store the project id, or set VERCEL_PROJECT_ID.";
1259
- return "Fix the cause of the warnings.";
1260
- }
1261
- async function confirmProvision(count, host) {
1262
- const terminal = createInterface({
1263
- input: process.stdin,
1264
- output: process.stderr
1265
- });
1266
- try {
1267
- return /^y(?:es)?$/iu.test((await terminal.question(`Create or change ${count} ${count === 1 ? "resource" : "resources"} on ${host}? [y/N] `)).trim());
1268
- } finally {
1269
- terminal.close();
1270
- }
1271
- }
1272
- /**
1273
- * Runs the Provision Steps of `host` before the build, with the credentials that deploy resolved, such as a
1274
- * `wrangler login`. It creates missing resources and records their ids in `.vitehub/provision.json`, so the build
1275
- * binds them and a second deploy creates nothing. Returns undefined when the host has no step with a resource.
1276
- */
1277
- async function provisionForDeploy(input, context) {
1278
- const { host } = input;
1279
- if (!isProvisionHost(host) || !context.loadProvision) return;
1280
- const env = provisionEnv(context.env, input.credentials, {
1281
- ...input.link?.account?.id ? { accountId: input.link.account.id } : {},
1282
- ...input.link?.project.id ? { projectId: input.link.project.id } : {}
774
+ if (!site) omits.push({
775
+ path: "config",
776
+ reason: "opaque-config"
1283
777
  });
1284
- const loaded = await context.loadProvision(host);
1285
- const steps = loaded.steps.filter((step) => step.provider === host && declaresResources(step, env));
1286
- if (!steps.length) return;
1287
- const root = loaded.rootDir;
1288
- await readProvisionState(root);
1289
- const plan = await planProvisionSteps(host, steps, {
1290
- env,
1291
- fetch: context.fetch ?? globalThis.fetch,
1292
- logger: {
1293
- log: (message) => context.stderr.write(`${message}\n`),
1294
- warn: (message) => context.stderr.write(`${message}\n`)
1295
- }
778
+ if (site?.spread) omits.push({
779
+ path: "config",
780
+ reason: "spread"
1296
781
  });
1297
- if (!plan.checked) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_PROVISION_UNCHECKED({
1298
- host,
1299
- missing: missingCredential(host, env),
1300
- warnings: plan.warnings.join(" ")
1301
- }), setupExitCodes.inputNeeded, { rerun: input.rerun });
1302
- const changes = plan.actions.flatMap((planned) => {
1303
- const status = provisionActionStatus(planned);
1304
- return status === "exists" ? [] : [{
1305
- planned,
1306
- status
1307
- }];
782
+ if (status.host.name === "unknown") omits.push({
783
+ path: "host",
784
+ reason: "unresolved-host"
1308
785
  });
1309
- if (changes.length && !input.build) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_PROVISION_NEEDS_BUILD({
1310
- count: changes.length,
1311
- host
1312
- }), setupExitCodes.conflict);
1313
- if (changes.length) {
1314
- if (!input.json) {
1315
- context.stdout.write(`Provision on ${host}:\n`);
1316
- writeProvisionActions(changes.map((change) => change.planned), context.stdout);
1317
- }
1318
- if (!input.yes && !await confirmProvision(changes.length, host)) throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] The resources were not confirmed. Nothing was created or deployed." }), setupExitCodes.error);
1319
- }
1320
- let state = {};
1321
- try {
1322
- for (const { action } of plan.actions) {
1323
- const result = await action.apply();
1324
- if (result.ids) state = mergeProvisionState(state, result.ids);
786
+ for (const { id, enabled, support } of status.features) {
787
+ const setting = site?.keys[id];
788
+ if (setting?.kind === "expression") {
789
+ omits.push({
790
+ path: id,
791
+ reason: "expression"
792
+ });
793
+ continue;
1325
794
  }
1326
- } finally {
1327
- if (Object.keys(state).length) await writeProvisionState(root, state);
1328
- }
1329
- if (changes.length && !input.json) context.stdout.write(`Provisioned ${changes.length} ${changes.length === 1 ? "resource" : "resources"} on ${host}. Ids are in ${PROVISION_STATE_FILE}.\n`);
1330
- return {
1331
- changed: changes.map(({ planned, status }) => ({
1332
- kind: planned.action.kind,
1333
- name: planned.action.name,
1334
- status,
1335
- step: planned.step
1336
- })),
1337
- ids: state[host] ?? {}
1338
- };
1339
- }
1340
- //#endregion
1341
- //#region src/setup/deploy.ts
1342
- const deployHosts = [
1343
- "cloudflare",
1344
- "vercel",
1345
- "netlify",
1346
- "deno"
1347
- ];
1348
- const temporaryHosts = ["cloudflare", "vercel"];
1349
- const usage$2 = "vitehub deploy [--host <host>] [--preview] [--push-env] [--no-build] [--no-provision] [--no-push] [--no-check] [--no-index-now] [--temporary] [--yes] [--json]";
1350
- const help = `--host picks a host target of .vitehub/link.json. Without it, deploy uses the default target. The build runs
1351
- with VITEHUB_HOST set to that host, which wins over \`host\` in vitehub(). Each host has its own resources, such as D1,
1352
- KV, R2, and libSQL.
1353
-
1354
- On Cloudflare and Vercel, deploy first creates the missing resources of the app, such as D1, KV, R2, Queues, and Vercel
1355
- Blob, with the same login, and records their ids in .vitehub/provision.json. The build binds those ids, and a second
1356
- deploy creates nothing. It lists what it creates and asks first, unless you pass --yes. --no-provision skips it.
1357
-
1358
- With checkout folders in vitehub.lock, a production deploy pulls them and checks for conflicts before the build, and
1359
- pushes them after the deploy, as \`vitehub push\` does. A --preview deploy does not push, so a preview never writes
1360
- the shared Workspace ref. --no-push skips the pull, the check and the push.
1361
-
1362
- After the build, deploy checks the env names that the build lists. A production deploy reads stage production, a
1363
- --preview deploy stage preview: the shell, then .env.<stage> files. Each required name must be on the host or have a
1364
- local value, or nothing is deployed. Deploy sets the names that the host lacks from their local values; --push-env
1365
- also replaces the names that the host has. Cloudflare gets the values with the new version through --secrets-file.
1366
- Cloudflare always re-supplies local stage values and needs a local value for every existing Worker secret, so an
1367
- omitted secret cannot inherit from another stage. With --yes, a missing VITEHUB_SECRET is generated and set.
1368
-
1369
- After the upload, deploy requests the paths of \`deploy.check\` in vitehub(), and the health route with \`health\`, on
1370
- the deployed URL. When one does not answer with a 2xx status, deploy exits with 1 and prints the command that rolls
1371
- production back to the deployment it replaced. --no-check skips the checks. With \`deploy.indexNow\`, a production
1372
- deploy that passed its checks then sends the URLs of /sitemap.xml to IndexNow. --no-index-now skips it.
1373
- `;
1374
- function readDeployArgs(args) {
1375
- try {
1376
- const { values } = parseArgs({
1377
- args: [...args],
1378
- options: {
1379
- "help": {
1380
- short: "h",
1381
- type: "boolean",
1382
- default: false
1383
- },
1384
- "host": { type: "string" },
1385
- "json": {
1386
- type: "boolean",
1387
- default: false
1388
- },
1389
- "no-build": {
1390
- type: "boolean",
1391
- default: false
1392
- },
1393
- "no-check": {
1394
- type: "boolean",
1395
- default: false
1396
- },
1397
- "no-index-now": {
1398
- type: "boolean",
1399
- default: false
1400
- },
1401
- "no-provision": {
1402
- type: "boolean",
1403
- default: false
1404
- },
1405
- "no-push": {
1406
- type: "boolean",
1407
- default: false
1408
- },
1409
- "preview": {
1410
- type: "boolean",
1411
- default: false
1412
- },
1413
- "push-env": {
1414
- type: "boolean",
1415
- default: false
1416
- },
1417
- "temporary": {
1418
- type: "boolean",
1419
- default: false
1420
- },
1421
- "yes": {
1422
- short: "y",
1423
- type: "boolean",
1424
- default: false
1425
- }
1426
- },
1427
- strict: true
795
+ if (enabled === "unknown" && site && !site.spread) omits.push({
796
+ path: id,
797
+ reason: "unresolved-feature"
1428
798
  });
1429
- return {
1430
- build: !values["no-build"],
1431
- check: !values["no-check"],
1432
- help: values.help,
1433
- indexNow: !values["no-index-now"],
1434
- ...values.host === void 0 ? {} : { host: values.host },
1435
- json: values.json,
1436
- preview: values.preview,
1437
- pushEnv: values["push-env"],
1438
- provision: !values["no-provision"],
1439
- push: !values["no-push"],
1440
- temporary: values.temporary,
1441
- yes: values.yes
1442
- };
799
+ if (enabled !== "on") continue;
800
+ if (support.level === "unsupported") {
801
+ omits.push({
802
+ path: id,
803
+ reason: "unsupported-feature"
804
+ });
805
+ continue;
806
+ }
807
+ const value = setting?.value;
808
+ if (features[id].enabledByDefault && (value === void 0 || value === true || isRecord$1(value) && !Object.keys(value).length)) continue;
809
+ selected.push(id);
810
+ if (value !== void 0 && value !== true) collect(id, [], value);
811
+ }
812
+ const implied = impliedFeatures(selected);
813
+ for (const { id, enabled, reason } of status.features) if (enabled === "off" && reason === "config" && (features[id].enabledByDefault || implied.includes(id))) omits.push({
814
+ path: id,
815
+ reason: "disabled-feature"
816
+ });
817
+ const name = basename(project.root);
818
+ const args = [
819
+ name.startsWith("-") ? `./${name}` : name || "vitehub-app",
820
+ "--host",
821
+ status.host.name === "unknown" ? "<host>" : status.host.name,
822
+ "--features",
823
+ selected.join(","),
824
+ ...options.flatMap((option) => ["--option", option]),
825
+ "--framework",
826
+ status.framework === "nuxt" ? "nuxt" : "vite",
827
+ "--pm",
828
+ status.packageManager,
829
+ "--yes"
830
+ ];
831
+ if (status.host.name !== "unknown") try {
832
+ await validate(args);
1443
833
  } catch (error) {
1444
- throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${error instanceof Error ? error.message : String(error)} Usage: ${usage$2}` });
1445
- }
1446
- }
1447
- function rerunCommand$1(args, extra = {}) {
1448
- return [
1449
- "vitehub deploy",
1450
- ...args.host ? [`--host ${args.host}`] : [],
1451
- ...args.preview ? ["--preview"] : [],
1452
- ...args.pushEnv ? ["--push-env"] : [],
1453
- ...args.build ? [] : ["--no-build"],
1454
- ...args.provision && extra.provision !== false ? [] : ["--no-provision"],
1455
- ...args.push ? [] : ["--no-push"],
1456
- ...args.check ? [] : ["--no-check"],
1457
- ...args.indexNow ? [] : ["--no-index-now"],
1458
- ...args.temporary || extra.temporary ? ["--temporary"] : [],
1459
- "--yes",
1460
- ...args.json ? ["--json"] : []
1461
- ].join(" ");
1462
- }
1463
- function supportedHost(host) {
1464
- const found = deployHosts.find((item) => item === host);
1465
- if (!found) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_HOST_UNSUPPORTED({ host }), setupExitCodes.conflict);
1466
- return found;
1467
- }
1468
- /** `--host`, else the default target, else the only target, else the config host. The CLI host wins over the config. */
1469
- function deployTarget(project, links, option, env) {
1470
- if (option !== void 0) {
1471
- const named = hostFromNitroPreset(option);
1472
- if (!named) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] Unknown host ${JSON.stringify(option)}. Use cloudflare, vercel, netlify, or deno. Usage: ${usage$2}` });
1473
- const host = supportedHost(named);
834
+ if (!isSetupFailure(error)) throw error;
835
+ const missing = error.details.missing;
836
+ if (missing?.length) omits.push(...missing.map(({ field }) => ({
837
+ path: field,
838
+ reason: "required-option"
839
+ })));
840
+ else omits.push({
841
+ path: "features",
842
+ reason: "unplannable-stack"
843
+ });
1474
844
  return {
1475
- host,
1476
- link: links.targets.find((target) => target.host === host)
845
+ command: null,
846
+ omits
1477
847
  };
1478
848
  }
1479
- const selected = selectSetupLink(links);
1480
- if ("ambiguous" in selected) throw hostRequired(selected.ambiguous, "vitehub deploy");
1481
- if (selected.link) return {
1482
- host: selected.link.host,
1483
- link: selected.link
1484
- };
1485
849
  return {
1486
- host: supportedHost(setupStatus(project, env).host.name),
1487
- link: void 0
1488
- };
1489
- }
1490
- function temporaryUnsupported(reason) {
1491
- return setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_TEMPORARY_UNSUPPORTED({ reason }), setupExitCodes.conflict);
1492
- }
1493
- /** Cloudflare: Wrangler refuses `--temporary` with a login. Vercel: the CLI refuses it in CI and in a linked folder. */
1494
- function assertTemporary(host, args, credentials, project, env) {
1495
- if (!temporaryHosts.includes(host)) throw temporaryUnsupported(`${host} has no temporary deploy. Only cloudflare and vercel have one.`);
1496
- if (args.preview) throw temporaryUnsupported("A temporary deploy always goes to production, so --preview does not apply.");
1497
- if (credentials.ok) throw temporaryUnsupported(`It is for a machine without a ${host} login, and credentials were found (${credentials.source}).`);
1498
- if (host === "vercel") {
1499
- if (env.CI && env.CI !== "0" && env.CI !== "false") throw temporaryUnsupported("The Vercel CLI refuses temporary deploys in CI.");
1500
- if (existsSync(join(project.root, ".vercel", "project.json"))) throw temporaryUnsupported("The folder is linked to a Vercel project in .vercel/project.json.");
1501
- }
1502
- }
1503
- function credentialsMissing(host, credentials, args) {
1504
- const temporary = temporaryHosts.includes(host);
1505
- const offer = temporary ? ` Or deploy without an account: run \`${rerunCommand$1(args, { temporary: true })}\`${host === "cloudflare" ? " and claim the Worker within 60 minutes" : " and claim the deployment with the link that it prints"}.` : "";
1506
- return setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_CREDENTIALS_MISSING({
1507
- fix: `${credentials.fix}${offer}`,
1508
- host
1509
- }), setupExitCodes.inputNeeded, {
1510
- missing: credentials.missing.map((field) => ({ field })),
1511
- ...temporary ? { rerun: rerunCommand$1(args, { temporary: true }) } : {}
1512
- });
1513
- }
1514
- async function confirmDeploy(name, host, preview) {
1515
- const terminal = createInterface({
1516
- input: process.stdin,
1517
- output: process.stderr
1518
- });
1519
- try {
1520
- return /^y(?:es)?$/iu.test((await terminal.question(`Deploy ${name} to ${host}${preview ? " as a preview" : " production"}? [y/N] `)).trim());
1521
- } finally {
1522
- terminal.close();
1523
- }
1524
- }
1525
- async function hostAdapter(host, context) {
1526
- switch (host) {
1527
- case "cloudflare": return await cloudflareAdapter(context);
1528
- case "vercel": return vercelAdapter(context);
1529
- case "netlify": return netlifyAdapter(context);
1530
- case "deno": return await denoAdapter(context, denoOrganization(context.link, context.env));
1531
- }
1532
- }
1533
- /** Records the host project after a first deploy, so `status` finds it. It stays unverified until `vitehub link`. */
1534
- async function recordLink(root, host, result, fallbackName) {
1535
- const project = result.project ?? { name: fallbackName };
1536
- await addSetupLink(root, {
1537
- host,
1538
- ...project.accountId ? { account: { id: project.accountId } } : {},
1539
- project: {
1540
- ...project.id ? { id: project.id } : {},
1541
- name: project.name
1542
- },
1543
- verified: false,
1544
- linkedAt: (/* @__PURE__ */ new Date()).toISOString()
1545
- });
1546
- await ensureViteHubGitignore(root);
1547
- }
1548
- function writeDeployed(output, name, context) {
1549
- context.stdout.write(`Deployed ${name} to ${output.host}: ${output.url}\n`);
1550
- if (output.deploymentId) context.stdout.write(`Deployment: ${output.deploymentId}\n`);
1551
- if (output.version) context.stdout.write(`Version: ${output.version}\n`);
1552
- if (output.commit) context.stdout.write(`Commit: ${output.commit.sha}${output.commit.dirty ? " (with uncommitted changes)" : ""}\n`);
1553
- for (const check of output.checks ?? []) context.stdout.write(`Checked ${check.path}: ${check.status ?? check.error}\n`);
1554
- if (output.temporary) {
1555
- const window = output.host === "cloudflare" ? "within 60 minutes" : output.temporary.expiresAt ? `before ${output.temporary.expiresAt}` : "soon";
1556
- context.stdout.write(`This is a temporary deploy. Claim it ${window}, or the host deletes it. Do not share the claim link:\n${output.temporary.claimUrl}\n`);
1557
- }
1558
- }
1559
- /** Pushes the checkout folders after the deploy. A failed push does not undo the deploy, so it exits with 1 and says so. */
1560
- async function pushCheckouts(checkouts, deployed, args, context) {
1561
- try {
1562
- const pushed = await pushDeployCheckouts(checkouts, context);
1563
- if (!args.json) context.stdout.write(formatDeployCheckouts(pushed));
1564
- return {
1565
- ...deployed,
1566
- checkouts: pushed
1567
- };
1568
- } catch (error) {
1569
- const failure = checkoutPushError(error);
1570
- throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_PUSH_FAILED({
1571
- fix: failure.fix,
1572
- message: `${failure.code}: ${failure.message}`,
1573
- url: deployed.url
1574
- }), setupExitCodes.error, {
1575
- data: {
1576
- ...deployed,
1577
- checkouts: { error: failure }
1578
- },
1579
- rerun: "vitehub push"
1580
- });
1581
- }
1582
- }
1583
- async function runDeploy(args, context) {
1584
- const project = await readSetupProject(context.rootDir, context.env);
1585
- const links = await readSetupLinks(project.root);
1586
- const { host, link } = deployTarget(project, links, args.host, context.env);
1587
- if (args.preview && host === "deno") throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_PREVIEW_UNSUPPORTED({ host }), setupExitCodes.conflict);
1588
- const credentials = await resolveHostCredentials(host, {
1589
- cwd: project.root,
1590
- env: context.env,
1591
- ...context.runHostCli ? { run: context.runHostCli } : {}
1592
- });
1593
- const vercelLogin = host === "vercel" && !credentials.ok && await hasVercelLogin(project.root, context);
1594
- if (args.temporary && vercelLogin) throw temporaryUnsupported("It is for a machine without a vercel login, and a saved CLI login was found.");
1595
- if (args.temporary) assertTemporary(host, args, credentials, project, context.env);
1596
- else if (!credentials.ok && !vercelLogin) throw credentialsMissing(host, credentials, args);
1597
- const interactive = !args.json && !!process.stdin.isTTY && !!process.stderr.isTTY;
1598
- if (!args.yes) {
1599
- if (!interactive) throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] `vitehub deploy` publishes the app and was not confirmed. Without a terminal, pass --yes." }), setupExitCodes.inputNeeded, { rerun: rerunCommand$1(args) });
1600
- if (!await confirmDeploy(link?.project.name ?? basename(project.root), host, args.preview)) throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] The deploy was not confirmed. Nothing was deployed." }), setupExitCodes.error);
1601
- }
1602
- const provisioned = args.provision && !args.temporary ? await provisionForDeploy({
1603
- build: args.build,
1604
- credentials,
1605
- host,
1606
- json: args.json,
1607
- link,
1608
- rerun: rerunCommand$1(args, { provision: false }),
1609
- yes: args.yes
1610
- }, context) : void 0;
1611
- const checkouts = args.push && !args.preview ? await prepareDeployCheckouts(project.root, context) : void 0;
1612
- if (!link && !args.temporary) writeSeparateResourcesNote(context, host, links);
1613
- if (args.build) await build(project, host, context);
1614
- const output = await readBuildOutput(project.root, host);
1615
- const projectName = link?.project.name ?? output.identityName;
1616
- if (!projectName) throw setupFailure(cliErrorDiagnostics.SETUP_LINK_NAME_REQUIRED(), setupExitCodes.inputNeeded, {
1617
- missing: [{ field: "project" }],
1618
- rerun: "vitehub link --project <name>"
1619
- });
1620
- const secrets = credentials.ok ? [credentials.token] : [];
1621
- const run = createDeployRun(context.stderr, secrets);
1622
- const env = await checkDeployEnv({
1623
- context,
1624
- entries: output.env,
1625
- envDir: output.envDir,
1626
- host,
1627
- interactive,
1628
- link: args.temporary ? void 0 : link,
1629
- outputDir: output.outputDir,
1630
- preview: args.preview,
1631
- pushEnv: args.pushEnv,
1632
- root: project.root,
1633
- run,
1634
- secrets,
1635
- yes: args.yes
1636
- });
1637
- const deployContext = {
1638
- commit: await readDeployCommit(run, project.root, context.env),
1639
- credentials,
1640
- env: context.env,
1641
- fetch: context.fetch ?? globalThis.fetch,
1642
- link,
1643
- outputDir: output.outputDir,
1644
- preview: args.preview,
1645
- projectName,
1646
- root: project.root,
1647
- run,
1648
- secrets,
1649
- temporary: args.temporary,
1650
- upload: env.upload
1651
- };
1652
- const adapter = await hostAdapter(host, deployContext);
1653
- await env.apply();
1654
- const checkPaths = args.check ? output.deploy.check : [];
1655
- const previous = checkPaths.length && !args.preview && !args.temporary ? await previousDeployment(project.root, link, credentials, context, run) : void 0;
1656
- const result = await adapter.deploy();
1657
- if (!link && !args.temporary) await recordLink(project.root, host, result, projectName);
1658
- const checks = checkPaths.length ? await runDeployChecks(result.url, checkPaths, deployContext.fetch) : void 0;
1659
- const deployed = {
1660
- host,
1661
- url: result.url,
1662
- ...result.deploymentId ? { deploymentId: result.deploymentId } : {},
1663
- ...result.version ? { version: result.version } : {},
1664
- ...result.claim ? { temporary: {
1665
- claimUrl: result.claim.url,
1666
- ...result.claim.expiresAt ? { expiresAt: result.claim.expiresAt } : {}
1667
- } } : {},
1668
- ...deployContext.commit ? { commit: deployContext.commit } : {},
1669
- env: env.output,
1670
- ...provisioned ? { provision: provisioned } : {},
1671
- ...checks ? { checks } : {}
850
+ command: [
851
+ "pnpm",
852
+ "dlx",
853
+ "vite-hub",
854
+ "init",
855
+ ...args.map(shellQuote)
856
+ ].join(" "),
857
+ omits
1672
858
  };
1673
- if (checks?.some((check) => !check.ok)) throw checkFailed(deployed, host, previous, projectName, link, result, args.preview);
1674
- if (!args.json) writeDeployed(deployed, projectName, context);
1675
- const pushed = checkouts ? await pushCheckouts(checkouts, deployed, args, context) : deployed;
1676
- const indexNow = output.deploy.indexNow && args.indexNow && !args.preview && !args.temporary ? await submitIndexNow(output.deploy.indexNow, deployContext.fetch) : void 0;
1677
- if (indexNow && !args.json) context.stderr.write("submitted" in indexNow ? `IndexNow: sent ${indexNow.submitted} URLs (${indexNow.status}).\n` : `IndexNow: nothing was sent. ${indexNow.error} The deploy is done.\n`);
1678
- const final = indexNow ? {
1679
- ...pushed,
1680
- indexNow
1681
- } : pushed;
1682
- if (args.json) writeSetupJson(context, final);
1683
- return setupExitCodes.done;
1684
- }
1685
- /** The deployment that serves production before this deploy. Without a link or a token there is nothing to read. */
1686
- async function previousDeployment(root, link, credentials, context, run) {
1687
- if (!link) return { failed: "the project was not linked before this deploy." };
1688
- if (!credentials.ok) return { failed: `deploy used the saved ${link.host} CLI login, which gives no API token.` };
1689
- try {
1690
- return { deployment: await readLiveDeployment(root, link, credentials, context, run) };
1691
- } catch (error) {
1692
- return { failed: error instanceof Error ? error.message : String(error) };
1693
- }
1694
859
  }
1695
- /** A deployed app that failed a check. Production now serves it, so the error says how to roll back. */
1696
- function checkFailed(deployed, host, previous, projectName, link, result, preview) {
1697
- const rollback = preview ? { note: "This was a preview deploy, so production did not change." } : rollbackFor(host, {
1698
- previous: previous && "deployment" in previous ? previous.deployment : void 0,
1699
- projectName: link?.project.name ?? result.project?.name ?? projectName,
1700
- ...previous && "failed" in previous ? { lookupFailed: previous.failed } : {},
1701
- ...host === "netlify" && (link?.project.id ?? result.project?.id) ? { siteId: link?.project.id ?? result.project?.id } : {}
1702
- });
1703
- const failure = cliErrorDiagnostics.SETUP_DEPLOY_CHECK_FAILED({
1704
- failed: formatFailedChecks(deployed.checks ?? []),
1705
- rollback: rollback.command ? `Run \`${rollback.command}\` to put the previous deployment back on production.` : rollback.note,
1706
- url: deployed.url
1707
- });
1708
- return setupFailure(failure, setupExitCodes.error, { data: {
1709
- ...deployed,
1710
- rollback
1711
- } });
1712
- }
1713
- const deployCommand = {
1714
- description: "Create the missing host resources, build the app for a linked host, check its env, and deploy it with your local login. --host picks the host. Pushes the checkout folders of vitehub.lock.",
1715
- name: "deploy",
1716
- run: async (args, context) => {
1717
- const json = args.includes("--json");
1718
- try {
1719
- const parsed = readDeployArgs(args);
1720
- if (parsed.help) {
1721
- context.stdout.write(`Usage: ${usage$2}\n\n${deployCommand.description}\n\n${help}`);
1722
- return setupExitCodes.done;
1723
- }
1724
- return await runDeploy(parsed, context);
1725
- } catch (error) {
1726
- return writeSetupError(context, json, error);
1727
- }
1728
- },
1729
- usage: usage$2
1730
- };
1731
860
  //#endregion
1732
861
  //#region src/setup/init.ts
1733
- const usage$1 = "vitehub init <dir> --host <host> --features <id,id,...> [--option <feature.key=value>]... [--framework vite|nuxt] [--pm pnpm|npm|yarn|bun] [--no-install] [--dry-run] --yes [--json]";
1734
- /** The command that starts a project. It runs from the `vite-hub` package, so it needs no install. */
862
+ const usage$2 = "vitehub init <dir> --host <host> --features <id,id,...> [--option <feature.key=value>]... [--framework vite|nuxt] [--pm pnpm|npm|yarn|bun] [--no-install] [--dry-run] --yes [--json]";
1735
863
  const initCommandPrefix = "pnpm dlx vite-hub init";
1736
864
  const initHosts = [
1737
865
  "cloudflare",
@@ -1769,7 +897,7 @@ const initPackages = {
1769
897
  ],
1770
898
  prod: [
1771
899
  "vite-hub",
1772
- "nitro@3.0.261102-rc",
900
+ "nitro@3.0.261103-rc",
1773
901
  "h3@2.0.8",
1774
902
  "valibot"
1775
903
  ]
@@ -1777,20 +905,16 @@ const initPackages = {
1777
905
  };
1778
906
  /** The pinned Nuxt CLI that creates a new Nuxt app. */
1779
907
  const nuxiPackage = "nuxi@3.37.0";
1780
- /** Pin the starter files and select Nuxt 5 explicitly instead of the live minimal registry entry. */
1781
908
  const nuxtTemplate = "gh:nuxt/starter#db01806fcb37f2e369fb09443c72cac696b31548";
1782
- /** Where the reproducing command lives in README.md. */
1783
- const stackStart = "<!-- vitehub:stack -->";
1784
- const stackEnd = "<!-- /vitehub:stack -->";
1785
909
  function isRecord(value) {
1786
910
  return !!value && typeof value === "object" && !Array.isArray(value);
1787
911
  }
1788
- function invalid$1(message) {
1789
- return cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${message} Usage: ${usage$1}` });
912
+ function invalid$2(message) {
913
+ return cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${message} Usage: ${usage$2}` });
1790
914
  }
1791
915
  function oneOf(flag, value, choices) {
1792
916
  const found = choices.find((choice) => choice === value);
1793
- if (!found) throw invalid$1(`${flag} must be one of ${choices.join(", ")}, not ${JSON.stringify(value)}.`);
917
+ if (!found) throw invalid$2(`${flag} must be one of ${choices.join(", ")}, not ${JSON.stringify(value)}.`);
1794
918
  return found;
1795
919
  }
1796
920
  /** Reads the arguments. Throws `CLI_R0003` for an unknown flag or value. */
@@ -1809,7 +933,7 @@ function readInitArgs(args) {
1809
933
  const [flag, inline] = arg.startsWith("--") && arg.includes("=") ? [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)] : [arg, void 0];
1810
934
  const value = () => {
1811
935
  const next = inline ?? args[++index];
1812
- if (next === void 0 || inline === void 0 && next.startsWith("--")) throw invalid$1(`${flag} needs a value.`);
936
+ if (next === void 0 || inline === void 0 && next.startsWith("--")) throw invalid$2(`${flag} needs a value.`);
1813
937
  return next;
1814
938
  };
1815
939
  if (flag === "--json") parsed.json = true;
@@ -1822,14 +946,13 @@ function readInitArgs(args) {
1822
946
  else if (flag === "--option") parsed.options.push(value());
1823
947
  else if (flag === "--framework") parsed.framework = oneOf("--framework", value(), frameworks);
1824
948
  else if (flag === "--pm") parsed.pm = oneOf("--pm", value(), packageManagers);
1825
- else if (arg.startsWith("-")) throw invalid$1(`Unknown argument ${JSON.stringify(arg)}.`);
949
+ else if (arg.startsWith("-")) throw invalid$2(`Unknown argument ${JSON.stringify(arg)}.`);
1826
950
  else if (parsed.dir === void 0) parsed.dir = arg;
1827
- else throw invalid$1(`Pass one folder, not ${JSON.stringify(parsed.dir)} and ${JSON.stringify(arg)}.`);
951
+ else throw invalid$2(`Pass one folder, not ${JSON.stringify(parsed.dir)} and ${JSON.stringify(arg)}.`);
1828
952
  }
1829
953
  if (features !== void 0) parsed.features = readAddArgs(features.split(",").map((item) => item.trim()).filter(Boolean)).features;
1830
954
  return parsed;
1831
955
  }
1832
- /** The `vitehub add` arguments for the features and options of `init`. */
1833
956
  function addArgsOf(args) {
1834
957
  return {
1835
958
  ...readAddArgs([...args.features, ...args.options.flatMap((option) => ["--option", option])]),
@@ -1843,20 +966,15 @@ function initCommand(parts, extra) {
1843
966
  initCommandPrefix,
1844
967
  shellQuote(parts.dir),
1845
968
  "--host",
1846
- parts.host ?? "<host>",
969
+ shellQuote(parts.host ?? "<host>"),
1847
970
  "--features",
1848
- parts.features ? parts.features.join(",") || "''" : "<id,id,...>",
971
+ shellQuote(parts.features?.join(",") ?? "<id,id,...>"),
1849
972
  ...options.flatMap((option) => ["--option", shellQuote(option)]),
1850
973
  ...parts.framework === "nuxt" ? ["--framework", "nuxt"] : [],
1851
974
  ...parts.pm && parts.pm !== "pnpm" ? ["--pm", parts.pm] : [],
1852
975
  ...extra
1853
976
  ].join(" ");
1854
977
  }
1855
- /** The command that creates the same stack, for README.md and `vitehub status`. */
1856
- function stackCommand(parts) {
1857
- return initCommand(parts, ["--yes"]);
1858
- }
1859
- /** The `rerun` command: the same request with `--yes`. */
1860
978
  function rerunInit(args, parts) {
1861
979
  return initCommand(parts, [
1862
980
  ...args.install ? [] : ["--no-install"],
@@ -1864,37 +982,9 @@ function rerunInit(args, parts) {
1864
982
  ...args.json ? ["--json"] : []
1865
983
  ]);
1866
984
  }
1867
- function stackBlock(command) {
1868
- return `${stackStart}\nCreate the same stack with:\n\n\`\`\`sh\n${command}\n\`\`\`\n${stackEnd}\n`;
1869
- }
1870
- /** README.md with the stack block, or undefined when it already holds the same block. */
1871
- function readmeWithStack(readme, name, command) {
1872
- const block = stackBlock(command);
1873
- if (readme === void 0) return `# ${name}\n\n${block}`;
1874
- const from = readme.indexOf(stackStart);
1875
- const to = readme.indexOf(stackEnd, from);
1876
- if (from !== -1 && to !== -1) {
1877
- const after = readme.slice(to + 23).replace(/^\r?\n/u, "");
1878
- return `${readme.slice(0, from)}${block}${after}`;
1879
- }
1880
- return `${readme}${readme === "" || readme.endsWith("\n") ? "" : "\n"}\n${block}`;
1881
- }
1882
- /** The stack command in the README.md block of `root`, for `vitehub status`. `null` when there is no block. */
1883
- async function readSetupStack(root) {
1884
- const file = join(root, "README.md");
1885
- if (!existsSync(file)) return null;
1886
- const readme = await readFile(file, "utf8");
1887
- const from = readme.indexOf(stackStart);
1888
- const to = readme.indexOf(stackEnd, from);
1889
- if (from === -1 || to === -1) return null;
1890
- const command = readme.slice(from, to).split(/\r?\n/u).map((line) => line.trim()).find((line) => line.startsWith(initCommandPrefix));
1891
- return command ? { command } : null;
1892
- }
1893
- /** The deployment name rules of `vitehub({ name })`, for the package.json name of a new app. */
1894
985
  function packageNameOf(root) {
1895
986
  return basename(root).trim().toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-|-$/gu, "") || "vitehub-app";
1896
987
  }
1897
- /** The files of a new Vite app, as `fixtures/docs-hosts/installation` has them. */
1898
988
  function viteAppFiles(name, host) {
1899
989
  return {
1900
990
  ".gitignore": "node_modules\n.output\n.vitehub\n.env*\n!.env.example\n",
@@ -1926,7 +1016,6 @@ function viteAppFiles(name, host) {
1926
1016
  "vite.config.ts": `import { defineConfig } from "vite"\nimport { vitehub } from "vite-hub"\n\nexport default defineConfig({\n plugins: [vitehub({ host: "${host}" })],\n})\n`
1927
1017
  };
1928
1018
  }
1929
- /** The config that `nuxi init` and the adoption would give, to plan a new Nuxt app before `nuxi init` runs. */
1930
1019
  function nuxtAppFiles(name, host) {
1931
1020
  return {
1932
1021
  "nuxt.config.ts": `import viteHubNuxt from "vite-hub/nuxt"\n\nexport default defineNuxtConfig({\n modules: [\n [viteHubNuxt, { host: "${host}" }],\n ],\n})\n`,
@@ -1998,7 +1087,6 @@ function manualConfig(file, reason, host, framework) {
1998
1087
  snippet
1999
1088
  }), setupExitCodes.conflict, { data: { snippet } });
2000
1089
  }
2001
- /** The config of an existing app with ViteHub registered on `host`. */
2002
1090
  function adoptConfig(project, host, framework) {
2003
1091
  const file = project.configFile ?? (framework === "nuxt" ? "nuxt.config.ts" : "vite.config.ts");
2004
1092
  const config = project.config;
@@ -2040,7 +1128,6 @@ function adoptConfig(project, host, framework) {
2040
1128
  file
2041
1129
  };
2042
1130
  }
2043
- /** Plans `vitehub init` without writing anything. Throws `SetupFailure` when the change needs input or is not possible. */
2044
1131
  async function planInit(args, root, state, context) {
2045
1132
  const name = packageNameOf(root);
2046
1133
  const found = state.kind === "adopt" ? state.project.framework : void 0;
@@ -2090,7 +1177,7 @@ async function planInit(args, root, state, context) {
2090
1177
  packageManager,
2091
1178
  packageManagerSource: args.pm ? "manifest" : detected.packageManagerSource,
2092
1179
  root,
2093
- serverDirs: state.kind === "adopt" ? state.project.serverDirs : [join(root, "server")]
1180
+ serverDirs: state.kind === "adopt" ? state.project.serverDirs : []
2094
1181
  };
2095
1182
  const addArgs = addArgsOf(args);
2096
1183
  const parts = (extra = {}, extraFeatures = []) => {
@@ -2118,12 +1205,6 @@ async function planInit(args, root, state, context) {
2118
1205
  ...base.get(configFile),
2119
1206
  after: added.configFile.after
2120
1207
  });
2121
- const stack = stackCommand(parts());
2122
- const readme = state.kind === "create" ? void 0 : await readOptional(join(root, "README.md"));
2123
- base.set("README.md", {
2124
- ...readme === void 0 ? {} : { before: readme },
2125
- after: readmeWithStack(readme, name, stack)
2126
- });
2127
1208
  if (state.kind === "adopt") {
2128
1209
  const gitignore = await readOptional(join(root, ".gitignore"));
2129
1210
  base.set(".gitignore", {
@@ -2157,6 +1238,13 @@ async function planInit(args, root, state, context) {
2157
1238
  `Start the dev server: ${runScript(packageManager, "dev")}`,
2158
1239
  ...added.plan.nextSteps
2159
1240
  ];
1241
+ const finalConfig = base.get(configFile).after;
1242
+ const stackProject = {
1243
+ ...planned,
1244
+ config: locateViteHubConfig(configFile, finalConfig),
1245
+ configSource: finalConfig,
1246
+ packageManager: args.install && (command || scaffold) ? packageManager : detected.packageManager
1247
+ };
2160
1248
  return {
2161
1249
  install,
2162
1250
  plan: {
@@ -2175,14 +1263,27 @@ async function planInit(args, root, state, context) {
2175
1263
  packageManager,
2176
1264
  root,
2177
1265
  ...scaffold ? { scaffold: { command: [scaffold[0], ...scaffold[1]].join(" ") } } : {},
2178
- stack: { command: stack },
2179
1266
  status: writes.length || scaffold || command && args.install ? "planned" : "unchanged"
2180
1267
  },
2181
1268
  rerun: rerunInit(args, parts()),
1269
+ stackProject,
2182
1270
  writes,
2183
1271
  ...scaffold ? { scaffold } : {}
2184
1272
  };
2185
1273
  }
1274
+ function setupStack(project, status) {
1275
+ return deriveSetupStack(project, status, async (args) => {
1276
+ const inputs = await readInputs(readInitArgs(args));
1277
+ const rootDir = dirname(project.root);
1278
+ await planInit(inputs, resolve(rootDir, inputs.dir), {
1279
+ exists: false,
1280
+ kind: "create"
1281
+ }, {
1282
+ env: {},
1283
+ rootDir
1284
+ });
1285
+ });
1286
+ }
2186
1287
  async function applyInit(planned, install, context, scaffolded = false) {
2187
1288
  const { plan } = planned;
2188
1289
  const runInstall = async () => {
@@ -2196,7 +1297,7 @@ async function applyInit(planned, install, context, scaffolded = false) {
2196
1297
  stdout: "stderr"
2197
1298
  });
2198
1299
  if (result.exitCode !== 0) throw setupFailure(cliErrorDiagnostics.SETUP_INSTALL_FAILED({
2199
- command: [plan.packageManager, ...commandArgs].join(" "),
1300
+ command: formatInstallCommand(plan.packageManager, commandArgs),
2200
1301
  exitCode: result.exitCode ?? result.signal,
2201
1302
  filesWritten: scaffolded || plan.mode === "create"
2202
1303
  }), setupExitCodes.error);
@@ -2219,7 +1320,6 @@ async function applyInit(planned, install, context, scaffolded = false) {
2219
1320
  }
2220
1321
  if (plan.mode === "create") await runInstall();
2221
1322
  }
2222
- /** Runs `nuxi init` for a new Nuxt app. ViteHub then adopts the app that it created. */
2223
1323
  async function scaffoldNuxt(planned, context) {
2224
1324
  const [command, commandArgs] = planned.scaffold;
2225
1325
  await mkdir(dirname(planned.plan.root), { recursive: true });
@@ -2235,7 +1335,6 @@ async function scaffoldNuxt(planned, context) {
2235
1335
  }), setupExitCodes.error);
2236
1336
  await validateNuxtVersion(planned.plan.root, true);
2237
1337
  }
2238
- /** Accept nonempty ranges confined to Nuxt 5, including its prereleases and nightly aliases. */
2239
1338
  function supportsNuxt5(nuxt) {
2240
1339
  if (typeof nuxt !== "string") return false;
2241
1340
  const range = validRange(nuxt.replace(/^npm:nuxt(?:-nightly)?@/u, ""));
@@ -2243,7 +1342,6 @@ function supportsNuxt5(nuxt) {
2243
1342
  const releases = new Range(range).set.map((comparators) => comparators.map(({ operator, semver, value }) => typeof semver !== "symbol" && semver.major === 5 && semver.prerelease.length > 0 ? `${operator}5.${semver.minor}.${semver.patch}` : value).join(" ")).join(" || ");
2244
1343
  return subset(releases, ">=5.0.0 <6.0.0");
2245
1344
  }
2246
- /** Validate both existing apps and scaffold output before planning adoption or installing packages. */
2247
1345
  async function validateNuxtVersion(root, scaffolded = false) {
2248
1346
  const manifest = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
2249
1347
  const dependencies = isRecord(manifest) && isRecord(manifest.dependencies) ? manifest.dependencies : {};
@@ -2267,7 +1365,6 @@ async function ask(question) {
2267
1365
  terminal.close();
2268
1366
  }
2269
1367
  }
2270
- /** Asks for missing inputs in a terminal. Without one, fails with the flag and its choices. */
2271
1368
  async function readInputs(args) {
2272
1369
  if (interactive(args)) {
2273
1370
  const dir = args.dir ?? (await ask("Folder of the app: ") || ".");
@@ -2318,13 +1415,22 @@ function writePlan$1(plan, context) {
2318
1415
  if (plan.scaffold) context.stdout.write(`Run: ${plan.scaffold.command}\n`);
2319
1416
  for (const change of plan.changes) if (change.kind === "create") context.stdout.write(`create ${change.path}\n`);
2320
1417
  else context.stdout.write(change.diff.endsWith("\n") ? change.diff : `${change.diff}\n`);
2321
- const lines = [...plan.install.command ? [`Install: ${plan.install.command}`] : [], ...plan.implied.length ? [`Also turns on: ${plan.implied.join(", ")}`] : []];
2322
- if (lines.length) context.stdout.write(`${lines.join("\n")}\n`);
1418
+ const lines = [
1419
+ ...plan.install.command ? [`Install: ${plan.install.command}`] : [],
1420
+ ...plan.implied.length ? [`Also turns on: ${plan.implied.join(", ")}`] : [],
1421
+ ...stackLines(plan.stack)
1422
+ ];
1423
+ context.stdout.write(`${lines.join("\n")}\n`);
1424
+ }
1425
+ function stackLines(stack) {
1426
+ const { command, omissions } = setupStackLabels(stack);
1427
+ return [`Stack: ${command}`, ...omissions ? [`Stack omissions: ${omissions}`] : []];
2323
1428
  }
2324
1429
  function writeResult$1(plan, context) {
2325
1430
  const features = plan.features.length ? ` with ${plan.features.join(", ")}` : "";
2326
1431
  if (plan.status === "unchanged") context.stdout.write(`${plan.root} already has this stack. Nothing to change.\n`);
2327
1432
  else context.stdout.write(`${plan.mode === "create" ? "Created" : "Set up"} ${plan.root} for ${plan.host}${features}.\n`);
1433
+ context.stdout.write(`${stackLines(plan.stack).join("\n")}\n`);
2328
1434
  context.stdout.write(`\nNext steps:\n${plan.nextSteps.map((step) => `- ${step}`).join("\n")}\n`);
2329
1435
  }
2330
1436
  async function runInit(rawArgs, context) {
@@ -2333,13 +1439,16 @@ async function runInit(rawArgs, context) {
2333
1439
  const parsed = readInitArgs(rawArgs);
2334
1440
  json = parsed.json;
2335
1441
  if (parsed.help) {
2336
- context.stdout.write(`Usage: ${usage$1}\n\n${initCommandDefinition.description}\n`);
1442
+ context.stdout.write(`Usage: ${usage$2}\n\n${initCommandDefinition.description}\n`);
2337
1443
  return setupExitCodes.done;
2338
1444
  }
2339
1445
  const args = await readInputs(parsed);
2340
1446
  const root = resolve(context.rootDir, args.dir);
2341
1447
  let planned = await planInit(args, root, await readDir(root, context.env), context);
2342
- const { plan } = planned;
1448
+ const plan = {
1449
+ ...planned.plan,
1450
+ stack: await setupStack(planned.stackProject, setupStatus(planned.stackProject, context.env))
1451
+ };
2343
1452
  if (plan.status === "unchanged" || args.dryRun) {
2344
1453
  if (args.json) writeSetupJson(context, plan);
2345
1454
  else if (plan.status === "unchanged") writeResult$1(plan, context);
@@ -2365,9 +1474,11 @@ async function runInit(rawArgs, context) {
2365
1474
  }, root, await readDir(root, context.env), context);
2366
1475
  }
2367
1476
  await applyInit(planned, args.install, context, !!plan.scaffold);
1477
+ const project = await readSetupProject(root, context.env);
2368
1478
  const applied = {
2369
1479
  ...planned.plan,
2370
1480
  mode: plan.mode,
1481
+ stack: await setupStack(project, setupStatus(project, context.env)),
2371
1482
  status: "applied",
2372
1483
  ...plan.scaffold ? { scaffold: plan.scaffold } : {}
2373
1484
  };
@@ -2382,51 +1493,13 @@ const initCommandDefinition = {
2382
1493
  description: "Create a ViteHub app in a folder, or set up an existing Vite or Nuxt app, with a host and features.",
2383
1494
  name: "init",
2384
1495
  run: runInit,
2385
- usage: usage$1
1496
+ usage: usage$2
2386
1497
  };
2387
1498
  //#endregion
2388
- //#region ../internal/dist/definition-catalog.js
2389
- const ignoredDirs = /* @__PURE__ */ new Set([
2390
- "node_modules",
2391
- "dist",
2392
- ".output",
2393
- ".nuxt",
2394
- ".vercel",
2395
- ".git",
2396
- ".vitehub"
2397
- ]);
2398
- function readDirEntries(root) {
2399
- try {
2400
- return readdirSync(root, { withFileTypes: true });
2401
- } catch (error) {
2402
- if (error.code === "ENOENT") return [];
2403
- throw error;
2404
- }
2405
- }
2406
- function isGitRepositoryDirectory(directory) {
2407
- return existsSync(resolve(directory, ".git"));
2408
- }
2409
- function listMatchingFiles(root, predicate, options = {}) {
2410
- const files = [];
2411
- for (const entry of readDirEntries(root)) {
2412
- const absolute = resolve(root, entry.name);
2413
- if (entry.isDirectory() && !entry.isSymbolicLink()) {
2414
- if (isGitRepositoryDirectory(absolute)) continue;
2415
- if (entry.name.startsWith(".")) continue;
2416
- if (ignoredDirs.has(entry.name)) continue;
2417
- files.push(...listMatchingFiles(absolute, predicate, options));
2418
- continue;
2419
- }
2420
- if (entry.name.startsWith(".") && !options.includeHidden) continue;
2421
- if (entry.isFile() && predicate(entry.name)) files.push(absolute);
2422
- }
2423
- return files.sort();
2424
- }
2425
- //#endregion
2426
1499
  //#region src/setup/remove.ts
2427
- const usage = "vitehub remove <feature...> [--dry-run] [--yes] [--keep-files] [--force] [--no-uninstall] [--json]";
2428
- function invalid(message) {
2429
- return cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${message} Usage: ${usage}` });
1500
+ const usage$1 = "vitehub remove <feature...> [--dry-run] [--yes] [--keep-files] [--force] [--no-uninstall] [--json]";
1501
+ function invalid$1(message) {
1502
+ return cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${message} Usage: ${usage$1}` });
2430
1503
  }
2431
1504
  /** Reads the arguments. Throws `CLI_R0003` for an unknown flag or feature. */
2432
1505
  function readRemoveArgs(args) {
@@ -2447,9 +1520,9 @@ function readRemoveArgs(args) {
2447
1520
  else if (arg === "--force") parsed.force = true;
2448
1521
  else if (arg === "--no-uninstall") parsed.uninstall = false;
2449
1522
  else if (arg === "-h" || arg === "--help") parsed.help = true;
2450
- else if (arg.startsWith("-")) throw invalid(`Unknown argument ${JSON.stringify(arg)}.`);
1523
+ else if (arg.startsWith("-")) throw invalid$1(`Unknown argument ${JSON.stringify(arg)}.`);
2451
1524
  else {
2452
- const id = readFeatureId(arg, usage);
1525
+ const id = readFeatureId(arg, usage$1);
2453
1526
  if (!parsed.features.includes(id)) parsed.features.push(id);
2454
1527
  }
2455
1528
  return parsed;
@@ -2465,11 +1538,9 @@ function rerunCommand(args) {
2465
1538
  ...args.json ? ["--json"] : []
2466
1539
  ].join(" ");
2467
1540
  }
2468
- /** The `vite-hub` subpath of a feature, such as `vite-hub/rate-limit`. */
2469
1541
  function runtimeModule(id) {
2470
1542
  return `vite-hub/${id === "sandboxTask" ? "sandbox/task" : id.replace(/[A-Z]/gu, (char) => `-${char.toLowerCase()}`)}`;
2471
1543
  }
2472
- /** The package of an import, such as `@vite-hub/schedule` for `@vite-hub/schedule/vite`. */
2473
1544
  function packageName(specifier) {
2474
1545
  const parts = specifier.split("/");
2475
1546
  return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
@@ -2477,7 +1548,6 @@ function packageName(specifier) {
2477
1548
  function importsModule(specifier, module) {
2478
1549
  return specifier === module || specifier.startsWith(`${module}/`);
2479
1550
  }
2480
- /** Imports (including static template literals), re-exports, module augmentations, and triple-slash type references. Comments can match, which only makes `remove` stricter. */
2481
1551
  const specifierPattern = /(?:\b(?:from|import|require|declare\s+module)(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\r\n]*)*(?:\((?:\s|\/\*[\s\S]*?\*\/|\/\/[^\r\n]*)*)?|\/\/\/\s*<reference\s+types\s*=\s*)(?:(["'])([^"'\r\n]+)\1|`((?:[^`$\r\n]|\$(?!\{))+)`)/gu;
2482
1552
  const sourceFile = /\.(?:[cm]?[jt]sx?|vue|svelte|astro|mdx?|html?)$/iu;
2483
1553
  function lineAt(content, index) {
@@ -2485,7 +1555,6 @@ function lineAt(content, index) {
2485
1555
  for (let cursor = content.indexOf("\n"); cursor !== -1 && cursor < index; cursor = content.indexOf("\n", cursor + 1)) line++;
2486
1556
  return line;
2487
1557
  }
2488
- /** True when `content` equals the current or an earlier starter template for the Definition at `path`. */
2489
1558
  function isStarter(starter, path, content) {
2490
1559
  const parts = path.replace(/\.[^./]+$/u, "").split("/");
2491
1560
  const name = [
@@ -2495,7 +1564,6 @@ function isStarter(starter, path, content) {
2495
1564
  ].find((candidate) => candidate && starter.file(candidate) === path);
2496
1565
  return name !== void 0 && [starter.template, ...starter.previousTemplates ?? []].some((template) => template(name) === content);
2497
1566
  }
2498
- /** Features required by selected options. Unknown options can select any supported prerequisite. */
2499
1567
  function optionPrerequisites(id, value, unknown) {
2500
1568
  const options = isRecord$1(value) ? value : void 0;
2501
1569
  if (id === "cache" && (unknown || options?.driver === "kv")) return ["kv"];
@@ -2520,8 +1588,8 @@ async function planSetupRemove(project, args, env) {
2520
1588
  if (host === "unknown") throw manual(project.config && !project.config.ok ? project.config.reason : "dynamic-options");
2521
1589
  const keys = project.config?.ok ? project.config.site.keys : {};
2522
1590
  const before = project.configFile ? await readFile(join(project.root, project.configFile), "utf8") : "";
2523
- const simulate = (edits) => {
2524
- if (!edits.length) return { status };
1591
+ const simulate = (edits, withoutDefinitions) => {
1592
+ if (!edits.length) return { status: withoutDefinitions ? setupStatus(project, env, withoutDefinitions) : status };
2525
1593
  if (!project.config?.ok || !project.configFile) throw manual(project.config && !project.config.ok ? project.config.reason : "no-vitehub");
2526
1594
  const result = editViteHubConfig(project.configFile, before, edits);
2527
1595
  if (!result.ok) throw manual(result.reason);
@@ -2530,10 +1598,18 @@ async function planSetupRemove(project, args, env) {
2530
1598
  status: setupStatus({
2531
1599
  ...project,
2532
1600
  config: locateViteHubConfig(project.configFile, result.code)
2533
- }, env)
1601
+ }, env, withoutDefinitions)
2534
1602
  };
2535
1603
  };
2536
1604
  const enabled = (state, id) => state.features.find((item) => item.id === id);
1605
+ const impliedRemoval = (state, id) => {
1606
+ const disabled = state.features.filter((item) => item.enabled === "off" && item.reason === "config").map((item) => item.id);
1607
+ const by = state.features.filter((item) => item.enabled === "on" && item.reason !== "implied" && impliedFeatures([item.id], disabled).includes(id)).map((item) => item.id);
1608
+ return setupFailure(cliErrorDiagnostics.SETUP_FEATURE_IMPLIED({
1609
+ by: by.join(", "),
1610
+ feature: id
1611
+ }), setupExitCodes.conflict, { data: { impliedBy: by } });
1612
+ };
2537
1613
  const edits = /* @__PURE__ */ new Map();
2538
1614
  for (const id of args.features) {
2539
1615
  const current = keys[id];
@@ -2546,19 +1622,14 @@ async function planSetupRemove(project, args, env) {
2546
1622
  const deleted = simulate([...edits.values()]).status;
2547
1623
  const blocking = [];
2548
1624
  const directories = project.serverDirs ?? [];
1625
+ const discovered = /* @__PURE__ */ new Set();
2549
1626
  for (const id of args.features) {
2550
1627
  const state = enabled(deleted, id);
2551
1628
  if (state.enabled === "off") continue;
2552
- if (state.reason === "implied" && !args.force) {
2553
- const disabled = deleted.features.filter((item) => item.enabled === "off" && item.reason === "config").map((item) => item.id);
2554
- const by = deleted.features.filter((item) => item.enabled === "on" && item.reason !== "implied" && impliedFeatures([item.id], host, disabled).includes(id)).map((item) => item.id);
2555
- throw setupFailure(cliErrorDiagnostics.SETUP_FEATURE_IMPLIED({
2556
- by: by.join(", "),
2557
- feature: id
2558
- }), setupExitCodes.conflict, { data: { impliedBy: by } });
2559
- }
1629
+ if (state.reason === "implied" && !args.force) throw impliedRemoval(deleted, id);
2560
1630
  if (state.reason === "default" && !features[id].enabledByDefault && state.enabled === "on") {
2561
- for (const directory of directories) for (const name of features[id].enabledByDiscovery ?? []) if (existsSync(join(directory, name))) blocking.push({
1631
+ if (features[id].definition) discovered.add(id);
1632
+ else for (const directory of directories) for (const name of features[id].enabledByDiscovery ?? []) if (hasDefinitionFiles(join(directory, name))) blocking.push({
2562
1633
  feature: id,
2563
1634
  file: relative(project.root, join(directory, name))
2564
1635
  });
@@ -2581,7 +1652,7 @@ async function planSetupRemove(project, args, env) {
2581
1652
  return key?.kind === "literal" ? key.value : void 0;
2582
1653
  };
2583
1654
  for (const id of turnedOff) {
2584
- const by = remaining.filter((dependent) => optionPrerequisites(dependent, valueOf(afterKeys, dependent), enabled(after.status, dependent).enabled === "unknown").includes(id));
1655
+ const by = remaining.filter((dependent) => optionPrerequisites(dependent, valueOf(afterKeys, dependent), enabled(after.status, dependent).enabled === "unknown" && enabled(after.status, dependent).reason === "config").includes(id));
2585
1656
  if (by.length) throw setupFailure(cliErrorDiagnostics.SETUP_FEATURE_REQUIRED({
2586
1657
  by: by.join(", "),
2587
1658
  feature: id
@@ -2644,6 +1715,22 @@ async function planSetupRemove(project, args, env) {
2644
1715
  references: list
2645
1716
  }), setupExitCodes.conflict, { data: { references: blocking } });
2646
1717
  }
1718
+ const emptied = new Set(args.keepFiles ? [] : [...discovered].filter((id) => !blocking.some((item) => item.feature === id)));
1719
+ const withoutKeys = (omit) => [...edits].flatMap(([id, edit]) => !omit.has(id) ? [edit] : keys[id] ? [{
1720
+ key: id,
1721
+ op: "delete"
1722
+ }] : []);
1723
+ let written = after;
1724
+ if (emptied.size) {
1725
+ const projected = simulate(withoutKeys(emptied), emptied);
1726
+ const redundant = /* @__PURE__ */ new Set();
1727
+ for (const id of emptied) {
1728
+ const state = enabled(projected.status, id);
1729
+ if (state.reason === "implied" && !args.force) throw impliedRemoval(projected.status, id);
1730
+ if (state.enabled === "off") redundant.add(id);
1731
+ }
1732
+ written = simulate(withoutKeys(redundant), emptied);
1733
+ }
2647
1734
  const prod = [];
2648
1735
  const dev = [];
2649
1736
  for (const id of wasEnabled) {
@@ -2656,10 +1743,10 @@ async function planSetupRemove(project, args, env) {
2656
1743
  const uninstall = [...prod, ...dev];
2657
1744
  const command = uninstall.length ? [project.packageManager, ...uninstallArgs(project.packageManager, uninstall)].join(" ") : void 0;
2658
1745
  const changes = [];
2659
- if (after.code !== void 0 && after.code !== before) changes.push({
2660
- after: after.code,
1746
+ if (written.code !== void 0 && written.code !== before) changes.push({
1747
+ after: written.code,
2661
1748
  before,
2662
- diff: setupDiff(project.configFile, before, after.code),
1749
+ diff: setupDiff(project.configFile, before, written.code),
2663
1750
  kind: "patch",
2664
1751
  path: project.configFile
2665
1752
  });
@@ -2689,7 +1776,13 @@ async function planSetupRemove(project, args, env) {
2689
1776
  path,
2690
1777
  reason: "edited"
2691
1778
  });
2692
- const nextSteps = [];
1779
+ const configPatch = written.code !== void 0 && written.code !== before ? {
1780
+ after: written.code,
1781
+ before,
1782
+ path: project.configFile
1783
+ } : void 0;
1784
+ const restartRequired = !configPatch && deletes.length > 0 && emptied.size > 0;
1785
+ const nextSteps = restartRequired ? ["Restart the dev server to load the new feature configuration."] : [];
2693
1786
  if (command && !args.uninstall) nextSteps.push(`Uninstall the packages: ${command}`);
2694
1787
  if (edited.length) nextSteps.push(`${edited.join(", ")} stayed because ${edited.length === 1 ? "it differs" : "they differ"} from the starter. Delete or move ${edited.length === 1 ? "it" : "them"} by hand.`);
2695
1788
  const hosted = host === "node" ? [] : turnedOff.flatMap((id) => {
@@ -2718,15 +1811,11 @@ async function planSetupRemove(project, args, env) {
2718
1811
  ...command ? { command } : {}
2719
1812
  }
2720
1813
  },
1814
+ restartRequired,
2721
1815
  uninstall,
2722
- ...after.code !== void 0 && after.code !== before ? { configFile: {
2723
- after: after.code,
2724
- before,
2725
- path: project.configFile
2726
- } } : {}
1816
+ ...configPatch ? { configFile: configPatch } : {}
2727
1817
  };
2728
1818
  }
2729
- /** Deletes `path` and then each folder that is empty after it, such as the `server/queues` that `add` created. */
2730
1819
  async function deleteStarter(root, path) {
2731
1820
  await rm(join(root, path));
2732
1821
  for (let folder = dirname(join(root, path)); folder !== root && folder.startsWith(`${root}/`); folder = dirname(folder)) {
@@ -2779,7 +1868,7 @@ async function runRemove(args, context) {
2779
1868
  try {
2780
1869
  parsed = readRemoveArgs(args);
2781
1870
  if (parsed.help) {
2782
- context.stdout.write(`Usage: ${usage}\n\n${removeCommand.description}\n`);
1871
+ context.stdout.write(`Usage: ${usage$1}\n\n${removeCommand.description}\n`);
2783
1872
  return setupExitCodes.done;
2784
1873
  }
2785
1874
  if (!parsed.features.length) throw setupFailure(cliErrorDiagnostics.SETUP_INPUT_NEEDED({ message: "[vitehub] Name at least one feature, such as `vitehub remove kv`." }), setupExitCodes.inputNeeded, { missing: [{
@@ -2822,6 +1911,442 @@ const removeCommand = {
2822
1911
  description: "Turn off features: edit vitehub() options, delete unchanged starter Definitions, and uninstall unused packages. Reads the config without running it.",
2823
1912
  name: "remove",
2824
1913
  run: runRemove,
1914
+ usage: usage$1
1915
+ };
1916
+ //#endregion
1917
+ //#region src/setup/update.ts
1918
+ const usage = "vitehub update [--preview <commit>] [--dry-run] [--no-install] [--json]";
1919
+ const previewBase = "https://pkg.pr.new/vite-hub/vitehub";
1920
+ const defaultRegistry = "https://registry.npmjs.org/";
1921
+ const dependencyFields = [
1922
+ "dependencies",
1923
+ "devDependencies",
1924
+ "optionalDependencies"
1925
+ ];
1926
+ function isViteHubPackage(name) {
1927
+ return name === "vite-hub" || /^@vite-hub\/[a-z0-9][\w.-]*$/u.test(name);
1928
+ }
1929
+ function overrideTarget(key) {
1930
+ let part = key.split(">").at(-1).replace(/^\*\*\//u, "");
1931
+ const scoped = part.lastIndexOf("/@");
1932
+ if (scoped >= 0) part = part.slice(scoped + 1);
1933
+ else if (!part.startsWith("@") && part.includes("/")) part = part.slice(part.lastIndexOf("/") + 1);
1934
+ const name = part.replace(/(?<=.)@.*$/u, "");
1935
+ return isViteHubPackage(name) ? name : void 0;
1936
+ }
1937
+ function isReplaceable(specifier) {
1938
+ return specifier.startsWith(`${previewBase}/`) || specifier === "latest" || specifier === "next" || semver.validRange(specifier) !== null;
1939
+ }
1940
+ function nextSpecifier(name, current, place, target) {
1941
+ if ("preview" in target) return target.url(name);
1942
+ const version = target.versions.get(name);
1943
+ if (place === "override") return version;
1944
+ return `${/^[\^~]/u.exec(current)?.[0] ?? (semver.valid(current) ? "" : "^")}${version}`;
1945
+ }
1946
+ function isObject(value) {
1947
+ return !!value && typeof value === "object" && !Array.isArray(value);
1948
+ }
1949
+ function visitManifest(manifest, visit) {
1950
+ const entries = (holder, place, nameOf) => {
1951
+ if (!isObject(holder)) return;
1952
+ for (const [key, value] of Object.entries(holder)) {
1953
+ const name = nameOf(key);
1954
+ if (typeof value === "string") {
1955
+ if (name && isReplaceable(value)) visit(holder, key, {
1956
+ name,
1957
+ place
1958
+ });
1959
+ } else if (place === "override" && isObject(value)) {
1960
+ if (name && typeof value["."] === "string" && isReplaceable(value["."])) visit(value, ".", {
1961
+ name,
1962
+ place
1963
+ });
1964
+ entries(value, place, overrideTarget);
1965
+ }
1966
+ }
1967
+ };
1968
+ const plainName = (key) => isViteHubPackage(key) ? key : void 0;
1969
+ for (const field of dependencyFields) entries(manifest[field], "dependency", plainName);
1970
+ entries(manifest.overrides, "override", overrideTarget);
1971
+ entries(manifest.resolutions, "override", overrideTarget);
1972
+ if (isObject(manifest.pnpm)) entries(manifest.pnpm.overrides, "override", overrideTarget);
1973
+ if (isObject(manifest.workspaces)) {
1974
+ entries(manifest.workspaces.catalog, "dependency", plainName);
1975
+ if (isObject(manifest.workspaces.catalogs)) for (const catalog of Object.values(manifest.workspaces.catalogs)) entries(catalog, "dependency", plainName);
1976
+ }
1977
+ }
1978
+ function unquote(text) {
1979
+ const quote = text[0] === "'" || text[0] === "\"" ? text[0] : "";
1980
+ return quote && text.endsWith(quote) && text.length > 1 ? {
1981
+ quote,
1982
+ value: text.slice(1, -1)
1983
+ } : {
1984
+ quote: "",
1985
+ value: text
1986
+ };
1987
+ }
1988
+ function readYamlEntry(line) {
1989
+ const match = /^(\s+)("[^"]+"|'[^']+'|[^\s#'"][^:#]*?):\s+(.+?)(\s+#.*)?$/u.exec(line);
1990
+ if (!match) return;
1991
+ const [, indent, rawKey, rawValue, comment = ""] = match;
1992
+ const key = unquote(rawKey).value;
1993
+ const { quote, value } = unquote(rawValue);
1994
+ if (value.startsWith("{") || value.startsWith("[") || value.startsWith("&") || value.startsWith("*")) return;
1995
+ return {
1996
+ key,
1997
+ line: (next) => `${indent}${rawKey}: ${quote}${next}${quote}${comment}`,
1998
+ value
1999
+ };
2000
+ }
2001
+ function topLevelKey(line) {
2002
+ if (!line || /^\s/u.test(line) || line.startsWith("#") || line.startsWith("-")) return;
2003
+ return /^("[^"]+"|'[^']+'|[^:#\s]+):/u.exec(line)?.[1]?.replace(/^["']|["']$/gu, "");
2004
+ }
2005
+ function yamlBlocks(lines) {
2006
+ const blocks = /* @__PURE__ */ new Map();
2007
+ let current;
2008
+ for (const [index, line] of lines.entries()) {
2009
+ const key = topLevelKey(line);
2010
+ if (key === void 0) continue;
2011
+ if (current) blocks.get(current).end = index;
2012
+ current = key;
2013
+ blocks.set(key, {
2014
+ end: lines.length,
2015
+ start: index
2016
+ });
2017
+ }
2018
+ return blocks;
2019
+ }
2020
+ function yamlList(lines, range) {
2021
+ if (!range) return [];
2022
+ const inline = /^[^:]+:\s*\[(.*)\]\s*(#.*)?$/u.exec(lines[range.start]);
2023
+ if (inline) return inline[1].split(",").map((item) => ({
2024
+ index: range.start,
2025
+ value: unquote(item.trim()).value
2026
+ })).filter((item) => item.value);
2027
+ return lines.slice(range.start + 1, range.end).flatMap((line, offset) => {
2028
+ const match = /^\s+-\s+(.+?)(\s+#.*)?$/u.exec(line);
2029
+ return match ? [{
2030
+ index: range.start + 1 + offset,
2031
+ value: unquote(match[1]).value
2032
+ }] : [];
2033
+ });
2034
+ }
2035
+ function pinnedName(entry) {
2036
+ const at = entry.indexOf("@", entry.startsWith("@") ? 1 : 0);
2037
+ return at > 0 ? entry.slice(0, at) : void 0;
2038
+ }
2039
+ const releaseAgePatterns = ["vite-hub", "@vite-hub/*"];
2040
+ function editYamlEntries(lines, edit) {
2041
+ const blocks = yamlBlocks(lines);
2042
+ const removed = /* @__PURE__ */ new Set();
2043
+ for (const [block, place] of [
2044
+ ["overrides", "override"],
2045
+ ["catalog", "dependency"],
2046
+ ["catalogs", "dependency"]
2047
+ ]) {
2048
+ const range = blocks.get(block);
2049
+ if (!range) continue;
2050
+ for (let index = range.start + 1; index < range.end; index++) {
2051
+ const entry = readYamlEntry(lines[index]);
2052
+ const name = entry && (place === "override" ? overrideTarget(entry.key) : isViteHubPackage(entry.key) ? entry.key : void 0);
2053
+ if (!entry || !name || !isReplaceable(entry.value)) continue;
2054
+ const next = edit(name, entry.value, place);
2055
+ if (next === null) removed.add(index);
2056
+ else if (next !== void 0) lines[index] = entry.line(next);
2057
+ }
2058
+ }
2059
+ return removed;
2060
+ }
2061
+ function updateWorkspaceYaml(text, edit, options) {
2062
+ const lines = text.split("\n");
2063
+ const removed = editYamlEntries(lines, edit);
2064
+ const blocks = yamlBlocks(lines);
2065
+ if (!options.preview) {
2066
+ const range = blocks.get("minimumReleaseAgeExclude");
2067
+ const items = yamlList(lines, range);
2068
+ const isInline = range && /:\s*\[/u.test(lines[range.start]);
2069
+ if (range && !isInline) {
2070
+ for (const item of items) {
2071
+ const name = pinnedName(item.value);
2072
+ if (name && isViteHubPackage(name)) removed.add(item.index);
2073
+ }
2074
+ const missing = releaseAgePatterns.filter((pattern) => !items.some((item) => item.value === pattern));
2075
+ const indent = /^(\s+)-/u.exec(lines[items[0]?.index ?? -1] ?? "")?.[1] ?? " ";
2076
+ if (missing.length) lines[range.start] = `${lines[range.start]}\n${missing.map((pattern) => `${indent}- '${pattern}'`).join("\n")}`;
2077
+ } else if (!range) lines.splice(lines.at(-1) === "" ? -1 : lines.length, 0, ...text.trim() ? [""] : [], "# Let new ViteHub releases install without waiting for minimumReleaseAge.", "minimumReleaseAgeExclude:", ...releaseAgePatterns.map((pattern) => ` - '${pattern}'`));
2078
+ } else {
2079
+ const range = blocks.get("blockExoticSubdeps");
2080
+ if (range) lines[range.start] = lines[range.start].replace(/^(blockExoticSubdeps:\s*)true\b/u, "$1false");
2081
+ else lines.splice(lines.at(-1) === "" ? -1 : lines.length, 0, ...text.trim() ? [""] : [], "# pkg.pr.new builds depend on other pkg.pr.new builds.", "blockExoticSubdeps: false");
2082
+ }
2083
+ const after = lines.filter((_, index) => !removed.has(index)).join("\n");
2084
+ return after.endsWith("\n") || !after ? after : `${after}\n`;
2085
+ }
2086
+ async function workspaceFolders(root, patterns) {
2087
+ const find = async (selected) => {
2088
+ if (!selected.length) return /* @__PURE__ */ new Set();
2089
+ const folders = /* @__PURE__ */ new Set();
2090
+ const files = glob(selected.map((pattern) => `${pattern.replace(/\/+$/u, "")}/package.json`), {
2091
+ cwd: root,
2092
+ exclude: (path) => path.split(/[\\/]/u).includes("node_modules")
2093
+ });
2094
+ for await (const file of files) folders.add(dirname(file.replaceAll("\\", "/")));
2095
+ return folders;
2096
+ };
2097
+ const included = await find(patterns.filter((pattern) => !pattern.startsWith("!")));
2098
+ const excluded = await find(patterns.filter((pattern) => pattern.startsWith("!")).map((pattern) => pattern.slice(1)));
2099
+ return [...included].filter((folder) => !excluded.has(folder)).sort();
2100
+ }
2101
+ function workspacePatterns(yaml, manifest) {
2102
+ if (yaml !== void 0) {
2103
+ const lines = yaml.split("\n");
2104
+ return yamlList(lines, yamlBlocks(lines).get("packages")).map((item) => item.value);
2105
+ }
2106
+ const workspaces = manifest.workspaces;
2107
+ return (Array.isArray(workspaces) ? workspaces : isObject(workspaces) && Array.isArray(workspaces.packages) ? workspaces.packages : []).filter((item) => typeof item === "string");
2108
+ }
2109
+ async function workspaceRoot(start) {
2110
+ if (setupLockfiles.some(([file]) => existsSync(join(start, file)))) return start;
2111
+ for (let folder = dirname(start), last = start; folder !== last; last = folder, folder = dirname(folder)) {
2112
+ if (existsSync(join(folder, "pnpm-workspace.yaml"))) return folder;
2113
+ const manifest = join(folder, "package.json");
2114
+ if (!existsSync(manifest)) continue;
2115
+ const patterns = workspacePatterns(void 0, await readJson(manifest));
2116
+ if (patterns.length && (await workspaceFolders(folder, patterns)).includes(relative(folder, start))) return folder;
2117
+ }
2118
+ return start;
2119
+ }
2120
+ async function readJson(file) {
2121
+ const value = JSON.parse(await readFile(file, "utf8"));
2122
+ return isObject(value) ? value : {};
2123
+ }
2124
+ function stringifyLike(before, value) {
2125
+ const indent = /^[ \t]+(?=")/mu.exec(before)?.[0] ?? " ";
2126
+ return `${JSON.stringify(value, null, indent)}${before.endsWith("\n") ? "\n" : ""}`;
2127
+ }
2128
+ /** The command that installs the new specifiers. pnpm resolves ViteHub peers again only with `update`. */
2129
+ function updateInstallArgs(packageManager, workspace) {
2130
+ if (packageManager === "pnpm") return [
2131
+ "update",
2132
+ ...workspace ? ["--recursive"] : [],
2133
+ "vite-hub",
2134
+ "@vite-hub/*"
2135
+ ];
2136
+ return ["install"];
2137
+ }
2138
+ function invalid(message) {
2139
+ return cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${message} Usage: ${usage}` });
2140
+ }
2141
+ /** Reads the arguments. Throws `CLI_R0003` for an unknown flag or a value that is not a commit. */
2142
+ function readUpdateArgs(args) {
2143
+ const parsed = {
2144
+ dryRun: false,
2145
+ help: false,
2146
+ install: true,
2147
+ json: false
2148
+ };
2149
+ for (let index = 0; index < args.length; index++) {
2150
+ const arg = args[index];
2151
+ if (arg === "--json") parsed.json = true;
2152
+ else if (arg === "--dry-run") parsed.dryRun = true;
2153
+ else if (arg === "--no-install") parsed.install = false;
2154
+ else if (arg === "-h" || arg === "--help") parsed.help = true;
2155
+ else if (arg === "--preview" || arg.startsWith("--preview=")) {
2156
+ const value = arg.includes("=") ? arg.slice(arg.indexOf("=") + 1) : args[++index];
2157
+ if (!value || !/^[0-9a-f]{7,40}$/u.test(value)) throw invalid(`--preview needs a commit SHA of vite-hub/vitehub, such as \`--preview 01898b8\`. Got ${JSON.stringify(value ?? "")}.`);
2158
+ parsed.preview = value;
2159
+ } else throw invalid(`Unknown argument ${JSON.stringify(arg)}.`);
2160
+ }
2161
+ return parsed;
2162
+ }
2163
+ async function resolvePackages(names, preview, context) {
2164
+ const request = context.fetch ?? fetch;
2165
+ const registry = (context.env.npm_config_registry || defaultRegistry).replace(/\/?$/u, "/");
2166
+ const url = (name) => `${previewBase}/${name}@${preview}`;
2167
+ const versions = /* @__PURE__ */ new Map();
2168
+ const missing = [];
2169
+ await Promise.all(names.map(async (name) => {
2170
+ const target = preview ? url(name) : `${registry}${name.replace("/", "%2f")}/latest`;
2171
+ let response;
2172
+ try {
2173
+ response = await request(target, preview ? { method: "HEAD" } : { headers: { accept: "application/json" } });
2174
+ } catch (error) {
2175
+ throw cliErrorDiagnostics.CLI_UPDATE_REQUEST_FAILED({
2176
+ status: error instanceof Error ? error.message : String(error),
2177
+ url: target
2178
+ });
2179
+ }
2180
+ if (response.status === 404) {
2181
+ missing.push(name);
2182
+ return;
2183
+ }
2184
+ if (!response.ok) throw cliErrorDiagnostics.CLI_UPDATE_REQUEST_FAILED({
2185
+ status: response.status,
2186
+ url: target
2187
+ });
2188
+ if (preview) return;
2189
+ const body = await response.json();
2190
+ const version = isObject(body) && typeof body.version === "string" ? body.version : void 0;
2191
+ if (!version) throw cliErrorDiagnostics.CLI_UPDATE_REQUEST_FAILED({
2192
+ status: "a response without a version",
2193
+ url: target
2194
+ });
2195
+ versions.set(name, version);
2196
+ }));
2197
+ return {
2198
+ missing: missing.sort(),
2199
+ resolved: {
2200
+ ...preview ? { preview } : {},
2201
+ url,
2202
+ versions
2203
+ }
2204
+ };
2205
+ }
2206
+ /** Plans the update: finds every ViteHub specifier, resolves the target, and computes the new files. Writes nothing. */
2207
+ async function planSetupUpdate(rootDir, args, context) {
2208
+ const root = await workspaceRoot(rootDir);
2209
+ const rootManifestFile = join(root, "package.json");
2210
+ if (!existsSync(rootManifestFile)) throw cliErrorDiagnostics.SETUP_NOT_A_PROJECT({ root });
2211
+ const rootManifest = await readJson(rootManifestFile);
2212
+ const { packageManager } = detectPackageManager(root, rootManifest, context.env);
2213
+ const yamlFile = join(root, "pnpm-workspace.yaml");
2214
+ const yamlBefore = existsSync(yamlFile) ? await readFile(yamlFile, "utf8") : void 0;
2215
+ const folders = [".", ...(await workspaceFolders(root, workspacePatterns(yamlBefore, rootManifest))).filter((folder) => folder !== ".")];
2216
+ const manifests = await Promise.all(folders.map(async (folder) => {
2217
+ const path = join(root, folder, "package.json");
2218
+ return {
2219
+ before: await readFile(path, "utf8"),
2220
+ path,
2221
+ value: await readJson(path)
2222
+ };
2223
+ }));
2224
+ const places = /* @__PURE__ */ new Map();
2225
+ const note = (name, place) => places.set(name, (places.get(name) ?? /* @__PURE__ */ new Set()).add(place));
2226
+ for (const manifest of manifests) visitManifest(manifest.value, (_, __, found) => note(found.name, found.place));
2227
+ if (yamlBefore !== void 0) editYamlEntries(yamlBefore.split("\n"), (name, _, place) => {
2228
+ note(name, place);
2229
+ });
2230
+ if (!places.size) throw cliErrorDiagnostics.CLI_UPDATE_NO_PACKAGES({ root });
2231
+ const { missing, resolved } = await resolvePackages([...places.keys()].sort(), args.preview, context);
2232
+ const blocking = missing.filter((name) => places.get(name).has("dependency"));
2233
+ if (blocking.length) throw setupFailure(cliErrorDiagnostics.CLI_UPDATE_PACKAGE_MISSING({
2234
+ packages: blocking.join(", "),
2235
+ target: args.preview ? `the pkg.pr.new build of ${args.preview}` : "npm"
2236
+ }), setupExitCodes.error);
2237
+ const packages = {};
2238
+ const next = (name, current, place) => {
2239
+ if (missing.includes(name)) return null;
2240
+ const specifier = nextSpecifier(name, current, place, resolved);
2241
+ if (place === "dependency" || !(name in packages)) packages[name] = specifier;
2242
+ return specifier;
2243
+ };
2244
+ const files = [];
2245
+ for (const manifest of manifests) {
2246
+ const direct = /* @__PURE__ */ new Map();
2247
+ for (const field of dependencyFields) {
2248
+ const dependencies = manifest.value[field];
2249
+ if (!isObject(dependencies)) continue;
2250
+ for (const [name, value] of Object.entries(dependencies)) if (isViteHubPackage(name) && typeof value === "string" && isReplaceable(value) && !missing.includes(name)) direct.set(name, nextSpecifier(name, value, "dependency", resolved));
2251
+ }
2252
+ let edited = false;
2253
+ visitManifest(manifest.value, (holder, key, found) => {
2254
+ const current = String(holder[key]);
2255
+ const specifier = found.place === "override" && direct.has(found.name) ? direct.get(found.name) : next(found.name, current, found.place);
2256
+ if (specifier === current) return;
2257
+ edited = true;
2258
+ if (specifier === null) delete holder[key];
2259
+ else holder[key] = specifier;
2260
+ });
2261
+ if (edited) files.push({
2262
+ after: stringifyLike(manifest.before, manifest.value),
2263
+ before: manifest.before,
2264
+ path: manifest.path
2265
+ });
2266
+ }
2267
+ if (yamlBefore !== void 0 || packageManager === "pnpm") {
2268
+ const after = updateWorkspaceYaml(yamlBefore ?? "", next, { preview: !!args.preview });
2269
+ files.push({
2270
+ after,
2271
+ before: yamlBefore ?? "",
2272
+ path: yamlFile
2273
+ });
2274
+ }
2275
+ const changed = files.filter((file) => file.after !== file.before);
2276
+ const installArgs = updateInstallArgs(packageManager, folders.length > 1);
2277
+ return {
2278
+ files: changed,
2279
+ installArgs,
2280
+ packageManager,
2281
+ plan: {
2282
+ changes: changed.map((file) => {
2283
+ const path = relative(root, file.path);
2284
+ return {
2285
+ diff: setupDiff(path, file.before, file.after),
2286
+ kind: file.before ? "patch" : "create",
2287
+ path
2288
+ };
2289
+ }),
2290
+ install: { command: [packageManager, ...installArgs.map((arg) => arg.includes("*") ? `"${arg}"` : arg)].join(" ") },
2291
+ packages: Object.fromEntries(Object.entries(packages).sort(([left], [right]) => left.localeCompare(right))),
2292
+ root,
2293
+ status: changed.length ? "planned" : "unchanged",
2294
+ target: args.preview ? { preview: args.preview } : { version: resolved.versions.get("vite-hub") ?? [...resolved.versions.values()].sort(semver.rcompare)[0] }
2295
+ }
2296
+ };
2297
+ }
2298
+ function targetLabel(target) {
2299
+ return "preview" in target ? `the pkg.pr.new build of ${target.preview}` : target.version;
2300
+ }
2301
+ async function runUpdate(args, context) {
2302
+ let parsed;
2303
+ try {
2304
+ parsed = readUpdateArgs(args);
2305
+ if (parsed.help) {
2306
+ context.stdout.write(`Usage: ${usage}\n\n${updateCommand.description}\n`);
2307
+ return setupExitCodes.done;
2308
+ }
2309
+ const { files, installArgs, packageManager, plan } = await planSetupUpdate(context.rootDir, parsed, context);
2310
+ if (parsed.dryRun || plan.status === "unchanged") {
2311
+ if (parsed.json) writeSetupJson(context, plan);
2312
+ else if (plan.status === "unchanged") context.stdout.write(`ViteHub packages already use ${targetLabel(plan.target)}. Nothing to change.\n`);
2313
+ else {
2314
+ for (const change of plan.changes) context.stdout.write(change.diff.endsWith("\n") ? change.diff : `${change.diff}\n`);
2315
+ context.stdout.write(`${parsed.install ? "Install" : "Then install"}: ${plan.install.command}\n`);
2316
+ }
2317
+ return setupExitCodes.done;
2318
+ }
2319
+ for (const file of files) await writeFile(file.path, file.after);
2320
+ if (parsed.install) {
2321
+ const result = await context.spawn(packageManager, installArgs, {
2322
+ cwd: plan.root,
2323
+ env: context.env,
2324
+ stdout: "stderr"
2325
+ });
2326
+ if (result.exitCode !== 0) throw setupFailure(cliErrorDiagnostics.CLI_UPDATE_INSTALL_FAILED({
2327
+ command: plan.install.command,
2328
+ exitCode: result.exitCode ?? result.signal
2329
+ }), setupExitCodes.error);
2330
+ }
2331
+ const applied = {
2332
+ ...plan,
2333
+ status: "applied"
2334
+ };
2335
+ if (parsed.json) writeSetupJson(context, applied);
2336
+ else {
2337
+ const names = Object.keys(plan.packages);
2338
+ context.stdout.write(`Moved ${names.length} ViteHub ${names.length === 1 ? "package" : "packages"} to ${targetLabel(plan.target)}. Changed ${plan.changes.map((change) => change.path).join(", ")}.\n`);
2339
+ if (!parsed.install) context.stdout.write(`Install the packages: ${plan.install.command}\n`);
2340
+ }
2341
+ return setupExitCodes.done;
2342
+ } catch (error) {
2343
+ return writeSetupError(context, parsed?.json ?? args.includes("--json"), error);
2344
+ }
2345
+ }
2346
+ const updateCommand = {
2347
+ description: "Move vite-hub and every @vite-hub/* package to the latest npm release, or to one pkg.pr.new build with --preview <commit>. Edits dependencies, overrides, and catalogs in every package of the workspace, then installs. Does not load the project config.",
2348
+ name: "update",
2349
+ run: runUpdate,
2825
2350
  usage
2826
2351
  };
2827
2352
  //#endregion
@@ -2836,7 +2361,6 @@ function writeHelp(command, context) {
2836
2361
  context.stdout.write(`Usage: ${command.usage}\n\n${command.description}\n`);
2837
2362
  return setupExitCodes.done;
2838
2363
  }
2839
- /** Runs `body` and reports any error in the setup envelope. */
2840
2364
  async function runSetupCommand(command, args, context, body) {
2841
2365
  const json = args.includes("--json");
2842
2366
  try {
@@ -2880,6 +2404,7 @@ function credentialsLabel(credentials) {
2880
2404
  function writeStatus(status, context) {
2881
2405
  const shown = status.features.filter((feature) => feature.enabled !== "off");
2882
2406
  const off = status.features.length - shown.length;
2407
+ const stack = status.stack ? setupStackLabels(status.stack) : void 0;
2883
2408
  context.stdout.write(`${table([
2884
2409
  ["root", status.root],
2885
2410
  ["framework", status.framework],
@@ -2889,7 +2414,8 @@ function writeStatus(status, context) {
2889
2414
  ["link", linkLabel(status)],
2890
2415
  ["credentials", credentialsLabel(status.credentials)],
2891
2416
  ["live", liveLabel(status)],
2892
- ...status.stack ? [["stack", status.stack.command]] : []
2417
+ ...stack ? [["stack", stack.command]] : [],
2418
+ ...stack?.omissions ? [["stack omissions", stack.omissions]] : []
2893
2419
  ])}\n\n`);
2894
2420
  if (shown.length) context.stdout.write(`${table([[
2895
2421
  "feature",
@@ -2907,10 +2433,6 @@ function writeStatus(status, context) {
2907
2433
  function isCheckoutStatusModule(value) {
2908
2434
  return Object(value) === value && typeof Reflect.get(Object(value), "formatWorkspaceStatus") === "function" && typeof Reflect.get(Object(value), "localCheckoutStatus") === "function";
2909
2435
  }
2910
- /**
2911
- * The checkout folders of `vitehub.lock`, read by the Workspace package that the project installs. Undefined without a
2912
- * lock file. The Workspace package reads only local files here; it never calls the app.
2913
- */
2914
2436
  async function readCheckouts(root) {
2915
2437
  if (!existsSync(join$1(root, "vitehub.lock"))) return void 0;
2916
2438
  const require = createRequire(join$1(root, "package.json"));
@@ -2954,7 +2476,7 @@ const statusCommand = {
2954
2476
  offline,
2955
2477
  signal
2956
2478
  }),
2957
- stack: await readSetupStack(project.root)
2479
+ stack: "manual" in features.config && features.config.manual === "no-vitehub" ? null : await setupStack(project, features)
2958
2480
  };
2959
2481
  const checkouts = await readCheckouts(status.root);
2960
2482
  if (json) {
@@ -3090,6 +2612,7 @@ const setupCommands = [
3090
2612
  initCommandDefinition,
3091
2613
  addCommand,
3092
2614
  removeCommand,
2615
+ updateCommand,
3093
2616
  catalogCommand,
3094
2617
  statusCommand,
3095
2618
  linkCommand,
@@ -3101,4 +2624,4 @@ const setupCommands = [
3101
2624
  whoamiCommand
3102
2625
  ];
3103
2626
  //#endregion
3104
- export { shellQuote as S, setupCatalog as _, readRemoveArgs as a, planSetupAdd as b, initPackages as c, readSetupStack as d, deployCommand as f, readSetupLive as g, deploymentsCommand as h, planSetupRemove as i, nuxiPackage as l, STATUS_HOST_TIMEOUT_MS as m, setupCommands as n, removeCommand as o, readDeployArgs as p, applySetupRemove as r, initCommandDefinition as s, commands_exports as t, readInitArgs as u, addCommand as v, readAddArgs as x, applySetupAdd as y };
2627
+ export { applySetupAdd as _, updateCommand as a, planSetupRemove as c, initCommandDefinition as d, initPackages as f, addCommand as g, setupCatalog as h, readUpdateArgs as i, readRemoveArgs as l, readInitArgs as m, setupCommands as n, updateInstallArgs as o, nuxiPackage as p, planSetupUpdate as r, applySetupRemove as s, commands_exports as t, removeCommand as u, planSetupAdd as v, readAddArgs as y };