@vite-hub/cli 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,20 +1,21 @@
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 { B as readSetupProject, F as uninstallArgs, G as featureSupport, H as featureHosts, J as editViteHubConfig, K as features, L as hasDefinitionFiles, M as installCommand, N as setsOption, P as setupStatus, R as listMatchingFiles, U as featureIds, V as setupLockfiles, W as featurePackages, X as locateViteHubConfig, Y as insertViteHubConfig, Z as __exportAll, c as linkSetupProject, j as installArgs, l as readLinkHostOption, m as unlinkSetupProject, o as gitignoreWithViteHub, q as impliedFeatures, r as SETUP_LINK_FILE, u as readSetupLinkState, z as detectPackageManager } from "./env-B1Gg-WnA.js";
2
+ import { m as cliErrorDiagnostics } from "./provision-DXl97xG0.js";
3
+ import { a as table, i as setupFailure, n as readSetupArgs, o as writeSetupError, r as setupExitCodes, s as writeSetupJson } from "./envelope-B4mPbSbj.js";
4
+ import { l as whoamiCommand, o as loginCommand, s as logoutCommand } from "./console-auth-B0HxFFiX.js";
5
+ import { a as deploymentsCommand, i as STATUS_HOST_TIMEOUT_MS, o as liveLabel, s as readSetupLive, t as deployCommand } from "./deploy-C0RdI5OK.js";
5
6
  import { createRequire } from "node:module";
6
- import { existsSync, readFileSync, readdirSync } from "node:fs";
7
+ import { existsSync, readFileSync } from "node:fs";
7
8
  import process from "node:process";
8
9
  import { basename, dirname, join, relative, resolve } from "pathe";
9
- import { mkdir, readFile, readdir, rm, rmdir, writeFile } from "node:fs/promises";
10
+ import { glob, mkdir, readFile, readdir, rm, rmdir, writeFile } from "node:fs/promises";
10
11
  import { join as join$1 } from "node:path";
11
12
  import { createInterface } from "node:readline/promises";
12
13
  import { pathToFileURL } from "node:url";
13
14
  import { createTwoFilesPatch } from "diff";
14
15
  import { parseArgs } from "node:util";
15
- import { Range, minVersion, subset, validRange } from "semver";
16
+ import semver, { Range, minVersion, subset, validRange } from "semver";
16
17
  //#region src/setup/add.ts
17
- const usage$4 = "vitehub add <feature...> [--name <definition>] [--option <key=value>]... [--dry-run] [--yes] [--no-install] [--json]";
18
+ const usage$3 = "vitehub add <feature...> [--name <definition>] [--option <key=value>]... [--dry-run] [--yes] [--no-install] [--json]";
18
19
  /**
19
20
  * Values that `--option` can choose for an `explicit` host, first the one that `rerun` uses, and the feature that the
20
21
  * value needs. Options without an entry, such as `database.connection`, need a value that only the developer knows.
@@ -62,14 +63,14 @@ function installSpecifiers(packages) {
62
63
  })[0];
63
64
  return packages.map((name) => preview && name.startsWith("@vite-hub/") ? `${preview.base}/${name}@${preview.ref}` : name);
64
65
  }
65
- function invalid$2(message, commandUsage = usage$4) {
66
+ function invalid$3(message, commandUsage = usage$3) {
66
67
  return cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${message} Usage: ${commandUsage}` });
67
68
  }
68
69
  /** 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) {
70
+ function readFeatureId(value, commandUsage = usage$3) {
70
71
  const key = value.replaceAll("-", "").toLowerCase();
71
72
  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);
73
+ if (!id) throw invalid$3(`Unknown feature ${JSON.stringify(value)}. Run \`vitehub catalog\` to list the features.`, commandUsage);
73
74
  return id;
74
75
  }
75
76
  function optionValue(value) {
@@ -107,7 +108,7 @@ function readAddArgs(args) {
107
108
  const [flag, inline] = arg.startsWith("--") && arg.includes("=") ? [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)] : [arg, void 0];
108
109
  const value = () => {
109
110
  const next = inline ?? args[++index];
110
- if (next === void 0 || inline === void 0 && next.startsWith("--")) throw invalid$2(`${flag} needs a value.`);
111
+ if (next === void 0 || inline === void 0 && next.startsWith("--")) throw invalid$3(`${flag} needs a value.`);
111
112
  return next;
112
113
  };
113
114
  if (flag === "--json") parsed.json = true;
@@ -117,18 +118,18 @@ function readAddArgs(args) {
117
118
  else if (flag === "-h" || flag === "--help") parsed.help = true;
118
119
  else if (flag === "--name") parsed.name = value();
119
120
  else if (flag === "--option") rawOptions.push(value());
120
- else if (arg.startsWith("-")) throw invalid$2(`Unknown argument ${JSON.stringify(arg)}.`);
121
+ else if (arg.startsWith("-")) throw invalid$3(`Unknown argument ${JSON.stringify(arg)}.`);
121
122
  else if (!parsed.features.includes(readFeatureId(arg))) parsed.features.push(readFeatureId(arg));
122
123
  }
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\`.`);
124
+ 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
125
  for (const option of rawOptions) {
125
126
  const separator = option.indexOf("=");
126
- if (separator <= 0) throw invalid$2(`--option ${JSON.stringify(option)} must be key=value, such as \`email.driver=resend\`.`);
127
+ if (separator <= 0) throw invalid$3(`--option ${JSON.stringify(option)} must be key=value, such as \`email.driver=resend\`.`);
127
128
  const path = option.slice(0, separator).split(".");
128
129
  const head = featureIds.find((id) => id === path[0]);
129
130
  const id = head ?? (parsed.features.length === 1 ? parsed.features[0] : void 0);
130
131
  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
+ 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\`.`);
132
133
  setPath(parsed.options[id] ??= {}, keys, optionValue(option.slice(separator + 1)));
133
134
  }
134
135
  return parsed;
@@ -144,7 +145,7 @@ function flattenOptions(prefix, value, out = []) {
144
145
  return out;
145
146
  }
146
147
  /** The `vitehub add` command for `args`, with `extra` options and `--yes` unless it is a dry run. */
147
- function rerunCommand$2(args, extra = {}, extraFeatures = []) {
148
+ function rerunCommand$1(args, extra = {}, extraFeatures = []) {
148
149
  const ids = [...args.features, ...extraFeatures.filter((id) => !args.features.includes(id))];
149
150
  const options = [.../* @__PURE__ */ new Set([
150
151
  ...ids,
@@ -201,7 +202,8 @@ function nextValue(id, status, project, options) {
201
202
  return sameValue(literal, merged) ? void 0 : { value: merged };
202
203
  }
203
204
  /** 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) {
205
+ async function planSetupAdd(project, args, env, rerun = rerunCommand$1) {
206
+ if (args.options.observability && Object.hasOwn(args.options.observability, "logs")) throw setupFailure(cliErrorDiagnostics.SETUP_LOGS_OPTION_MOVED(), setupExitCodes.conflict);
205
207
  const status = setupStatus(project, env);
206
208
  const host = status.host.name;
207
209
  if (host === "unknown") {
@@ -238,10 +240,10 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
238
240
  const current = project.config?.ok ? project.config.site.keys[id] : void 0;
239
241
  return mergeValue(current?.kind === "literal" ? current.value : void 0, args.options[id]);
240
242
  };
241
- const inputFeatures = [...args.features, ...impliedFeatures(args.features, host, keep.filter((id) => id !== "database"))];
243
+ const inputFeatures = [...args.features, ...impliedFeatures(args.features, keep.filter((id) => id !== "database"))];
242
244
  if (inputFeatures.includes("database") && keep.includes("database")) requires.push("database");
243
245
  const requireFeature = (required) => {
244
- for (const id of [required, ...impliedFeatures([required], host, keep.filter((id) => id !== "database"))]) {
246
+ for (const id of [required, ...impliedFeatures([required], keep.filter((id) => id !== "database"))]) {
245
247
  if (!inputFeatures.includes(id)) inputFeatures.push(id);
246
248
  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
249
  }
@@ -302,9 +304,8 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
302
304
  host
303
305
  }), setupExitCodes.conflict);
304
306
  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
307
  const storageSelected = id === "workflow" && host !== "netlify" && selectsProvider(id, value, host);
307
- if (support.level === "explicit" && !inlineOnly && !storageSelected) {
308
+ if (support.level === "explicit" && !storageSelected) {
308
309
  const key = support.option.slice(id.length + 1);
309
310
  if (!(options && key in options) && !setsOption(project, support.option)) {
310
311
  const choices = optionChoices[support.option];
@@ -331,7 +332,7 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
331
332
  });
332
333
  setPath(defaults.schedule ??= {}, ["providerOutput"], "auto");
333
334
  }
334
- if (!isRecord$1(value) || !isRecord$1(value.runtime) || value.runtime.driver !== "process") {
335
+ if (isRecord$1(value) && value.runtime !== void 0 && (!isRecord$1(value.runtime) || value.runtime.driver !== "process")) {
335
336
  missing.push({
336
337
  choices: ["process"],
337
338
  field: "schedule.runtime.driver"
@@ -349,7 +350,7 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
349
350
  feature: "observability",
350
351
  host
351
352
  }), 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(", ")}.`);
353
+ 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(", ")}.`);
353
354
  if (missing.length) {
354
355
  const fields = missing.map((item) => `\`${item.field}\``).join(", ");
355
356
  throw setupFailure(cliErrorDiagnostics.SETUP_INPUT_NEEDED({ message: `[vitehub] Set ${fields} to add ${args.features.join(", ")} on the ${host} host.` }), setupExitCodes.inputNeeded, {
@@ -359,10 +360,12 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
359
360
  }
360
361
  const edits = [];
361
362
  let expression = false;
363
+ const site = project.config?.ok ? project.config.site : void 0;
362
364
  const addedFeatures = [...args.features, ...requires];
363
365
  for (const id of /* @__PURE__ */ new Set([...addedFeatures, ...inputFeatures.filter((id) => args.options[id])])) {
364
366
  const next = nextValue(id, status, project, args.options[id]);
365
367
  expression ||= next === "expression";
368
+ 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
369
  if (next !== void 0) edits.push({
367
370
  key: id,
368
371
  op: "set",
@@ -371,13 +374,14 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
371
374
  }
372
375
  const changes = [];
373
376
  const files = [];
377
+ let addsDiscovery = false;
374
378
  let configFile;
375
379
  const serverDir = relative(project.root, project.serverDirs?.[0] ?? join(project.root, "server"));
376
380
  const nuxtRoot = project.config?.ok ? project.config.site.nuxt?.keys.rootDir : void 0;
377
381
  const definitionRoot = nuxtRoot?.kind === "literal" && typeof nuxtRoot.value === "string" ? resolve(project.root, nuxtRoot.value) : project.root;
378
382
  if (args.name !== void 0) {
379
383
  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(", ")}.`);
384
+ 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
385
  if (project.framework === "nuxt" && !project.serverDirs?.length) throw setupFailure(cliErrorDiagnostics.SETUP_SERVER_DIR_MANUAL(), setupExitCodes.conflict);
382
386
  for (const id of withStarter) {
383
387
  const starter = features[id].definition;
@@ -404,6 +408,8 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
404
408
  kind: "create",
405
409
  path
406
410
  });
411
+ const previous = status.features.find((item) => item.id === id);
412
+ if (features[id].enabledByDiscovery && site && !site.spread && !site.keys[id] && (previous?.enabled !== "on" || previous.reason === "implied")) addsDiscovery = true;
407
413
  }
408
414
  }
409
415
  if (edits.length) {
@@ -433,7 +439,7 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
433
439
  });
434
440
  }
435
441
  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));
442
+ const implied = impliedFeatures([.../* @__PURE__ */ new Set([...alreadyOn, ...addedFeatures])], keep.filter((id) => !requires.includes(id))).filter((id) => !addedFeatures.includes(id));
437
443
  const enabled = /* @__PURE__ */ new Set([
438
444
  ...alreadyOn,
439
445
  ...addedFeatures,
@@ -453,14 +459,13 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
453
459
  install.prod = installSpecifiers(install.prod);
454
460
  install.dev = installSpecifiers(install.dev);
455
461
  const command = installCommand(project.packageManager, install.prod, install.dev);
456
- const nextSteps = [];
462
+ const restartRequired = addsDiscovery && !configFile;
463
+ const nextSteps = restartRequired ? ["Restart the dev server to load the new feature configuration."] : [];
457
464
  if (command && !args.install) nextSteps.push(`Install the packages: ${command}`);
458
465
  for (const id of implied) {
459
466
  const support = featureSupport(id, host);
460
467
  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}`);
468
+ 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}`);
464
469
  }
465
470
  for (const id of [...addedFeatures, ...implied]) {
466
471
  if (selectsProvider(id, valueFor(id))) continue;
@@ -488,6 +493,7 @@ async function planSetupAdd(project, args, env, rerun = rerunCommand$2) {
488
493
  root: project.root,
489
494
  status: changes.length || command && args.install ? "planned" : "unchanged"
490
495
  },
496
+ restartRequired,
491
497
  ...configFile ? { configFile } : {}
492
498
  };
493
499
  }
@@ -549,7 +555,7 @@ async function runAdd(args, context) {
549
555
  try {
550
556
  parsed = readAddArgs(args);
551
557
  if (parsed.help) {
552
- context.stdout.write(`Usage: ${usage$4}\n\n${addCommand.description}\n`);
558
+ context.stdout.write(`Usage: ${usage$3}\n\n${addCommand.description}\n`);
553
559
  return setupExitCodes.done;
554
560
  }
555
561
  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 +576,7 @@ async function runAdd(args, context) {
570
576
  if (!parsed.json) writePlan$2(plan, context);
571
577
  throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] `vitehub add` changes files and was not confirmed. Without a terminal, pass --yes." }), setupExitCodes.inputNeeded, {
572
578
  data: plan,
573
- rerun: rerunCommand$2(parsed)
579
+ rerun: rerunCommand$1(parsed)
574
580
  });
575
581
  }
576
582
  writePlan$2(plan, context);
@@ -593,7 +599,7 @@ const addCommand = {
593
599
  description: "Turn on features: edit vitehub() options, install packages, and create starter Definitions. Reads the config without running it.",
594
600
  name: "add",
595
601
  run: runAdd,
596
- usage: usage$4
602
+ usage: usage$3
597
603
  };
598
604
  //#endregion
599
605
  //#region src/setup/catalog.ts
@@ -606,1131 +612,8 @@ function setupCatalog() {
606
612
  };
607
613
  }
608
614
  //#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;
847
- 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);
856
- } 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
- return;
874
- }
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
- }
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
- };
980
- }
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}` });
1029
- }
1030
- }
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
1080
- };
1081
- if (json) writeSetupJson(context, output);
1082
- else writeDeployments(output, context);
1083
- return setupExitCodes.done;
1084
- }
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);
1099
- }
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
1114
- });
1115
- } catch {
1116
- return;
1117
- }
1118
- };
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 } : {}
1283
- });
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
- }
1296
- });
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
- }];
1308
- });
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);
1325
- }
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
1428
- });
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
- };
1443
- } 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);
1474
- return {
1475
- host,
1476
- link: links.targets.find((target) => target.host === host)
1477
- };
1478
- }
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
- 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 } : {}
1672
- };
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
- }
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
- //#endregion
1732
615
  //#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]";
616
+ 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]";
1734
617
  /** The command that starts a project. It runs from the `vite-hub` package, so it needs no install. */
1735
618
  const initCommandPrefix = "pnpm dlx vite-hub init";
1736
619
  const initHosts = [
@@ -1785,12 +668,12 @@ const stackEnd = "<!-- /vitehub:stack -->";
1785
668
  function isRecord(value) {
1786
669
  return !!value && typeof value === "object" && !Array.isArray(value);
1787
670
  }
1788
- function invalid$1(message) {
1789
- return cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${message} Usage: ${usage$1}` });
671
+ function invalid$2(message) {
672
+ return cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${message} Usage: ${usage$2}` });
1790
673
  }
1791
674
  function oneOf(flag, value, choices) {
1792
675
  const found = choices.find((choice) => choice === value);
1793
- if (!found) throw invalid$1(`${flag} must be one of ${choices.join(", ")}, not ${JSON.stringify(value)}.`);
676
+ if (!found) throw invalid$2(`${flag} must be one of ${choices.join(", ")}, not ${JSON.stringify(value)}.`);
1794
677
  return found;
1795
678
  }
1796
679
  /** Reads the arguments. Throws `CLI_R0003` for an unknown flag or value. */
@@ -1809,7 +692,7 @@ function readInitArgs(args) {
1809
692
  const [flag, inline] = arg.startsWith("--") && arg.includes("=") ? [arg.slice(0, arg.indexOf("=")), arg.slice(arg.indexOf("=") + 1)] : [arg, void 0];
1810
693
  const value = () => {
1811
694
  const next = inline ?? args[++index];
1812
- if (next === void 0 || inline === void 0 && next.startsWith("--")) throw invalid$1(`${flag} needs a value.`);
695
+ if (next === void 0 || inline === void 0 && next.startsWith("--")) throw invalid$2(`${flag} needs a value.`);
1813
696
  return next;
1814
697
  };
1815
698
  if (flag === "--json") parsed.json = true;
@@ -1822,9 +705,9 @@ function readInitArgs(args) {
1822
705
  else if (flag === "--option") parsed.options.push(value());
1823
706
  else if (flag === "--framework") parsed.framework = oneOf("--framework", value(), frameworks);
1824
707
  else if (flag === "--pm") parsed.pm = oneOf("--pm", value(), packageManagers);
1825
- else if (arg.startsWith("-")) throw invalid$1(`Unknown argument ${JSON.stringify(arg)}.`);
708
+ else if (arg.startsWith("-")) throw invalid$2(`Unknown argument ${JSON.stringify(arg)}.`);
1826
709
  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)}.`);
710
+ else throw invalid$2(`Pass one folder, not ${JSON.stringify(parsed.dir)} and ${JSON.stringify(arg)}.`);
1828
711
  }
1829
712
  if (features !== void 0) parsed.features = readAddArgs(features.split(",").map((item) => item.trim()).filter(Boolean)).features;
1830
713
  return parsed;
@@ -2333,7 +1216,7 @@ async function runInit(rawArgs, context) {
2333
1216
  const parsed = readInitArgs(rawArgs);
2334
1217
  json = parsed.json;
2335
1218
  if (parsed.help) {
2336
- context.stdout.write(`Usage: ${usage$1}\n\n${initCommandDefinition.description}\n`);
1219
+ context.stdout.write(`Usage: ${usage$2}\n\n${initCommandDefinition.description}\n`);
2337
1220
  return setupExitCodes.done;
2338
1221
  }
2339
1222
  const args = await readInputs(parsed);
@@ -2382,51 +1265,13 @@ const initCommandDefinition = {
2382
1265
  description: "Create a ViteHub app in a folder, or set up an existing Vite or Nuxt app, with a host and features.",
2383
1266
  name: "init",
2384
1267
  run: runInit,
2385
- usage: usage$1
1268
+ usage: usage$2
2386
1269
  };
2387
1270
  //#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
1271
  //#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}` });
1272
+ const usage$1 = "vitehub remove <feature...> [--dry-run] [--yes] [--keep-files] [--force] [--no-uninstall] [--json]";
1273
+ function invalid$1(message) {
1274
+ return cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${message} Usage: ${usage$1}` });
2430
1275
  }
2431
1276
  /** Reads the arguments. Throws `CLI_R0003` for an unknown flag or feature. */
2432
1277
  function readRemoveArgs(args) {
@@ -2447,9 +1292,9 @@ function readRemoveArgs(args) {
2447
1292
  else if (arg === "--force") parsed.force = true;
2448
1293
  else if (arg === "--no-uninstall") parsed.uninstall = false;
2449
1294
  else if (arg === "-h" || arg === "--help") parsed.help = true;
2450
- else if (arg.startsWith("-")) throw invalid(`Unknown argument ${JSON.stringify(arg)}.`);
1295
+ else if (arg.startsWith("-")) throw invalid$1(`Unknown argument ${JSON.stringify(arg)}.`);
2451
1296
  else {
2452
- const id = readFeatureId(arg, usage);
1297
+ const id = readFeatureId(arg, usage$1);
2453
1298
  if (!parsed.features.includes(id)) parsed.features.push(id);
2454
1299
  }
2455
1300
  return parsed;
@@ -2520,8 +1365,8 @@ async function planSetupRemove(project, args, env) {
2520
1365
  if (host === "unknown") throw manual(project.config && !project.config.ok ? project.config.reason : "dynamic-options");
2521
1366
  const keys = project.config?.ok ? project.config.site.keys : {};
2522
1367
  const before = project.configFile ? await readFile(join(project.root, project.configFile), "utf8") : "";
2523
- const simulate = (edits) => {
2524
- if (!edits.length) return { status };
1368
+ const simulate = (edits, withoutDefinitions) => {
1369
+ if (!edits.length) return { status: withoutDefinitions ? setupStatus(project, env, withoutDefinitions) : status };
2525
1370
  if (!project.config?.ok || !project.configFile) throw manual(project.config && !project.config.ok ? project.config.reason : "no-vitehub");
2526
1371
  const result = editViteHubConfig(project.configFile, before, edits);
2527
1372
  if (!result.ok) throw manual(result.reason);
@@ -2530,10 +1375,18 @@ async function planSetupRemove(project, args, env) {
2530
1375
  status: setupStatus({
2531
1376
  ...project,
2532
1377
  config: locateViteHubConfig(project.configFile, result.code)
2533
- }, env)
1378
+ }, env, withoutDefinitions)
2534
1379
  };
2535
1380
  };
2536
1381
  const enabled = (state, id) => state.features.find((item) => item.id === id);
1382
+ const impliedRemoval = (state, id) => {
1383
+ const disabled = state.features.filter((item) => item.enabled === "off" && item.reason === "config").map((item) => item.id);
1384
+ const by = state.features.filter((item) => item.enabled === "on" && item.reason !== "implied" && impliedFeatures([item.id], disabled).includes(id)).map((item) => item.id);
1385
+ return setupFailure(cliErrorDiagnostics.SETUP_FEATURE_IMPLIED({
1386
+ by: by.join(", "),
1387
+ feature: id
1388
+ }), setupExitCodes.conflict, { data: { impliedBy: by } });
1389
+ };
2537
1390
  const edits = /* @__PURE__ */ new Map();
2538
1391
  for (const id of args.features) {
2539
1392
  const current = keys[id];
@@ -2546,19 +1399,14 @@ async function planSetupRemove(project, args, env) {
2546
1399
  const deleted = simulate([...edits.values()]).status;
2547
1400
  const blocking = [];
2548
1401
  const directories = project.serverDirs ?? [];
1402
+ const discovered = /* @__PURE__ */ new Set();
2549
1403
  for (const id of args.features) {
2550
1404
  const state = enabled(deleted, id);
2551
1405
  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
- }
1406
+ if (state.reason === "implied" && !args.force) throw impliedRemoval(deleted, id);
2560
1407
  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({
1408
+ if (features[id].definition) discovered.add(id);
1409
+ else for (const directory of directories) for (const name of features[id].enabledByDiscovery ?? []) if (hasDefinitionFiles(join(directory, name))) blocking.push({
2562
1410
  feature: id,
2563
1411
  file: relative(project.root, join(directory, name))
2564
1412
  });
@@ -2581,7 +1429,7 @@ async function planSetupRemove(project, args, env) {
2581
1429
  return key?.kind === "literal" ? key.value : void 0;
2582
1430
  };
2583
1431
  for (const id of turnedOff) {
2584
- const by = remaining.filter((dependent) => optionPrerequisites(dependent, valueOf(afterKeys, dependent), enabled(after.status, dependent).enabled === "unknown").includes(id));
1432
+ 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
1433
  if (by.length) throw setupFailure(cliErrorDiagnostics.SETUP_FEATURE_REQUIRED({
2586
1434
  by: by.join(", "),
2587
1435
  feature: id
@@ -2644,6 +1492,22 @@ async function planSetupRemove(project, args, env) {
2644
1492
  references: list
2645
1493
  }), setupExitCodes.conflict, { data: { references: blocking } });
2646
1494
  }
1495
+ const emptied = new Set(args.keepFiles ? [] : [...discovered].filter((id) => !blocking.some((item) => item.feature === id)));
1496
+ const withoutKeys = (omit) => [...edits].flatMap(([id, edit]) => !omit.has(id) ? [edit] : keys[id] ? [{
1497
+ key: id,
1498
+ op: "delete"
1499
+ }] : []);
1500
+ let written = after;
1501
+ if (emptied.size) {
1502
+ const projected = simulate(withoutKeys(emptied), emptied);
1503
+ const redundant = /* @__PURE__ */ new Set();
1504
+ for (const id of emptied) {
1505
+ const state = enabled(projected.status, id);
1506
+ if (state.reason === "implied" && !args.force) throw impliedRemoval(projected.status, id);
1507
+ if (state.enabled === "off") redundant.add(id);
1508
+ }
1509
+ written = simulate(withoutKeys(redundant), emptied);
1510
+ }
2647
1511
  const prod = [];
2648
1512
  const dev = [];
2649
1513
  for (const id of wasEnabled) {
@@ -2656,10 +1520,10 @@ async function planSetupRemove(project, args, env) {
2656
1520
  const uninstall = [...prod, ...dev];
2657
1521
  const command = uninstall.length ? [project.packageManager, ...uninstallArgs(project.packageManager, uninstall)].join(" ") : void 0;
2658
1522
  const changes = [];
2659
- if (after.code !== void 0 && after.code !== before) changes.push({
2660
- after: after.code,
1523
+ if (written.code !== void 0 && written.code !== before) changes.push({
1524
+ after: written.code,
2661
1525
  before,
2662
- diff: setupDiff(project.configFile, before, after.code),
1526
+ diff: setupDiff(project.configFile, before, written.code),
2663
1527
  kind: "patch",
2664
1528
  path: project.configFile
2665
1529
  });
@@ -2689,7 +1553,13 @@ async function planSetupRemove(project, args, env) {
2689
1553
  path,
2690
1554
  reason: "edited"
2691
1555
  });
2692
- const nextSteps = [];
1556
+ const configPatch = written.code !== void 0 && written.code !== before ? {
1557
+ after: written.code,
1558
+ before,
1559
+ path: project.configFile
1560
+ } : void 0;
1561
+ const restartRequired = !configPatch && deletes.length > 0 && emptied.size > 0;
1562
+ const nextSteps = restartRequired ? ["Restart the dev server to load the new feature configuration."] : [];
2693
1563
  if (command && !args.uninstall) nextSteps.push(`Uninstall the packages: ${command}`);
2694
1564
  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
1565
  const hosted = host === "node" ? [] : turnedOff.flatMap((id) => {
@@ -2718,12 +1588,9 @@ async function planSetupRemove(project, args, env) {
2718
1588
  ...command ? { command } : {}
2719
1589
  }
2720
1590
  },
1591
+ restartRequired,
2721
1592
  uninstall,
2722
- ...after.code !== void 0 && after.code !== before ? { configFile: {
2723
- after: after.code,
2724
- before,
2725
- path: project.configFile
2726
- } } : {}
1593
+ ...configPatch ? { configFile: configPatch } : {}
2727
1594
  };
2728
1595
  }
2729
1596
  /** Deletes `path` and then each folder that is empty after it, such as the `server/queues` that `add` created. */
@@ -2779,7 +1646,7 @@ async function runRemove(args, context) {
2779
1646
  try {
2780
1647
  parsed = readRemoveArgs(args);
2781
1648
  if (parsed.help) {
2782
- context.stdout.write(`Usage: ${usage}\n\n${removeCommand.description}\n`);
1649
+ context.stdout.write(`Usage: ${usage$1}\n\n${removeCommand.description}\n`);
2783
1650
  return setupExitCodes.done;
2784
1651
  }
2785
1652
  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 +1689,466 @@ const removeCommand = {
2822
1689
  description: "Turn off features: edit vitehub() options, delete unchanged starter Definitions, and uninstall unused packages. Reads the config without running it.",
2823
1690
  name: "remove",
2824
1691
  run: runRemove,
1692
+ usage: usage$1
1693
+ };
1694
+ //#endregion
1695
+ //#region src/setup/update.ts
1696
+ const usage = "vitehub update [--preview <commit>] [--dry-run] [--no-install] [--json]";
1697
+ const previewBase = "https://pkg.pr.new/vite-hub/vitehub";
1698
+ const defaultRegistry = "https://registry.npmjs.org/";
1699
+ const dependencyFields = [
1700
+ "dependencies",
1701
+ "devDependencies",
1702
+ "optionalDependencies"
1703
+ ];
1704
+ /** `vite-hub` and every `@vite-hub/*` package. */
1705
+ function isViteHubPackage(name) {
1706
+ return name === "vite-hub" || /^@vite-hub\/[a-z0-9][\w.-]*$/u.test(name);
1707
+ }
1708
+ /**
1709
+ * The package that an override or resolution key targets, such as `@vite-hub/env` for `foo>@vite-hub/env@0.1.0` or
1710
+ * `**\/@vite-hub/env`. Undefined when it is not a ViteHub package.
1711
+ */
1712
+ function overrideTarget(key) {
1713
+ let part = key.split(">").at(-1).replace(/^\*\*\//u, "");
1714
+ const scoped = part.lastIndexOf("/@");
1715
+ if (scoped >= 0) part = part.slice(scoped + 1);
1716
+ else if (!part.startsWith("@") && part.includes("/")) part = part.slice(part.lastIndexOf("/") + 1);
1717
+ const name = part.replace(/(?<=.)@.*$/u, "");
1718
+ return isViteHubPackage(name) ? name : void 0;
1719
+ }
1720
+ /** True for a specifier that names a release or a pkg.pr.new build, not `workspace:`, `catalog:`, a link, or git. */
1721
+ function isReplaceable(specifier) {
1722
+ return specifier.startsWith(`${previewBase}/`) || specifier === "latest" || specifier === "next" || semver.validRange(specifier) !== null;
1723
+ }
1724
+ /** The new specifier for `name`, from the resolved npm version or preview URL. */
1725
+ function nextSpecifier(name, current, place, target) {
1726
+ if ("preview" in target) return target.url(name);
1727
+ const version = target.versions.get(name);
1728
+ if (place === "override") return version;
1729
+ return `${/^[\^~]/u.exec(current)?.[0] ?? (semver.valid(current) ? "" : "^")}${version}`;
1730
+ }
1731
+ function isObject(value) {
1732
+ return !!value && typeof value === "object" && !Array.isArray(value);
1733
+ }
1734
+ /** Calls `visit` for every ViteHub specifier in the update fields of a package.json. */
1735
+ function visitManifest(manifest, visit) {
1736
+ const entries = (holder, place, nameOf) => {
1737
+ if (!isObject(holder)) return;
1738
+ for (const [key, value] of Object.entries(holder)) {
1739
+ const name = nameOf(key);
1740
+ if (typeof value === "string") {
1741
+ if (name && isReplaceable(value)) visit(holder, key, {
1742
+ name,
1743
+ place
1744
+ });
1745
+ } else if (place === "override" && isObject(value)) {
1746
+ if (name && typeof value["."] === "string" && isReplaceable(value["."])) visit(value, ".", {
1747
+ name,
1748
+ place
1749
+ });
1750
+ entries(value, place, overrideTarget);
1751
+ }
1752
+ }
1753
+ };
1754
+ const plainName = (key) => isViteHubPackage(key) ? key : void 0;
1755
+ for (const field of dependencyFields) entries(manifest[field], "dependency", plainName);
1756
+ entries(manifest.overrides, "override", overrideTarget);
1757
+ entries(manifest.resolutions, "override", overrideTarget);
1758
+ if (isObject(manifest.pnpm)) entries(manifest.pnpm.overrides, "override", overrideTarget);
1759
+ if (isObject(manifest.workspaces)) {
1760
+ entries(manifest.workspaces.catalog, "dependency", plainName);
1761
+ if (isObject(manifest.workspaces.catalogs)) for (const catalog of Object.values(manifest.workspaces.catalogs)) entries(catalog, "dependency", plainName);
1762
+ }
1763
+ }
1764
+ function unquote(text) {
1765
+ const quote = text[0] === "'" || text[0] === "\"" ? text[0] : "";
1766
+ return quote && text.endsWith(quote) && text.length > 1 ? {
1767
+ quote,
1768
+ value: text.slice(1, -1)
1769
+ } : {
1770
+ quote: "",
1771
+ value: text
1772
+ };
1773
+ }
1774
+ /** A `key: value` line inside a block, such as ` "@vite-hub/env": 0.1.0 # pinned`. Undefined for other lines. */
1775
+ function readYamlEntry(line) {
1776
+ const match = /^(\s+)("[^"]+"|'[^']+'|[^\s#'"][^:#]*?):\s+(.+?)(\s+#.*)?$/u.exec(line);
1777
+ if (!match) return;
1778
+ const [, indent, rawKey, rawValue, comment = ""] = match;
1779
+ const key = unquote(rawKey).value;
1780
+ const { quote, value } = unquote(rawValue);
1781
+ if (value.startsWith("{") || value.startsWith("[") || value.startsWith("&") || value.startsWith("*")) return;
1782
+ return {
1783
+ key,
1784
+ line: (next) => `${indent}${rawKey}: ${quote}${next}${quote}${comment}`,
1785
+ value
1786
+ };
1787
+ }
1788
+ /** The top-level key of a line without indentation, such as `overrides` for `overrides:`. */
1789
+ function topLevelKey(line) {
1790
+ if (!line || /^\s/u.test(line) || line.startsWith("#") || line.startsWith("-")) return;
1791
+ return /^("[^"]+"|'[^']+'|[^:#\s]+):/u.exec(line)?.[1]?.replace(/^["']|["']$/gu, "");
1792
+ }
1793
+ /** The line ranges of each top-level block of a YAML file. */
1794
+ function yamlBlocks(lines) {
1795
+ const blocks = /* @__PURE__ */ new Map();
1796
+ let current;
1797
+ for (const [index, line] of lines.entries()) {
1798
+ const key = topLevelKey(line);
1799
+ if (key === void 0) continue;
1800
+ if (current) blocks.get(current).end = index;
1801
+ current = key;
1802
+ blocks.set(key, {
1803
+ end: lines.length,
1804
+ start: index
1805
+ });
1806
+ }
1807
+ return blocks;
1808
+ }
1809
+ /** The items of a top-level YAML list, such as `packages`, with their line numbers. */
1810
+ function yamlList(lines, range) {
1811
+ if (!range) return [];
1812
+ const inline = /^[^:]+:\s*\[(.*)\]\s*(#.*)?$/u.exec(lines[range.start]);
1813
+ if (inline) return inline[1].split(",").map((item) => ({
1814
+ index: range.start,
1815
+ value: unquote(item.trim()).value
1816
+ })).filter((item) => item.value);
1817
+ return lines.slice(range.start + 1, range.end).flatMap((line, offset) => {
1818
+ const match = /^\s+-\s+(.+?)(\s+#.*)?$/u.exec(line);
1819
+ return match ? [{
1820
+ index: range.start + 1 + offset,
1821
+ value: unquote(match[1]).value
1822
+ }] : [];
1823
+ });
1824
+ }
1825
+ /** The name of a `minimumReleaseAgeExclude` entry that pins versions, such as `@vite-hub/env` for `@vite-hub/env@0.1.0`. */
1826
+ function pinnedName(entry) {
1827
+ const at = entry.indexOf("@", entry.startsWith("@") ? 1 : 0);
1828
+ return at > 0 ? entry.slice(0, at) : void 0;
1829
+ }
1830
+ /** The patterns that let a fresh ViteHub release through pnpm's `minimumReleaseAge`. */
1831
+ const releaseAgePatterns = ["vite-hub", "@vite-hub/*"];
1832
+ /** Calls `edit` for each ViteHub entry of the `overrides`, `catalog`, and `catalogs` blocks, and returns the removed lines. */
1833
+ function editYamlEntries(lines, edit) {
1834
+ const blocks = yamlBlocks(lines);
1835
+ const removed = /* @__PURE__ */ new Set();
1836
+ for (const [block, place] of [
1837
+ ["overrides", "override"],
1838
+ ["catalog", "dependency"],
1839
+ ["catalogs", "dependency"]
1840
+ ]) {
1841
+ const range = blocks.get(block);
1842
+ if (!range) continue;
1843
+ for (let index = range.start + 1; index < range.end; index++) {
1844
+ const entry = readYamlEntry(lines[index]);
1845
+ const name = entry && (place === "override" ? overrideTarget(entry.key) : isViteHubPackage(entry.key) ? entry.key : void 0);
1846
+ if (!entry || !name || !isReplaceable(entry.value)) continue;
1847
+ const next = edit(name, entry.value, place);
1848
+ if (next === null) removed.add(index);
1849
+ else if (next !== void 0) lines[index] = entry.line(next);
1850
+ }
1851
+ }
1852
+ return removed;
1853
+ }
1854
+ /** Rewrites the ViteHub entries of pnpm-workspace.yaml, and the settings that the target needs. */
1855
+ function updateWorkspaceYaml(text, edit, options) {
1856
+ const lines = text.split("\n");
1857
+ const removed = editYamlEntries(lines, edit);
1858
+ const blocks = yamlBlocks(lines);
1859
+ if (!options.preview) {
1860
+ const range = blocks.get("minimumReleaseAgeExclude");
1861
+ const items = yamlList(lines, range);
1862
+ const isInline = range && /:\s*\[/u.test(lines[range.start]);
1863
+ if (range && !isInline) {
1864
+ for (const item of items) {
1865
+ const name = pinnedName(item.value);
1866
+ if (name && isViteHubPackage(name)) removed.add(item.index);
1867
+ }
1868
+ const missing = releaseAgePatterns.filter((pattern) => !items.some((item) => item.value === pattern));
1869
+ const indent = /^(\s+)-/u.exec(lines[items[0]?.index ?? -1] ?? "")?.[1] ?? " ";
1870
+ if (missing.length) lines[range.start] = `${lines[range.start]}\n${missing.map((pattern) => `${indent}- '${pattern}'`).join("\n")}`;
1871
+ } 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}'`));
1872
+ } else {
1873
+ const range = blocks.get("blockExoticSubdeps");
1874
+ if (range) lines[range.start] = lines[range.start].replace(/^(blockExoticSubdeps:\s*)true\b/u, "$1false");
1875
+ 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");
1876
+ }
1877
+ const after = lines.filter((_, index) => !removed.has(index)).join("\n");
1878
+ return after.endsWith("\n") || !after ? after : `${after}\n`;
1879
+ }
1880
+ /** The workspace package folders that `patterns` select, relative to `root`. */
1881
+ async function workspaceFolders(root, patterns) {
1882
+ const find = async (selected) => {
1883
+ if (!selected.length) return /* @__PURE__ */ new Set();
1884
+ const folders = /* @__PURE__ */ new Set();
1885
+ const files = glob(selected.map((pattern) => `${pattern.replace(/\/+$/u, "")}/package.json`), {
1886
+ cwd: root,
1887
+ exclude: (path) => path.split(/[\\/]/u).includes("node_modules")
1888
+ });
1889
+ for await (const file of files) folders.add(dirname(file.replaceAll("\\", "/")));
1890
+ return folders;
1891
+ };
1892
+ const included = await find(patterns.filter((pattern) => !pattern.startsWith("!")));
1893
+ const excluded = await find(patterns.filter((pattern) => pattern.startsWith("!")).map((pattern) => pattern.slice(1)));
1894
+ return [...included].filter((folder) => !excluded.has(folder)).sort();
1895
+ }
1896
+ /** The workspace patterns of a root: `packages` of pnpm-workspace.yaml, else `workspaces` of package.json. */
1897
+ function workspacePatterns(yaml, manifest) {
1898
+ if (yaml !== void 0) {
1899
+ const lines = yaml.split("\n");
1900
+ return yamlList(lines, yamlBlocks(lines).get("packages")).map((item) => item.value);
1901
+ }
1902
+ const workspaces = manifest.workspaces;
1903
+ return (Array.isArray(workspaces) ? workspaces : isObject(workspaces) && Array.isArray(workspaces.packages) ? workspaces.packages : []).filter((item) => typeof item === "string");
1904
+ }
1905
+ /**
1906
+ * The root of the workspace that `start` belongs to: the nearest pnpm-workspace.yaml above, like pnpm finds it, or the
1907
+ * nearest package.json whose `workspaces` list `start`, like npm, Yarn, and Bun. `start` itself when it has a lockfile
1908
+ * or no workspace lists it.
1909
+ */
1910
+ async function workspaceRoot(start) {
1911
+ if (setupLockfiles.some(([file]) => existsSync(join(start, file)))) return start;
1912
+ for (let folder = dirname(start), last = start; folder !== last; last = folder, folder = dirname(folder)) {
1913
+ if (existsSync(join(folder, "pnpm-workspace.yaml"))) return folder;
1914
+ const manifest = join(folder, "package.json");
1915
+ if (!existsSync(manifest)) continue;
1916
+ const patterns = workspacePatterns(void 0, await readJson(manifest));
1917
+ if (patterns.length && (await workspaceFolders(folder, patterns)).includes(relative(folder, start))) return folder;
1918
+ }
1919
+ return start;
1920
+ }
1921
+ async function readJson(file) {
1922
+ const value = JSON.parse(await readFile(file, "utf8"));
1923
+ return isObject(value) ? value : {};
1924
+ }
1925
+ function stringifyLike(before, value) {
1926
+ const indent = /^[ \t]+(?=")/mu.exec(before)?.[0] ?? " ";
1927
+ return `${JSON.stringify(value, null, indent)}${before.endsWith("\n") ? "\n" : ""}`;
1928
+ }
1929
+ /** The command that installs the new specifiers. pnpm resolves ViteHub peers again only with `update`. */
1930
+ function updateInstallArgs(packageManager, workspace) {
1931
+ if (packageManager === "pnpm") return [
1932
+ "update",
1933
+ ...workspace ? ["--recursive"] : [],
1934
+ "vite-hub",
1935
+ "@vite-hub/*"
1936
+ ];
1937
+ return ["install"];
1938
+ }
1939
+ function invalid(message) {
1940
+ return cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${message} Usage: ${usage}` });
1941
+ }
1942
+ /** Reads the arguments. Throws `CLI_R0003` for an unknown flag or a value that is not a commit. */
1943
+ function readUpdateArgs(args) {
1944
+ const parsed = {
1945
+ dryRun: false,
1946
+ help: false,
1947
+ install: true,
1948
+ json: false
1949
+ };
1950
+ for (let index = 0; index < args.length; index++) {
1951
+ const arg = args[index];
1952
+ if (arg === "--json") parsed.json = true;
1953
+ else if (arg === "--dry-run") parsed.dryRun = true;
1954
+ else if (arg === "--no-install") parsed.install = false;
1955
+ else if (arg === "-h" || arg === "--help") parsed.help = true;
1956
+ else if (arg === "--preview" || arg.startsWith("--preview=")) {
1957
+ const value = arg.includes("=") ? arg.slice(arg.indexOf("=") + 1) : args[++index];
1958
+ 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 ?? "")}.`);
1959
+ parsed.preview = value;
1960
+ } else throw invalid(`Unknown argument ${JSON.stringify(arg)}.`);
1961
+ }
1962
+ return parsed;
1963
+ }
1964
+ /** Asks npm for the `latest` version of each package, or pkg.pr.new whether the build has it. Undefined when it has not. */
1965
+ async function resolvePackages(names, preview, context) {
1966
+ const request = context.fetch ?? fetch;
1967
+ const registry = (context.env.npm_config_registry || defaultRegistry).replace(/\/?$/u, "/");
1968
+ const url = (name) => `${previewBase}/${name}@${preview}`;
1969
+ const versions = /* @__PURE__ */ new Map();
1970
+ const missing = [];
1971
+ await Promise.all(names.map(async (name) => {
1972
+ const target = preview ? url(name) : `${registry}${name.replace("/", "%2f")}/latest`;
1973
+ let response;
1974
+ try {
1975
+ response = await request(target, preview ? { method: "HEAD" } : { headers: { accept: "application/json" } });
1976
+ } catch (error) {
1977
+ throw cliErrorDiagnostics.CLI_UPDATE_REQUEST_FAILED({
1978
+ status: error instanceof Error ? error.message : String(error),
1979
+ url: target
1980
+ });
1981
+ }
1982
+ if (response.status === 404) {
1983
+ missing.push(name);
1984
+ return;
1985
+ }
1986
+ if (!response.ok) throw cliErrorDiagnostics.CLI_UPDATE_REQUEST_FAILED({
1987
+ status: response.status,
1988
+ url: target
1989
+ });
1990
+ if (preview) return;
1991
+ const body = await response.json();
1992
+ const version = isObject(body) && typeof body.version === "string" ? body.version : void 0;
1993
+ if (!version) throw cliErrorDiagnostics.CLI_UPDATE_REQUEST_FAILED({
1994
+ status: "a response without a version",
1995
+ url: target
1996
+ });
1997
+ versions.set(name, version);
1998
+ }));
1999
+ return {
2000
+ missing: missing.sort(),
2001
+ resolved: {
2002
+ ...preview ? { preview } : {},
2003
+ url,
2004
+ versions
2005
+ }
2006
+ };
2007
+ }
2008
+ /** Plans the update: finds every ViteHub specifier, resolves the target, and computes the new files. Writes nothing. */
2009
+ async function planSetupUpdate(rootDir, args, context) {
2010
+ const root = await workspaceRoot(rootDir);
2011
+ const rootManifestFile = join(root, "package.json");
2012
+ if (!existsSync(rootManifestFile)) throw cliErrorDiagnostics.SETUP_NOT_A_PROJECT({ root });
2013
+ const rootManifest = await readJson(rootManifestFile);
2014
+ const { packageManager } = detectPackageManager(root, rootManifest, context.env);
2015
+ const yamlFile = join(root, "pnpm-workspace.yaml");
2016
+ const yamlBefore = existsSync(yamlFile) ? await readFile(yamlFile, "utf8") : void 0;
2017
+ const folders = [".", ...(await workspaceFolders(root, workspacePatterns(yamlBefore, rootManifest))).filter((folder) => folder !== ".")];
2018
+ const manifests = await Promise.all(folders.map(async (folder) => {
2019
+ const path = join(root, folder, "package.json");
2020
+ return {
2021
+ before: await readFile(path, "utf8"),
2022
+ path,
2023
+ value: await readJson(path)
2024
+ };
2025
+ }));
2026
+ const places = /* @__PURE__ */ new Map();
2027
+ const note = (name, place) => places.set(name, (places.get(name) ?? /* @__PURE__ */ new Set()).add(place));
2028
+ for (const manifest of manifests) visitManifest(manifest.value, (_, __, found) => note(found.name, found.place));
2029
+ if (yamlBefore !== void 0) editYamlEntries(yamlBefore.split("\n"), (name, _, place) => {
2030
+ note(name, place);
2031
+ });
2032
+ if (!places.size) throw cliErrorDiagnostics.CLI_UPDATE_NO_PACKAGES({ root });
2033
+ const { missing, resolved } = await resolvePackages([...places.keys()].sort(), args.preview, context);
2034
+ const blocking = missing.filter((name) => places.get(name).has("dependency"));
2035
+ if (blocking.length) throw setupFailure(cliErrorDiagnostics.CLI_UPDATE_PACKAGE_MISSING({
2036
+ packages: blocking.join(", "),
2037
+ target: args.preview ? `the pkg.pr.new build of ${args.preview}` : "npm"
2038
+ }), setupExitCodes.error);
2039
+ const packages = {};
2040
+ const next = (name, current, place) => {
2041
+ if (missing.includes(name)) return null;
2042
+ const specifier = nextSpecifier(name, current, place, resolved);
2043
+ if (place === "dependency" || !(name in packages)) packages[name] = specifier;
2044
+ return specifier;
2045
+ };
2046
+ const files = [];
2047
+ for (const manifest of manifests) {
2048
+ const direct = /* @__PURE__ */ new Map();
2049
+ for (const field of dependencyFields) {
2050
+ const dependencies = manifest.value[field];
2051
+ if (!isObject(dependencies)) continue;
2052
+ 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));
2053
+ }
2054
+ let edited = false;
2055
+ visitManifest(manifest.value, (holder, key, found) => {
2056
+ const current = String(holder[key]);
2057
+ const specifier = found.place === "override" && direct.has(found.name) ? direct.get(found.name) : next(found.name, current, found.place);
2058
+ if (specifier === current) return;
2059
+ edited = true;
2060
+ if (specifier === null) delete holder[key];
2061
+ else holder[key] = specifier;
2062
+ });
2063
+ if (edited) files.push({
2064
+ after: stringifyLike(manifest.before, manifest.value),
2065
+ before: manifest.before,
2066
+ path: manifest.path
2067
+ });
2068
+ }
2069
+ if (yamlBefore !== void 0 || packageManager === "pnpm") {
2070
+ const after = updateWorkspaceYaml(yamlBefore ?? "", next, { preview: !!args.preview });
2071
+ files.push({
2072
+ after,
2073
+ before: yamlBefore ?? "",
2074
+ path: yamlFile
2075
+ });
2076
+ }
2077
+ const changed = files.filter((file) => file.after !== file.before);
2078
+ const installArgs = updateInstallArgs(packageManager, folders.length > 1);
2079
+ return {
2080
+ files: changed,
2081
+ installArgs,
2082
+ packageManager,
2083
+ plan: {
2084
+ changes: changed.map((file) => {
2085
+ const path = relative(root, file.path);
2086
+ return {
2087
+ diff: setupDiff(path, file.before, file.after),
2088
+ kind: file.before ? "patch" : "create",
2089
+ path
2090
+ };
2091
+ }),
2092
+ install: { command: [packageManager, ...installArgs.map((arg) => arg.includes("*") ? `"${arg}"` : arg)].join(" ") },
2093
+ packages: Object.fromEntries(Object.entries(packages).sort(([left], [right]) => left.localeCompare(right))),
2094
+ root,
2095
+ status: changed.length ? "planned" : "unchanged",
2096
+ target: args.preview ? { preview: args.preview } : { version: resolved.versions.get("vite-hub") ?? [...resolved.versions.values()].sort(semver.rcompare)[0] }
2097
+ }
2098
+ };
2099
+ }
2100
+ function targetLabel(target) {
2101
+ return "preview" in target ? `the pkg.pr.new build of ${target.preview}` : target.version;
2102
+ }
2103
+ async function runUpdate(args, context) {
2104
+ let parsed;
2105
+ try {
2106
+ parsed = readUpdateArgs(args);
2107
+ if (parsed.help) {
2108
+ context.stdout.write(`Usage: ${usage}\n\n${updateCommand.description}\n`);
2109
+ return setupExitCodes.done;
2110
+ }
2111
+ const { files, installArgs, packageManager, plan } = await planSetupUpdate(context.rootDir, parsed, context);
2112
+ if (parsed.dryRun || plan.status === "unchanged") {
2113
+ if (parsed.json) writeSetupJson(context, plan);
2114
+ else if (plan.status === "unchanged") context.stdout.write(`ViteHub packages already use ${targetLabel(plan.target)}. Nothing to change.\n`);
2115
+ else {
2116
+ for (const change of plan.changes) context.stdout.write(change.diff.endsWith("\n") ? change.diff : `${change.diff}\n`);
2117
+ context.stdout.write(`${parsed.install ? "Install" : "Then install"}: ${plan.install.command}\n`);
2118
+ }
2119
+ return setupExitCodes.done;
2120
+ }
2121
+ for (const file of files) await writeFile(file.path, file.after);
2122
+ if (parsed.install) {
2123
+ const result = await context.spawn(packageManager, installArgs, {
2124
+ cwd: plan.root,
2125
+ env: context.env,
2126
+ stdout: "stderr"
2127
+ });
2128
+ if (result.exitCode !== 0) throw setupFailure(cliErrorDiagnostics.CLI_UPDATE_INSTALL_FAILED({
2129
+ command: plan.install.command,
2130
+ exitCode: result.exitCode ?? result.signal
2131
+ }), setupExitCodes.error);
2132
+ }
2133
+ const applied = {
2134
+ ...plan,
2135
+ status: "applied"
2136
+ };
2137
+ if (parsed.json) writeSetupJson(context, applied);
2138
+ else {
2139
+ const names = Object.keys(plan.packages);
2140
+ 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`);
2141
+ if (!parsed.install) context.stdout.write(`Install the packages: ${plan.install.command}\n`);
2142
+ }
2143
+ return setupExitCodes.done;
2144
+ } catch (error) {
2145
+ return writeSetupError(context, parsed?.json ?? args.includes("--json"), error);
2146
+ }
2147
+ }
2148
+ const updateCommand = {
2149
+ 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.",
2150
+ name: "update",
2151
+ run: runUpdate,
2825
2152
  usage
2826
2153
  };
2827
2154
  //#endregion
@@ -3090,6 +2417,7 @@ const setupCommands = [
3090
2417
  initCommandDefinition,
3091
2418
  addCommand,
3092
2419
  removeCommand,
2420
+ updateCommand,
3093
2421
  catalogCommand,
3094
2422
  statusCommand,
3095
2423
  linkCommand,
@@ -3101,4 +2429,4 @@ const setupCommands = [
3101
2429
  whoamiCommand
3102
2430
  ];
3103
2431
  //#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 };
2432
+ export { addCommand as _, updateCommand as a, readAddArgs as b, planSetupRemove as c, initCommandDefinition as d, initPackages as f, setupCatalog as g, readSetupStack 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, applySetupAdd as v, shellQuote as x, planSetupAdd as y };