@vite-hub/cli 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2169 @@
1
+ import { a as isProvisionRequestError, d as cliErrorDiagnostics, f as loadAllEnv, l as resolveHostCredentials, n as createCloudflareProvisionClient, p as withViteStageEnvironment, r as createNetlifyApiClient, w as isRecord } from "./provision-9QsGgeiq.js";
2
+ import { c as shellQuote, d as resolveDeploymentPlan } from "./status-gjvZVutV.js";
3
+ import { C as splitManifestCommand, S as redact, _ as isoTime, b as parseCommitMessage, d as commitMessage, f as createDeployRun, g as hostListFailed, h as hostCliFailed, m as hostCli, o as vercelEnv, p as findUrl, s as vercelProject, u as commandRejected, v as lastJsonObject, w as untilInterrupted, y as optionalString } from "./vercel-B5CJLsT0.js";
4
+ import { c as __exportAll, i as setupFailure, o as writeSetupError, r as setupExitCodes, s as writeSetupJson, t as isSetupFailure } from "./envelope-BJQ7xPyX.js";
5
+ import { n as dotenvLine$1 } from "./console-env-eXdVI6kw.js";
6
+ import { a as consoleClient, c as listConsoleApps, i as consoleAppUrl, n as checkConsoleApp, r as checkProblem, s as linkConsoleApp } from "./console-apps-BQX-Np9Q.js";
7
+ import { g as readSetupProject, u as selectConsole } from "./console-auth-cCodgT_T.js";
8
+ import { a as hostRequired, f as readSetupLinks, l as readLinkHostOption, p as selectSetupLink } from "./link-BRNWNqT9.js";
9
+ import { constants, existsSync, lstatSync, statSync } from "node:fs";
10
+ import process from "node:process";
11
+ import { basename, dirname, join, relative } from "pathe";
12
+ import { mkdir, mkdtemp, open, readFile, readdir, realpath, rm, stat, writeFile } from "node:fs/promises";
13
+ import { basename as basename$1 } from "node:path";
14
+ import { createInterface } from "node:readline/promises";
15
+ import { tmpdir } from "node:os";
16
+ import { parseArgs, parseEnv, stripVTControlCharacters } from "node:util";
17
+ import { setTimeout } from "node:timers/promises";
18
+ import { normalizeConsoleProjectUrl } from "@vite-hub/runtime/internal/console";
19
+ import { createPublicKey, diffieHellman, generateKeyPairSync, randomBytes } from "node:crypto";
20
+ import { hsalsa, xsalsa20poly1305 } from "@noble/ciphers/salsa.js";
21
+ import { blake2b } from "@noble/hashes/blake2.js";
22
+ // src/setup/build-output.ts
23
+ /** Runs the build script for `host`. VITEHUB_HOST_SOURCE=cli makes `host` win over a `host` literal in vitehub(). */
24
+ async function build(project, host, context) {
25
+ const command = `${project.packageManager} run build`;
26
+ const manifest = existsSync(join(project.root, "package.json")) ? JSON.parse(await readFile(join(project.root, "package.json"), "utf8")) : void 0;
27
+ if (!isRecord(manifest) || !isRecord(manifest.scripts) || typeof manifest.scripts.build !== "string") throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_BUILD_FAILED({
28
+ command,
29
+ framework: project.framework
30
+ }), setupExitCodes.error);
31
+ const env = {
32
+ ...context.env,
33
+ VITEHUB_HOST: host,
34
+ VITEHUB_HOST_SOURCE: "cli",
35
+ VITEHUB_LINK_ROOT: project.root
36
+ };
37
+ const result = await context.spawn(project.packageManager, ["run", "build"], {
38
+ cwd: project.root,
39
+ env,
40
+ stdout: "stderr"
41
+ });
42
+ if (result.exitCode !== 0) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_BUILD_FAILED({
43
+ command,
44
+ exitCode: result.exitCode ?? result.signal
45
+ }), setupExitCodes.error);
46
+ }
47
+ function stringList(value) {
48
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
49
+ }
50
+ function readEnvEntry(value) {
51
+ if (!isRecord(value)) return [];
52
+ const names = stringList(value.names);
53
+ const prefix = optionalString(value.prefix);
54
+ if (!names.length && !prefix) return [];
55
+ const owners = stringList(value.owners);
56
+ const path = optionalString(value.path);
57
+ return [{
58
+ ...path ? { path } : {},
59
+ names,
60
+ ...prefix ? { prefix } : {},
61
+ required: value.required === true,
62
+ secret: value.secret === true,
63
+ hasDefault: value.hasDefault === true,
64
+ ...owners.length ? { owners } : {}
65
+ }];
66
+ }
67
+ function readDeploy(value) {
68
+ if (!isRecord(value)) return { check: [] };
69
+ const check = stringList(value.check).filter((path) => path.startsWith("/") && !path.startsWith("//"));
70
+ const indexNow = isRecord(value.indexNow) ? value.indexNow : void 0;
71
+ const key = optionalString(indexNow?.key);
72
+ const url = optionalString(indexNow?.url);
73
+ return {
74
+ check,
75
+ ...key && /^[\w-]{8,128}$/u.test(key) && url && URL.canParse(url) ? { indexNow: {
76
+ key,
77
+ url: new URL(url).origin
78
+ } } : {}
79
+ };
80
+ }
81
+ /** Reads `<output>/deployment.json`, which the build writes, and checks that it is for `host`. */
82
+ async function readBuildOutput(root, host) {
83
+ const outputDir = join(root, resolveDeploymentPlan(host).output.directory);
84
+ const file = join(outputDir, "deployment.json");
85
+ let manifest;
86
+ try {
87
+ manifest = JSON.parse(await readFile(file, "utf8"));
88
+ } catch {
89
+ throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_OUTPUT_MISSING({ file }), setupExitCodes.error);
90
+ }
91
+ const built = isRecord(manifest) ? optionalString(manifest.host) : void 0;
92
+ if (built !== host) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_HOST_MISMATCH({
93
+ built: built ?? "an unknown host",
94
+ host
95
+ }), setupExitCodes.conflict);
96
+ const identityName = isRecord(manifest) && isRecord(manifest.identity) ? optionalString(manifest.identity.name) : void 0;
97
+ const env = isRecord(manifest) && Array.isArray(manifest.env) ? manifest.env.flatMap(readEnvEntry) : [];
98
+ const recordedEnvDir = isRecord(manifest) ? manifest.envDir : void 0;
99
+ const envDir = recordedEnvDir === false ? false : typeof recordedEnvDir === "string" ? join(outputDir, recordedEnvDir) : root;
100
+ return {
101
+ deploy: readDeploy(isRecord(manifest) ? manifest.deploy : void 0),
102
+ env,
103
+ envDir,
104
+ outputDir,
105
+ ...identityName ? { identityName } : {}
106
+ };
107
+ }
108
+ // src/setup/deploy/console.ts
109
+ const consoleKeyPrefix = "VITEHUB_CONSOLE_KEY_";
110
+ const checkDelays = [
111
+ 1e3,
112
+ 2e3,
113
+ 4e3
114
+ ];
115
+ /** True when the build reads `VITEHUB_CONSOLE_KEY_<NAME>`, which `console: true` adds. */
116
+ function readsConsoleKey(entries) {
117
+ return entries.some((entry) => entry.prefix === consoleKeyPrefix);
118
+ }
119
+ async function openDeployConsole(context) {
120
+ const { credential } = await selectConsole(context);
121
+ if (!credential) return;
122
+ try {
123
+ const client = consoleClient(context, credential);
124
+ const apps = await listConsoleApps(client);
125
+ return {
126
+ apps,
127
+ client,
128
+ keys: Object.fromEntries(apps.flatMap((app) => app.keyVariable && app.publicKey ? [[app.keyVariable, app.publicKey]] : []))
129
+ };
130
+ } catch (error) {
131
+ context.stderr.write(`Warning: deploy does not link the app in the Console, because the Console failed: ${errorMessage(error)}\n`);
132
+ return "unavailable";
133
+ }
134
+ }
135
+ async function linkDeployedApp(options) {
136
+ const { client } = options.console;
137
+ try {
138
+ const target = normalizeConsoleProjectUrl(options.url);
139
+ const installed = options.console.apps.filter((app) => app.keyVariable && options.onHost.has(app.keyVariable));
140
+ const known = installed.find((app) => app.url === target);
141
+ if (!known && installed.length) {
142
+ options.context.stderr.write(`Warning: the installed Console key links to ${installed.map((app) => app.url).join(", ")}, not ${options.url}. Link the current production URL and set its key with \`vitehub apps link ${options.url}\`.\n`);
143
+ return;
144
+ }
145
+ const { app, created } = known ? {
146
+ app: known,
147
+ created: false
148
+ } : await linkConsoleApp(client, {
149
+ label: options.label,
150
+ url: options.url
151
+ });
152
+ const keySet = app.keyVariable && app.publicKey && !options.onHost.has(app.keyVariable) ? app.keyVariable : void 0;
153
+ const liveUrl = keySet && app.publicKey ? await options.setKey(keySet, app.publicKey) : options.url;
154
+ if (!liveUrl || normalizeConsoleProjectUrl(liveUrl) !== app.url) {
155
+ options.context.stderr.write(`Warning: the Console record for ${app.url} does not match the final production URL (${liveUrl ?? "not reported"}). Check the production URL before linking the app.\n`);
156
+ return;
157
+ }
158
+ let check = await checkConsoleApp(client, app.id);
159
+ for (const delay of checkDelays) {
160
+ if (check.linked) break;
161
+ await setTimeout(delay);
162
+ check = await checkConsoleApp(client, app.id);
163
+ }
164
+ return {
165
+ app: app.id,
166
+ console: client.origin,
167
+ created,
168
+ ...keySet ? { keySet } : {},
169
+ linked: check.linked,
170
+ ...check.linked ? {} : { problem: checkProblem(check) },
171
+ url: consoleAppUrl(client.origin, app)
172
+ };
173
+ } catch (error) {
174
+ options.context.stderr.write(`Warning: the app is deployed, but deploy could not link it in the Console: ${errorMessage(error)} Run \`vitehub apps link ${options.url}\`.\n`);
175
+ }
176
+ }
177
+ function formatDeployConsole(output) {
178
+ return `${[
179
+ ...output.created ? [`Linked the app in ${output.console} as ${output.app}.`] : [],
180
+ ...output.keySet ? [`Set ${output.keySet} on the host.`] : [],
181
+ output.linked ? `Console: ${output.url}` : `The app does not accept the Console yet: ${output.problem ?? "no answer"}. Run \`vitehub apps check ${output.app}\`.`
182
+ ].join("\n")}\n`;
183
+ }
184
+ function errorMessage(error) {
185
+ return error instanceof Error ? error.message : String(error);
186
+ }
187
+ // ../internal/dist/cloudflare-BMyyNwZd.js
188
+ const placeholderId = /^(?:0+|0{8}-0{4}-[0-8]000-[089ab]000-0{12})$/;
189
+ /**
190
+ * Whether `value` is an all-zero id, such as `00000000000000000000000000000000` or
191
+ * `00000000-0000-4000-8000-000000000000`. Templates such as a Deploy to Cloudflare repository put one where Cloudflare
192
+ * writes the real id. It never names a resource.
193
+ */
194
+ function isPlaceholderCloudflareId(value) {
195
+ return typeof value === "string" && placeholderId.test(value);
196
+ }
197
+ const vitehubD1BindingsFile = ".vitehub/d1-bindings.json";
198
+ // src/setup/deploy/cloudflare.ts
199
+ const valueFlags = /* @__PURE__ */ new Set(["--config"]);
200
+ const plainFlags = /* @__PURE__ */ new Set(["--containers-rollout=gradual"]);
201
+ async function readWranglerCommand(outputDir) {
202
+ let manifest;
203
+ try {
204
+ manifest = JSON.parse(await readFile(join(outputDir, "nitro.json"), "utf8"));
205
+ } catch {
206
+ throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_OUTPUT_MISSING({ file: join(outputDir, "nitro.json") }), setupExitCodes.error);
207
+ }
208
+ const command = isRecord(manifest) && isRecord(manifest.commands) ? optionalString(manifest.commands.deploy) : void 0;
209
+ if (!command) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_OUTPUT_MISSING({ file: `commands.deploy in ${join(outputDir, "nitro.json")}` }), setupExitCodes.error);
210
+ const steps = command.split(" && ").map((step) => splitManifestCommand(step));
211
+ const words = steps.pop();
212
+ if (words[0] !== "npx" || words[1] !== "wrangler" || words[2] !== "deploy") throw commandRejected(command);
213
+ const args = [];
214
+ let config;
215
+ for (let index = 3; index < words.length; index++) {
216
+ const word = words[index];
217
+ if (plainFlags.has(word)) args.push(word);
218
+ else if (valueFlags.has(word) && words[index + 1] !== void 0 && !words[index + 1].startsWith("-")) {
219
+ const value = words[++index];
220
+ if (word === "--config") config = value;
221
+ args.push(word, value);
222
+ } else throw commandRejected(command);
223
+ }
224
+ if (!config) throw commandRejected(command);
225
+ const migrations = steps.map((step) => {
226
+ const [binding, ...flags] = step.slice(5);
227
+ if (!(step.slice(0, 5).join(" ") === "npx wrangler d1 migrations apply" && binding !== void 0 && /^[A-Z_a-z]\w*$/u.test(binding) && flags.length === 3 && flags[0] === "--remote" && flags[1] === "--config" && flags[2] === config)) throw commandRejected(command);
228
+ return binding;
229
+ });
230
+ return {
231
+ args,
232
+ config,
233
+ migrations
234
+ };
235
+ }
236
+ /**
237
+ * The plain vars of the Wrangler config that the build writes (`vars` in the `--config` file of `commands.deploy`). The
238
+ * deploy sets them with the version, so the Worker has them at runtime even though `wrangler secret list` omits them.
239
+ */
240
+ async function wranglerVarNames(outputDir) {
241
+ const { config } = await readWranglerCommand(outputDir);
242
+ const wrangler = await readWranglerConfig(outputDir, config);
243
+ return isRecord(wrangler.vars) ? Object.keys(wrangler.vars) : [];
244
+ }
245
+ /** The Wrangler config that the `--config` flag of `commands.deploy` names. */
246
+ async function readWranglerConfig(outputDir, config) {
247
+ const file = join(outputDir, config);
248
+ let value;
249
+ try {
250
+ value = JSON.parse(await readFile(file, "utf8"));
251
+ } catch {
252
+ throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_OUTPUT_MISSING({ file }), setupExitCodes.error);
253
+ }
254
+ return isRecord(value) ? value : {};
255
+ }
256
+ /**
257
+ * The D1 bindings of the Wrangler config whose `migrations_dir` holds `.sql` files, except the bindings that the deploy
258
+ * command migrates. Wrangler reads `migrations_dir` relative to the config file, and its default pattern is `*.sql`
259
+ * without dot files. A binding with `migrations_pattern` selects other files, and ViteHub's build never writes one.
260
+ */
261
+ async function unmigratedD1Bindings(outputDir, config, wrangler, migrated) {
262
+ const found = [];
263
+ for (const entry of Array.isArray(wrangler.d1_databases) ? wrangler.d1_databases : []) {
264
+ if (!isRecord(entry)) continue;
265
+ const binding = optionalString(entry.binding);
266
+ const dir = optionalString(entry.migrations_dir);
267
+ if (!binding || !dir || entry.migrations_pattern !== void 0 || migrated.includes(binding)) continue;
268
+ const files = (await readdir(join(outputDir, dirname(config), dir), { withFileTypes: true }).catch(() => [])).filter((item) => item.isFile() && item.name.endsWith(".sql") && !item.name.startsWith(".")).map((item) => item.name).toSorted();
269
+ if (files.length) found.push({
270
+ binding,
271
+ files,
272
+ table: optionalString(entry.migrations_table) ?? "d1_migrations"
273
+ });
274
+ }
275
+ return found;
276
+ }
277
+ async function readManagedD1Bindings(outputDir, config) {
278
+ const file = join(outputDir, dirname(config), vitehubD1BindingsFile);
279
+ const value = await readFile(file, "utf8").then((text) => JSON.parse(text)).catch((error) => {
280
+ if (error.code === "ENOENT") return [];
281
+ throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_OUTPUT_MISSING({ file }), setupExitCodes.error);
282
+ });
283
+ return Array.isArray(value) ? value : [];
284
+ }
285
+ function d1BindingsWithoutId(wrangler) {
286
+ return (Array.isArray(wrangler.d1_databases) ? wrangler.d1_databases : []).flatMap((entry) => {
287
+ if (!isRecord(entry) || !optionalString(entry.binding)) return [];
288
+ const id = optionalString(entry.database_id)?.trim();
289
+ return !id || isPlaceholderCloudflareId(id) ? [entry] : [];
290
+ });
291
+ }
292
+ /** The `results` rows of `wrangler d1 execute --json`, which prints one `{ results, success, meta }` per statement. */
293
+ function d1ResultNames(result) {
294
+ let value;
295
+ try {
296
+ value = JSON.parse(result.stdout.slice(Math.max(result.stdout.indexOf("["), 0)));
297
+ } catch {
298
+ return;
299
+ }
300
+ if (!Array.isArray(value)) return void 0;
301
+ return value.flatMap((item) => isRecord(item) && Array.isArray(item.results) ? item.results : []).flatMap((row) => isRecord(row) && typeof row.name === "string" ? [row.name] : []);
302
+ }
303
+ async function readWranglerOutput(file) {
304
+ return (await readFile(file, "utf8").catch(() => "")).split("\n").flatMap((line) => {
305
+ try {
306
+ const value = JSON.parse(line);
307
+ return isRecord(value) ? [value] : [];
308
+ } catch {
309
+ return [];
310
+ }
311
+ });
312
+ }
313
+ /**
314
+ * Wrangler 4.157 writes the `workers.dev` target as an `https://` URL, a custom domain as a bare host, such as
315
+ * `example.com (custom domain)`, and a route as its pattern. A route with one host and the path `/*` serves every path
316
+ * of that host. A wildcard host, a narrower path, triggers, and a custom domain with `production: disabled` have no
317
+ * URL to request.
318
+ */
319
+ function wranglerTargetUrl(targets) {
320
+ const texts = Array.isArray(targets) ? targets.filter((target) => typeof target === "string") : [];
321
+ return [...texts.map(directTargetUrl), ...texts.map(routeTargetUrl)].find((url) => url !== void 0 && URL.canParse(url));
322
+ }
323
+ const workersDevTarget = /^https:\/\/[^\s*/]+\.workers\.dev\/?$/u;
324
+ const customDomainTarget = /^([^\s*/:]+) \(custom domain[ )]/u;
325
+ const catchAllRouteTarget = /^(?:https:\/\/)?([^\s*/:]+)\/\*(?: \(zone (?:id|name): [^)]+\))?$/u;
326
+ function directTargetUrl(target) {
327
+ if (workersDevTarget.test(target)) return target;
328
+ const domain = customDomainTarget.exec(target)?.[1];
329
+ return domain && !target.includes("production: disabled") ? `https://${domain}` : void 0;
330
+ }
331
+ function routeTargetUrl(target) {
332
+ const host = catchAllRouteTarget.exec(target)?.[1];
333
+ return host ? `https://${host}` : void 0;
334
+ }
335
+ const durationUnits = {
336
+ second: 1e3,
337
+ minute: 6e4,
338
+ hour: 36e5,
339
+ day: 864e5
340
+ };
341
+ function claimExpiry(text) {
342
+ const match = /Claim within:\s*(\d+)\s*(second|minute|hour|day)s?/u.exec(text);
343
+ return match ? new Date(Date.now() + Number(match[1]) * durationUnits[match[2]]).toISOString() : void 0;
344
+ }
345
+ async function cloudflareAdapter(context) {
346
+ const command = await readWranglerCommand(context.outputDir);
347
+ const wrangler = hostCli("wrangler", "wrangler", context.root, context.env);
348
+ const linked = !context.temporary && context.link?.host === "cloudflare" ? context.link : void 0;
349
+ const accountId = linked?.account?.id ?? (context.credentials.ok ? context.credentials.accountId : void 0);
350
+ const target = linked ? ["--name", linked.project.name] : [];
351
+ const env = {
352
+ ...context.env,
353
+ ...accountId ? { CLOUDFLARE_ACCOUNT_ID: accountId } : {}
354
+ };
355
+ const run = (args, options = {}) => context.run(wrangler[0], [...wrangler.slice(1), ...args], {
356
+ cwd: context.outputDir,
357
+ env: options.env ?? env,
358
+ ...options
359
+ });
360
+ /** The migrations of `target` that its migrations table does not list. A database without the table has none applied. */
361
+ const pendingD1Migrations = async (target) => {
362
+ const query = async (sql) => {
363
+ const step = `wrangler d1 execute ${target.binding}`;
364
+ const result = await run([
365
+ "d1",
366
+ "execute",
367
+ target.binding,
368
+ "--remote",
369
+ "--config",
370
+ command.config,
371
+ "--json",
372
+ "--command",
373
+ sql
374
+ ], { env: {
375
+ ...env,
376
+ WRANGLER_LOG: "log"
377
+ } });
378
+ if (result.exitCode !== 0) throw hostCliFailed(step, result, context.secrets);
379
+ const names = d1ResultNames(result);
380
+ if (!names) throw hostCliFailed(`${step} printed no JSON`, result, context.secrets);
381
+ return names;
382
+ };
383
+ const tables = await query(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = '${target.table.replaceAll("'", "''")}'`);
384
+ const applied = new Set(tables.length ? await query(`SELECT name FROM "${target.table.replaceAll("\"", "\"\"")}"`) : []);
385
+ return target.files.filter((file) => !applied.has(file));
386
+ };
387
+ return { async deploy() {
388
+ if (!context.temporary) {
389
+ const wranglerConfig = await readWranglerConfig(context.outputDir, command.config);
390
+ const environment = env.CLOUDFLARE_ENV;
391
+ const named = environment && isRecord(wranglerConfig.env) && Object.hasOwn(wranglerConfig.env, environment) ? wranglerConfig.env[environment] : void 0;
392
+ const config = isRecord(named) ? named : wranglerConfig;
393
+ const missingIds = d1BindingsWithoutId(config);
394
+ if (missingIds.length) {
395
+ const managed = isRecord(named) ? [] : await readManagedD1Bindings(context.outputDir, command.config);
396
+ const unprovisioned = missingIds.filter((entry) => managed.some((item) => isRecord(item) && item.binding === entry.binding && item.database_name === entry.database_name));
397
+ if (unprovisioned.length) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_D1_DATABASE_ID_MISSING({ bindings: unprovisioned.map((entry) => entry.binding).join(", ") }), setupExitCodes.error);
398
+ if (context.preview) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_D1_DATABASE_ID_MISSING({
399
+ bindings: missingIds.map((entry) => entry.binding).join(", "),
400
+ wranglerOwned: true
401
+ }), setupExitCodes.error);
402
+ }
403
+ for (const target of context.preview ? [] : await unmigratedD1Bindings(context.outputDir, command.config, config, command.migrations)) {
404
+ const pending = await pendingD1Migrations(target);
405
+ if (!pending.length) continue;
406
+ throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_D1_MIGRATIONS_PENDING({
407
+ apply: `npx wrangler d1 migrations apply ${shellQuote(target.binding)} --remote --config ${shellQuote(command.config)}${environment ? ` --env ${shellQuote(environment)}` : ""}`,
408
+ binding: target.binding,
409
+ migrations: pending.join(", ")
410
+ }), setupExitCodes.error);
411
+ }
412
+ for (const binding of context.preview ? [] : command.migrations) {
413
+ const result = await run([
414
+ "d1",
415
+ "migrations",
416
+ "apply",
417
+ binding,
418
+ "--remote",
419
+ "--config",
420
+ command.config
421
+ ], { show: true });
422
+ if (result.exitCode !== 0) throw hostCliFailed(`wrangler d1 migrations apply ${binding}`, result, context.secrets);
423
+ }
424
+ }
425
+ return await untilInterrupted(async (signal) => {
426
+ const folder = await mkdtemp(join(tmpdir(), "vitehub-deploy-"));
427
+ const outputFile = join(folder, "wrangler-output.jsonl");
428
+ try {
429
+ const args = context.preview ? [
430
+ "versions",
431
+ "upload",
432
+ ...command.args.filter((arg) => !plainFlags.has(arg))
433
+ ] : ["deploy", ...command.args];
434
+ args.push(...target, "--keep-vars");
435
+ if (context.temporary) args.push("--temporary");
436
+ if (context.commit) args.push("--tag", context.commit.sha.slice(0, 12), "--message", commitMessage(context.commit));
437
+ if (context.upload && Object.keys(context.upload).length) {
438
+ const secretsFile = join(folder, "secrets.json");
439
+ await writeFile(secretsFile, JSON.stringify(context.upload), {
440
+ flag: "wx",
441
+ mode: 384
442
+ });
443
+ args.push("--secrets-file", secretsFile);
444
+ }
445
+ const result = await run(args, {
446
+ env: {
447
+ ...env,
448
+ WRANGLER_OUTPUT_FILE_PATH: outputFile
449
+ },
450
+ show: true,
451
+ signal
452
+ });
453
+ const step = context.preview ? "wrangler versions upload" : "wrangler deploy";
454
+ if (result.exitCode !== 0) throw hostCliFailed(step, result, context.secrets);
455
+ const entry = (await readWranglerOutput(outputFile)).findLast((item) => item.type === (context.preview ? "version-upload" : "deploy"));
456
+ const text = `${result.stdout}\n${result.stderr}`;
457
+ const fromTargets = entry && !context.preview;
458
+ const url = fromTargets ? wranglerTargetUrl(entry.targets) : optionalString(entry?.preview_url) ?? findUrl(text, /\.workers\.dev$/u);
459
+ if (!url && !fromTargets) throw hostCliFailed(`${step} printed no URL`, result, context.secrets);
460
+ const version = optionalString(entry?.version_id);
461
+ const claimUrl = /Claim URL:\s*(https:\/\/\S+)/u.exec(text)?.[1];
462
+ const expiresAt = claimExpiry(text);
463
+ const name = optionalString(entry?.worker_name);
464
+ return {
465
+ ...url ? { url } : {},
466
+ ...version ? { version } : {},
467
+ ...claimUrl ? { claim: {
468
+ url: claimUrl,
469
+ ...expiresAt ? { expiresAt } : {}
470
+ } } : {},
471
+ ...name ? { project: {
472
+ name,
473
+ ...accountId ? { accountId } : {}
474
+ } } : {}
475
+ };
476
+ } finally {
477
+ await rm(folder, {
478
+ force: true,
479
+ recursive: true
480
+ });
481
+ }
482
+ });
483
+ } };
484
+ }
485
+ /**
486
+ * The secrets of the linked Worker. Wrangler 4.158 (`wrangler secret put --help`, `wrangler secret list --help`, in
487
+ * test/fixtures/host-cli-help/). `secret put` reads the value from stdin when stdin is not a terminal, and creates a
488
+ * draft Worker when the Worker does not exist. A Worker has one set of secrets for every version, so there is no
489
+ * preview target. Every value becomes a secret: a plain var lives in the Wrangler config that the build writes.
490
+ */
491
+ function cloudflareEnv(context, purpose = "env") {
492
+ const wrangler = hostCli("wrangler", "wrangler", context.root, context.env);
493
+ const env = {
494
+ ...context.env,
495
+ ...context.link.account ? { CLOUDFLARE_ACCOUNT_ID: context.link.account.id } : {}
496
+ };
497
+ const worker = ["--name", context.link.project.name];
498
+ const run = (args, stdin) => context.run(wrangler[0], [...wrangler.slice(1), ...args], {
499
+ cwd: context.root,
500
+ env,
501
+ ...stdin === void 0 ? {} : { stdin }
502
+ });
503
+ return {
504
+ async listSecretNames() {
505
+ const result = await run([
506
+ "secret",
507
+ "list",
508
+ "--format",
509
+ "json",
510
+ ...worker
511
+ ]);
512
+ if (result.exitCode !== 0) {
513
+ if (purpose === "deploy" && stripVTControlCharacters(result.stderr).includes(`Worker "${context.link.project.name}" not found.`)) return [];
514
+ throw hostListFailed("wrangler secret list", result, context.secrets);
515
+ }
516
+ const start = result.stdout.indexOf("[");
517
+ let value;
518
+ try {
519
+ value = JSON.parse(result.stdout.slice(start));
520
+ } catch {
521
+ throw hostListFailed("wrangler secret list printed no JSON", result, context.secrets);
522
+ }
523
+ return Array.isArray(value) ? value.flatMap((item) => isRecord(item) && typeof item.name === "string" ? [item.name] : []) : [];
524
+ },
525
+ async setSecret(name, value) {
526
+ const result = await run([
527
+ "secret",
528
+ "put",
529
+ name,
530
+ ...worker
531
+ ], value);
532
+ if (result.exitCode !== 0) throw hostCliFailed(`wrangler secret put ${name}`, result, context.secrets);
533
+ }
534
+ };
535
+ }
536
+ function cloudflareSource(value) {
537
+ if (value === "wrangler" || value === "cf_cli") return "cli";
538
+ if (value === "workersci") return "git";
539
+ if (value === "dash" || value === "dash_template" || value === "quick_editor" || value === "playground") return "dashboard";
540
+ if (value === "api" || value === "terraform" || value === "integration") return "api";
541
+ return "unknown";
542
+ }
543
+ function parseVersion(value) {
544
+ if (!isRecord(value)) return;
545
+ const id = optionalString(value.id);
546
+ if (!id) return;
547
+ const metadata = isRecord(value.metadata) ? value.metadata : {};
548
+ const commit = isRecord(value.annotations) ? parseCommitMessage(value.annotations["workers/message"]) : void 0;
549
+ return {
550
+ createdAt: isoTime(metadata.created_on),
551
+ hasPreview: metadata.hasPreview === true,
552
+ id,
553
+ source: cloudflareSource(metadata.source),
554
+ ...commit ? { commit } : {}
555
+ };
556
+ }
557
+ function parseVersions(value) {
558
+ return (isRecord(value) && Array.isArray(value.items) ? value.items : []).flatMap((item) => parseVersion(item) ?? []);
559
+ }
560
+ function parseDeployments(value) {
561
+ return (isRecord(value) && Array.isArray(value.deployments) ? value.deployments : []).flatMap((item) => {
562
+ const id = isRecord(item) ? optionalString(item.id) : void 0;
563
+ if (!id || !isRecord(item)) return [];
564
+ const versions = (Array.isArray(item.versions) ? item.versions : []).flatMap((version) => {
565
+ const versionId = isRecord(version) ? optionalString(version.version_id) : void 0;
566
+ return versionId && isRecord(version) ? [{
567
+ id: versionId,
568
+ percentage: typeof version.percentage === "number" ? version.percentage : 0
569
+ }] : [];
570
+ });
571
+ const main = versions.toSorted((a, b) => b.percentage - a.percentage)[0];
572
+ return [{
573
+ createdAt: isoTime(item.created_on),
574
+ id,
575
+ source: cloudflareSource(item.source),
576
+ versionIds: versions.map((version) => version.id),
577
+ ...main ? { versionId: main.id } : {}
578
+ }];
579
+ });
580
+ }
581
+ async function optional(request) {
582
+ try {
583
+ return await request;
584
+ } catch {
585
+ return;
586
+ }
587
+ }
588
+ /**
589
+ * Workers API, newest first:
590
+ * - `GET /accounts/{account_id}/workers/scripts/{script_name}/deployments`: the first one gets the traffic, as in
591
+ * `wrangler deployments list`. https://developers.cloudflare.com/api/resources/workers/subresources/scripts/subresources/deployments/methods/list/
592
+ * - `GET .../versions?per_page=`: a bounded page of versions, with the `workers/message` annotation. A version in no
593
+ * deployment is a preview (`wrangler versions upload`). https://developers.cloudflare.com/api/resources/workers/subresources/scripts/subresources/versions/methods/list/
594
+ * - `GET /accounts/{account_id}/workers/subdomain`: the account's `workers.dev` suffix. https://developers.cloudflare.com/api/resources/workers/subresources/subdomains/methods/get/
595
+ * - `GET .../scripts/{script_name}/subdomain`: whether production and preview `workers.dev` URLs are enabled. https://developers.cloudflare.com/api/resources/workers/subresources/scripts/subresources/subdomain/methods/get/
596
+ */
597
+ const listCloudflareDeployments = async (context, { limit, includeLive }) => {
598
+ const accountId = context.link.account?.id ?? context.credentials.accountId;
599
+ if (!accountId) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOYMENTS_ACCOUNT_REQUIRED({ host: "cloudflare" }), setupExitCodes.inputNeeded, {
600
+ missing: [{ field: "CLOUDFLARE_ACCOUNT_ID" }],
601
+ rerun: "vitehub link --host cloudflare --account <id>"
602
+ });
603
+ const client = createCloudflareProvisionClient({
604
+ accountId,
605
+ token: context.credentials.token
606
+ }, context.fetch);
607
+ const script = `/workers/scripts/${encodeURIComponent(context.link.project.name)}`;
608
+ const [deployments, versions, subdomain, settings] = await Promise.all([
609
+ client(`${script}/deployments`, {
610
+ parse: parseDeployments,
611
+ query: { per_page: String(limit) }
612
+ }),
613
+ client(`${script}/versions`, {
614
+ parse: parseVersions,
615
+ query: { per_page: String(limit) }
616
+ }),
617
+ optional(client("/workers/subdomain", { parse: (value) => isRecord(value) ? optionalString(value.subdomain) : void 0 })),
618
+ optional(client(`${script}/subdomain`, { parse: (value) => isRecord(value) ? {
619
+ enabled: value.enabled === true,
620
+ previewsEnabled: value.previews_enabled === true
621
+ } : void 0 }))
622
+ ]);
623
+ const byId = new Map((versions.result ?? []).map((version) => [version.id, version]));
624
+ const listed = (deployments.result ?? []).slice(0, limit);
625
+ const missing = [...new Set(listed.flatMap((item) => item.versionId && !byId.has(item.versionId) ? [item.versionId] : []))];
626
+ for (const version of await Promise.all(missing.map((id) => optional(client(`${script}/versions/${encodeURIComponent(id)}`, { parse: parseVersion }))))) if (version?.result) byId.set(version.result.id, version.result);
627
+ const name = context.link.project.name;
628
+ const host = subdomain?.result ? `${subdomain.result}.workers.dev` : void 0;
629
+ const productionUrl = host && settings?.result?.enabled ? `https://${name}.${host}` : void 0;
630
+ const previewUrl = (version) => host && settings?.result?.previewsEnabled && version?.hasPreview ? `https://${version.id.slice(0, 8)}-${name}.${host}` : void 0;
631
+ const deployed = new Set(listed.flatMap((item) => item.versionIds));
632
+ const result = listed.map((item, index) => {
633
+ const version = item.versionId ? byId.get(item.versionId) : void 0;
634
+ const url = index === 0 ? productionUrl : previewUrl(version);
635
+ return {
636
+ createdAt: item.createdAt,
637
+ id: item.id,
638
+ live: index === 0,
639
+ source: item.source,
640
+ state: "ready",
641
+ target: "production",
642
+ ...url ? { url } : {},
643
+ ...item.versionId ? { version: item.versionId } : {},
644
+ ...version?.commit ? { commit: {
645
+ ...version.commit,
646
+ from: "vitehub"
647
+ } } : {}
648
+ };
649
+ });
650
+ for (const version of versions.result ?? []) {
651
+ if (deployed.has(version.id)) continue;
652
+ const url = previewUrl(version);
653
+ result.push({
654
+ createdAt: version.createdAt,
655
+ id: version.id,
656
+ live: false,
657
+ source: version.source,
658
+ state: "ready",
659
+ target: "preview",
660
+ version: version.id,
661
+ ...url ? { url } : {},
662
+ ...version.commit ? { commit: {
663
+ ...version.commit,
664
+ from: "vitehub"
665
+ } } : {}
666
+ });
667
+ }
668
+ const recent = result.toSorted((a, b) => b.createdAt.localeCompare(a.createdAt)).slice(0, limit);
669
+ const live = result.find((item) => item.live);
670
+ if (includeLive && live && !recent.includes(live)) recent.push(live);
671
+ return recent;
672
+ };
673
+ // src/setup/deploy/deno.ts
674
+ const runnerFirstLine = "import { spawn } from \"node:child_process\"";
675
+ async function denoAdapter(context, organization) {
676
+ const runner = join(context.outputDir, "deploy.mjs");
677
+ const source = await readFile(runner, "utf8").catch(() => void 0);
678
+ if (source === void 0) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_OUTPUT_MISSING({ file: runner }), setupExitCodes.error);
679
+ if (!source.startsWith(runnerFirstLine)) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_COMMAND_REJECTED({ command: runner }), setupExitCodes.error);
680
+ const env = {
681
+ ...context.env,
682
+ DENO_DEPLOY_APP: context.projectName,
683
+ DENO_DEPLOY_ORG: organization
684
+ };
685
+ return { async deploy() {
686
+ const result = await context.run(process.execPath, [runner], {
687
+ cwd: context.root,
688
+ env,
689
+ show: true
690
+ });
691
+ if (result.exitCode !== 0) throw hostCliFailed("node .output/deploy.mjs", result, context.secrets);
692
+ const url = findUrl(`${result.stdout}\n${result.stderr}`, /\.deno\.(?:net|dev)$/u);
693
+ if (!url) throw hostCliFailed("deno deploy printed no URL", result, context.secrets);
694
+ return {
695
+ url,
696
+ project: {
697
+ name: context.projectName,
698
+ accountId: organization
699
+ }
700
+ };
701
+ } };
702
+ }
703
+ /** The Deno Deploy organization: the linked account, else `DENO_DEPLOY_ORG`. */
704
+ function denoOrganization(link, env) {
705
+ const organization = (link?.host === "deno" ? link.account?.id : void 0) ?? env.DENO_DEPLOY_ORG?.trim();
706
+ if (!organization) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_ORG_REQUIRED(), setupExitCodes.inputNeeded, { missing: [{ field: "DENO_DEPLOY_ORG" }] });
707
+ return organization;
708
+ }
709
+ function dotenvLine(name, value) {
710
+ if (/['\r\n]/u.test(value)) throw setupFailure(cliErrorDiagnostics.SETUP_ENV_VALUE_UNSUPPORTED({
711
+ host: "deno",
712
+ name,
713
+ reason: "It has a single quote or a line break, and `deno deploy env load` reads a dotenv file."
714
+ }), setupExitCodes.conflict);
715
+ return `${name}='${value}'\n`;
716
+ }
717
+ /**
718
+ * The environment variables of the linked app. Deno Deploy CLI 0.0.9909 (`deno deploy env list --help`, `deno deploy env
719
+ * load --help`, in test/fixtures/host-cli-help/). `env add` takes the value as an argument, so the value goes to
720
+ * `env load /dev/stdin` as a dotenv line. `env load` sets a variable for every context, and Deno decides from the name
721
+ * whether it is secret; names it cannot store as secrets are refused. `--non-secrets` keeps a plain value readable.
722
+ * ViteHub deploys Deno to production only.
723
+ */
724
+ function denoEnv(context) {
725
+ const deno = hostCli("deno", "deno", context.root, context.env);
726
+ const app = [
727
+ "--org",
728
+ denoOrganization(context.link, context.env),
729
+ "--app",
730
+ context.link.project.name
731
+ ];
732
+ const run = (args, stdin) => context.run(deno[0], [
733
+ ...deno.slice(1),
734
+ "deploy",
735
+ "env",
736
+ ...args,
737
+ "--json",
738
+ "--non-interactive",
739
+ ...app
740
+ ], {
741
+ cwd: context.root,
742
+ env: context.env,
743
+ ...stdin === void 0 ? {} : {
744
+ stdin,
745
+ stdinAsFile: true
746
+ }
747
+ });
748
+ return {
749
+ async listSecretNames() {
750
+ const result = await run(["list"]);
751
+ if (result.exitCode !== 0) throw hostListFailed("deno deploy env list", result, context.secrets);
752
+ const start = result.stdout.indexOf("[");
753
+ let value;
754
+ try {
755
+ value = JSON.parse(result.stdout.slice(start));
756
+ } catch {
757
+ throw hostListFailed("deno deploy env list printed no JSON", result, context.secrets);
758
+ }
759
+ return Array.isArray(value) ? value.flatMap((item) => isRecord(item) && typeof item.key === "string" ? [item.key] : []) : [];
760
+ },
761
+ async setSecret(name, value, { secret }) {
762
+ if (process.platform === "win32") throw setupFailure(cliErrorDiagnostics.SETUP_ENV_VALUE_UNSUPPORTED({
763
+ host: "deno",
764
+ name,
765
+ reason: "Windows has no /dev/stdin for `deno deploy env load`."
766
+ }), setupExitCodes.conflict);
767
+ if (secret && (!/_(?:KEY|SECRET|TOKEN|PASSWORD|PRIVATE|CREDENTIALS|AUTH)$/u.test(name) || /^(?:PUBLIC|VITE|NEXT_PUBLIC|NUXT_PUBLIC|REACT_APP|EXPO_PUBLIC|GATSBY)_/u.test(name))) throw setupFailure(cliErrorDiagnostics.SETUP_ENV_VALUE_UNSUPPORTED({
768
+ host: "deno",
769
+ name,
770
+ reason: "The Deno CLI cannot enforce secret storage for this name. Set it as a secret in Deno Deploy before continuing."
771
+ }), setupExitCodes.conflict);
772
+ const result = await run([
773
+ "load",
774
+ "/dev/stdin",
775
+ "--replace",
776
+ ...secret ? [] : ["--non-secrets", name]
777
+ ], dotenvLine(name, value));
778
+ if (result.exitCode !== 0) throw hostCliFailed(`deno deploy env load (${name})`, result, context.secrets);
779
+ }
780
+ };
781
+ }
782
+ function denoState(value) {
783
+ if (value === "succeeded") return "ready";
784
+ if (value === "failed") return "error";
785
+ if (value === "skipped") return "canceled";
786
+ return value === "queued" || value === "building" ? "building" : "unknown";
787
+ }
788
+ /**
789
+ * Deno Deploy CLI 0.0.9909, recorded in test/fixtures/host-cli-help/. Both print one JSON object with `--json`:
790
+ * - `deno deploy deployments list --limit <n>`: `{ items: [{ id, status, prod, createdAt }] }`, newest first.
791
+ * - `deno deploy apps get`: `productionRevisionId` and `productionUrl`, the revision that serves production.
792
+ * Deno Deploy keeps no deploy message, so a Deno deployment has no commit.
793
+ * https://docs.deno.com/runtime/reference/cli/deploy/#agent--ci-usage
794
+ */
795
+ const listDenoDeployments = async (context, { limit, includeLive }) => {
796
+ const organization = denoOrganization(context.link, context.env);
797
+ const deno = hostCli("deno", "deno", context.root, context.env);
798
+ const app = [
799
+ "--json",
800
+ "--non-interactive",
801
+ "--org",
802
+ organization,
803
+ "--app",
804
+ context.link.project.name
805
+ ];
806
+ const run = async (step, args) => {
807
+ const result = await context.run(deno[0], [
808
+ ...deno.slice(1),
809
+ "deploy",
810
+ ...args,
811
+ ...app
812
+ ], {
813
+ cwd: context.root,
814
+ env: context.env,
815
+ ...context.timeoutMs ? { timeoutMs: context.timeoutMs } : {}
816
+ });
817
+ if (result.exitCode !== 0) throw hostCliFailed(step, result, []);
818
+ return lastJsonObject(result.stdout);
819
+ };
820
+ const [list, details] = await Promise.all([run("deno deploy deployments list", [
821
+ "deployments",
822
+ "list",
823
+ "--limit",
824
+ String(limit)
825
+ ]), run("deno deploy apps get", ["apps", "get"])]);
826
+ const production = optionalString(details?.productionRevisionId);
827
+ const productionUrl = optionalString(details?.productionUrl);
828
+ const recent = (Array.isArray(list?.items) ? list.items : []).flatMap((item) => {
829
+ const id = isRecord(item) ? optionalString(item.id) : void 0;
830
+ if (!id || !isRecord(item)) return [];
831
+ const live = id === production;
832
+ return [{
833
+ createdAt: isoTime(item.createdAt),
834
+ id,
835
+ live,
836
+ source: "unknown",
837
+ state: denoState(item.status),
838
+ target: item.prod === true ? "production" : "preview",
839
+ ...live && productionUrl ? { url: productionUrl } : {}
840
+ }];
841
+ }).slice(0, limit);
842
+ if (includeLive && production && !recent.some((item) => item.live)) recent.push({
843
+ createdAt: "",
844
+ id: production,
845
+ live: true,
846
+ source: "unknown",
847
+ state: "ready",
848
+ target: "production",
849
+ ...productionUrl ? { url: productionUrl } : {}
850
+ });
851
+ return recent;
852
+ };
853
+ // src/setup/deploy/netlify.ts
854
+ const publishDir = "dist";
855
+ function netlifyAdapter(context) {
856
+ const netlify = hostCli("netlify", "netlify-cli", context.root, context.env);
857
+ const linked = context.link?.host === "netlify" && context.link.project.id ? context.link : void 0;
858
+ let site = linked?.project.id ? {
859
+ id: linked.project.id,
860
+ ...linked.account ? { accountId: linked.account.id } : {}
861
+ } : void 0;
862
+ return { async deploy() {
863
+ const args = [
864
+ "deploy",
865
+ "--no-build",
866
+ "--dir",
867
+ publishDir,
868
+ "--json",
869
+ ...context.preview ? ["--context", "deploy-preview"] : ["--prod"]
870
+ ];
871
+ args.push(...site ? ["--site", site.id] : ["--site-name", context.projectName]);
872
+ if (context.commit) args.push("--message", commitMessage(context.commit));
873
+ const result = await context.run(netlify[0], [...netlify.slice(1), ...args], {
874
+ cwd: context.root,
875
+ env: context.env,
876
+ show: true
877
+ });
878
+ if (result.exitCode !== 0) throw hostCliFailed("netlify deploy", result, context.secrets);
879
+ const json = lastJsonObject(result.stdout);
880
+ const url = optionalString(json?.url) ?? optionalString(json?.deploy_url);
881
+ if (!url) throw hostCliFailed("netlify deploy printed no URL", result, context.secrets);
882
+ const siteId = optionalString(json?.site_id);
883
+ if (siteId && siteId !== site?.id) site = { id: siteId };
884
+ const deploymentId = optionalString(json?.deploy_id);
885
+ const name = optionalString(json?.site_name) ?? context.projectName;
886
+ return {
887
+ url,
888
+ ...deploymentId ? { deploymentId } : {},
889
+ project: {
890
+ ...site ? { id: site.id } : {},
891
+ name,
892
+ ...site?.accountId ? { accountId: site.accountId } : {}
893
+ }
894
+ };
895
+ } };
896
+ }
897
+ const netlifyContexts = {
898
+ preview: "deploy-preview",
899
+ production: "production"
900
+ };
901
+ const allContexts = [
902
+ "production",
903
+ "deploy-preview",
904
+ "branch-deploy",
905
+ "dev",
906
+ "dev-server"
907
+ ];
908
+ function netlifyValues(value) {
909
+ if (!Array.isArray(value)) return;
910
+ const values = [];
911
+ for (const item of value) {
912
+ if (!isRecord(item) || typeof item.context !== "string" || typeof item.value !== "string") return;
913
+ values.push({
914
+ context: item.context,
915
+ value: item.value,
916
+ ...typeof item.context_parameter === "string" ? { context_parameter: item.context_parameter } : {}
917
+ });
918
+ }
919
+ return values;
920
+ }
921
+ function netlifyUpdate(existing, name, context, value, secret) {
922
+ const refuse = (reason) => setupFailure(cliErrorDiagnostics.SETUP_ENV_VALUE_UNSUPPORTED({
923
+ host: "netlify",
924
+ name,
925
+ reason
926
+ }), setupExitCodes.conflict);
927
+ if (!isRecord(existing) || !Array.isArray(existing.scopes)) throw refuse("The Netlify API returned the variable without its scopes.");
928
+ const scopes = existing.scopes.filter((scope) => typeof scope === "string");
929
+ const wasSecret = existing.is_secret === true;
930
+ if (scopes.includes("functions") && (wasSecret || !secret)) return;
931
+ const values = netlifyValues(existing.values);
932
+ if (!values) throw refuse("The Netlify API returned the variable without its values.");
933
+ const others = values.flatMap((item) => item.context === "all" ? allContexts.map((each) => ({
934
+ ...item,
935
+ context: each
936
+ })) : [item]).filter((item) => item.context !== context);
937
+ if (wasSecret && others.some((item) => item.context !== "dev")) throw refuse(`It is a secret without Functions scope, and Netlify does not return the secret values of its other contexts, so ViteHub cannot keep them. Add Functions scope to ${name} in Netlify, then push again.`);
938
+ const isSecret = wasSecret || secret;
939
+ return {
940
+ is_secret: isSecret,
941
+ key: name,
942
+ scopes: [.../* @__PURE__ */ new Set([...scopes, "functions"])].filter((scope) => !isSecret || !/^post[-_]processing$/u.test(scope)),
943
+ values: [...others, {
944
+ context,
945
+ value
946
+ }]
947
+ };
948
+ }
949
+ /**
950
+ * The environment variables of the linked site for one deploy context. Netlify CLI 27.11 (`netlify env:list --help`,
951
+ * `netlify env:import --help`, in test/fixtures/host-cli-help/). `env:list --json` prints the names with values, so
952
+ * its stdout never goes into an error. `env:set` takes the value as an argument, and `env:import` replaces a variable
953
+ * in every context, so a value goes through the environment variables API with NETLIFY_AUTH_TOKEN instead:
954
+ * https://open-api.netlify.com/#tag/environmentVariables
955
+ */
956
+ function netlifyEnv(context) {
957
+ const netlify = hostCli("netlify", "netlify-cli", context.root, context.env);
958
+ const siteId = context.link.project.id ?? "";
959
+ if (!siteId) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOYMENTS_PROJECT_ID_REQUIRED({ host: "netlify" }), setupExitCodes.inputNeeded, {
960
+ missing: [{ field: "project.id" }],
961
+ rerun: "vitehub link --host netlify"
962
+ });
963
+ const deployContext = netlifyContexts[context.target];
964
+ let accountId = context.link.account?.id;
965
+ async function api() {
966
+ const credentials = await resolveHostCredentials("netlify", {
967
+ cwd: context.root,
968
+ env: context.env
969
+ });
970
+ if (!credentials.ok) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_CREDENTIALS_MISSING({
971
+ fix: credentials.fix,
972
+ host: "netlify"
973
+ }), setupExitCodes.inputNeeded, { missing: credentials.missing.map((field) => ({ field })) });
974
+ const request = createNetlifyApiClient(credentials.token, context.fetch);
975
+ if (!accountId) {
976
+ const site = await request(`/sites/${encodeURIComponent(siteId)}`);
977
+ accountId = isRecord(site) ? optionalString(site.account_id) : void 0;
978
+ if (!accountId) throw cliErrorDiagnostics.CLI_R0001({ message: "[vitehub] The Netlify API returned a site without account_id." });
979
+ }
980
+ return {
981
+ path: `/accounts/${encodeURIComponent(accountId)}/env`,
982
+ query: { site_id: siteId },
983
+ request
984
+ };
985
+ }
986
+ return {
987
+ async listSecretNames() {
988
+ const result = await context.run(netlify[0], [
989
+ ...netlify.slice(1),
990
+ "env:list",
991
+ "--context",
992
+ deployContext,
993
+ "--scope",
994
+ "functions",
995
+ "--json",
996
+ "--site",
997
+ siteId
998
+ ], {
999
+ cwd: context.root,
1000
+ env: context.env
1001
+ });
1002
+ if (result.exitCode !== 0) throw hostListFailed("netlify env:list", result, context.secrets);
1003
+ const value = lastJsonObject(result.stdout);
1004
+ if (!value) throw hostListFailed("netlify env:list printed no JSON", result, context.secrets);
1005
+ return Object.keys(value);
1006
+ },
1007
+ async setSecret(name, value, { secret }) {
1008
+ const { path, query, request } = await api();
1009
+ const existing = await request(`${path}/${encodeURIComponent(name)}`, { query }).catch((error) => {
1010
+ if (isProvisionRequestError(error) && error.status === 404) return void 0;
1011
+ throw error;
1012
+ });
1013
+ if (existing === void 0) {
1014
+ await request(path, {
1015
+ body: [{
1016
+ is_secret: secret,
1017
+ key: name,
1018
+ scopes: ["functions"],
1019
+ values: [{
1020
+ context: deployContext,
1021
+ value
1022
+ }]
1023
+ }],
1024
+ method: "POST",
1025
+ query
1026
+ });
1027
+ return;
1028
+ }
1029
+ const update = netlifyUpdate(existing, name, deployContext, value, secret);
1030
+ if (update) await request(`${path}/${encodeURIComponent(name)}`, {
1031
+ body: update,
1032
+ method: "PUT",
1033
+ query
1034
+ });
1035
+ else await request(`${path}/${encodeURIComponent(name)}`, {
1036
+ body: {
1037
+ context: deployContext,
1038
+ value
1039
+ },
1040
+ method: "PATCH",
1041
+ query
1042
+ });
1043
+ }
1044
+ };
1045
+ }
1046
+ const buildingStates = /* @__PURE__ */ new Set([
1047
+ "new",
1048
+ "pending_review",
1049
+ "accepted",
1050
+ "enqueued",
1051
+ "building",
1052
+ "uploading",
1053
+ "uploaded",
1054
+ "preparing",
1055
+ "prepared",
1056
+ "processing",
1057
+ "processed",
1058
+ "retrying"
1059
+ ]);
1060
+ function netlifyState(value) {
1061
+ if (value === "ready") return "ready";
1062
+ if (value === "error") return "error";
1063
+ if (value === "rejected") return "canceled";
1064
+ return typeof value === "string" && buildingStates.has(value) ? "building" : "unknown";
1065
+ }
1066
+ function parseNetlifyDeploys(value, published) {
1067
+ if (!Array.isArray(value)) return [];
1068
+ return value.flatMap((item) => {
1069
+ const id = isRecord(item) ? optionalString(item.id) : void 0;
1070
+ if (!id || !isRecord(item)) return [];
1071
+ const marked = parseCommitMessage(item.title);
1072
+ const ref = optionalString(item.commit_ref);
1073
+ const commit = marked ? {
1074
+ ...marked,
1075
+ from: "vitehub"
1076
+ } : ref ? {
1077
+ dirty: false,
1078
+ from: "host",
1079
+ sha: ref
1080
+ } : void 0;
1081
+ const url = optionalString(item.deploy_ssl_url) ?? optionalString(item.deploy_url);
1082
+ return [{
1083
+ createdAt: isoTime(item.created_at),
1084
+ id,
1085
+ live: id === published,
1086
+ source: marked ? "cli" : ref ? "git" : "unknown",
1087
+ state: netlifyState(item.state),
1088
+ target: item.context === "production" ? "production" : "preview",
1089
+ ...url ? { url } : {},
1090
+ ...commit ? { commit } : {}
1091
+ }];
1092
+ });
1093
+ }
1094
+ /**
1095
+ * Netlify API (https://open-api.netlify.com/), with the site id that `vitehub link` or the first `vitehub deploy` stored:
1096
+ * - `GET /api/v1/sites/{site_id}/deploys?per_page=`, newest first (`listSiteDeploys`).
1097
+ * - `GET /api/v1/sites/{site_id}`: `published_deploy.id` is the deploy that serves production (`getSite`).
1098
+ */
1099
+ const listNetlifyDeployments = async (context, { limit, includeLive }) => {
1100
+ const siteId = context.link.project.id ?? "";
1101
+ if (!siteId) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOYMENTS_PROJECT_ID_REQUIRED({ host: "netlify" }), setupExitCodes.inputNeeded, {
1102
+ missing: [{ field: "project.id" }],
1103
+ rerun: "vitehub link --host netlify"
1104
+ });
1105
+ const client = createNetlifyApiClient(context.credentials.token, context.fetch);
1106
+ const path = `/sites/${encodeURIComponent(siteId)}`;
1107
+ const [site, deploys] = await Promise.all([client(path), client(`${path}/deploys`, { query: {
1108
+ page: "1",
1109
+ per_page: String(limit)
1110
+ } })]);
1111
+ const published = isRecord(site) && isRecord(site.published_deploy) ? optionalString(site.published_deploy.id) : void 0;
1112
+ const recent = parseNetlifyDeploys(deploys, published).slice(0, limit);
1113
+ if (includeLive && published && !recent.some((item) => item.live)) {
1114
+ const live = await client(`/deploys/${encodeURIComponent(published)}`);
1115
+ recent.push(...parseNetlifyDeploys([live], published));
1116
+ }
1117
+ return recent;
1118
+ };
1119
+ // src/setup/env-encrypted.ts
1120
+ const prefix = "encrypted:";
1121
+ /** The file where dotenvx writes private keys. It must never be in git. */
1122
+ const envKeysFile = ".env.keys";
1123
+ function isEncryptedEnvValue(value) {
1124
+ return value.startsWith(prefix);
1125
+ }
1126
+ /**
1127
+ * The name of the private key for `file`, as dotenvx names it: the `DOTENV_PUBLIC_KEY*` name in the file wins,
1128
+ * then `.env` takes `DOTENV_PRIVATE_KEY` and `.env.<a>[.<b>]` takes `DOTENV_PRIVATE_KEY_<A>[_<B>]`.
1129
+ */
1130
+ function envPrivateKeyName(file, source) {
1131
+ const declared = Object.keys(parseEnv(source)).find((name) => name.startsWith("DOTENV_PUBLIC_KEY"));
1132
+ if (declared) return declared.replace("DOTENV_PUBLIC_KEY", "DOTENV_PRIVATE_KEY");
1133
+ const parts = basename$1(file).toLowerCase().split(".").slice(2);
1134
+ return parts.length ? `DOTENV_PRIVATE_KEY_${parts.slice(0, 2).join("_").toUpperCase()}` : "DOTENV_PRIVATE_KEY";
1135
+ }
1136
+ /**
1137
+ * Decrypts dotenvx values with the private key of each file, from `env` first and then from `.env.keys`.
1138
+ * A key may list several private keys separated by commas, as dotenvx allows during a rotation.
1139
+ * Returns the plaintext by name, and the private keys it used so that output can redact them.
1140
+ */
1141
+ async function decryptEnvValues(root, items, env) {
1142
+ const values = /* @__PURE__ */ new Map();
1143
+ const keys = /* @__PURE__ */ new Set();
1144
+ if (!items.length) return {
1145
+ keys: [],
1146
+ values
1147
+ };
1148
+ const keysPath = join(root, envKeysFile);
1149
+ const keysFile = existsSync(keysPath) ? parseEnv(await readFile(keysPath, "utf8")) : {};
1150
+ const { decrypt } = await import("@dotenvx/primitives");
1151
+ const byFile = /* @__PURE__ */ new Map();
1152
+ for (const item of items) byFile.set(item.file, [...byFile.get(item.file) ?? [], item]);
1153
+ for (const [file, group] of byFile) {
1154
+ const keyName = envPrivateKeyName(file, await readFile(join(root, file), "utf8"));
1155
+ const names = group.map((item) => item.name).join(", ");
1156
+ const candidates = (env[keyName] || keysFile[keyName] || "").split(",").map((key) => key.trim()).filter(Boolean);
1157
+ if (!candidates.length) throw setupFailure(cliErrorDiagnostics.SETUP_ENV_PRIVATE_KEY_MISSING({
1158
+ file,
1159
+ key: keyName,
1160
+ names
1161
+ }), setupExitCodes.inputNeeded, { missing: [{ field: keyName }] });
1162
+ for (const key of candidates) keys.add(key);
1163
+ for (const item of group) {
1164
+ const errors = [];
1165
+ for (const key of candidates) try {
1166
+ values.set(item.name, decrypt(key, item.value));
1167
+ break;
1168
+ } catch (error) {
1169
+ const code = error instanceof Error ? Reflect.get(error, "code") : void 0;
1170
+ errors.push(typeof code === "string" ? code : "DECRYPTION_FAILED");
1171
+ }
1172
+ if (!values.has(item.name)) throw setupFailure(cliErrorDiagnostics.SETUP_ENV_DECRYPT_FAILED({
1173
+ file,
1174
+ key: keyName,
1175
+ name: item.name,
1176
+ reason: errors.at(-1)
1177
+ }), setupExitCodes.error);
1178
+ }
1179
+ }
1180
+ return {
1181
+ keys: [...keys],
1182
+ values
1183
+ };
1184
+ }
1185
+ // src/setup/deploy/github.ts
1186
+ const apiBase = "https://api.github.com";
1187
+ const repositoryPattern = /^[\w.-]+\/[\w.-]+$/u;
1188
+ /** GitHub accepts letters, digits, and `_`, not a digit first, and reserves the `GITHUB_` prefix. */
1189
+ function isGitHubSecretName(name) {
1190
+ return /^[A-Z_]\w*$/iu.test(name) && !/^GITHUB_/iu.test(name);
1191
+ }
1192
+ /** The `owner/name` of a GitHub remote URL: HTTPS, `git@github.com:`, or `ssh://`. */
1193
+ function githubRepositoryFromRemote(url) {
1194
+ return /^(?:https:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([\w.-]+\/[\w.-]+?)(?:\.git)?\/?$/u.exec(url.trim())?.[1];
1195
+ }
1196
+ /** `--repo`, else the GitHub repository of the git remote `origin`. */
1197
+ async function resolveGitHubRepository(repo, options) {
1198
+ if (repo !== void 0) {
1199
+ if (!repositoryPattern.test(repo)) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] --repo ${JSON.stringify(repo)} is not owner/name.` });
1200
+ return repo;
1201
+ }
1202
+ const result = await options.run("git", [
1203
+ "remote",
1204
+ "get-url",
1205
+ "origin"
1206
+ ], {
1207
+ cwd: options.root,
1208
+ env: options.env
1209
+ }).catch(() => void 0);
1210
+ const remote = result?.exitCode === 0 ? result.stdout.trim() : void 0;
1211
+ const repository = remote ? githubRepositoryFromRemote(remote) : void 0;
1212
+ if (!repository) throw setupFailure(cliErrorDiagnostics.SETUP_GITHUB_REPOSITORY_REQUIRED({ remote: remote ?? "" }), setupExitCodes.inputNeeded, { missing: [{ field: "repo" }] });
1213
+ return repository;
1214
+ }
1215
+ /**
1216
+ * A token that can write Actions secrets, in this order: `GITHUB_TOKEN`, `GH_TOKEN`, `gh auth token`, then an
1217
+ * installation token of the GitHub App that `@vite-hub/forge` reads (`VITEHUB_GITHUB_APP_ID`).
1218
+ */
1219
+ async function resolveGitHubToken(repository, options) {
1220
+ for (const name of ["GITHUB_TOKEN", "GH_TOKEN"]) {
1221
+ const token = options.env[name]?.trim();
1222
+ if (token) return token;
1223
+ }
1224
+ const gh = await options.run("gh", [
1225
+ "auth",
1226
+ "token",
1227
+ "--hostname",
1228
+ "github.com"
1229
+ ], {
1230
+ cwd: options.root,
1231
+ env: options.env
1232
+ }).catch(() => void 0);
1233
+ const ghToken = gh?.exitCode === 0 ? gh.stdout.trim() : "";
1234
+ if (ghToken) return ghToken;
1235
+ if (options.env.VITEHUB_GITHUB_APP_ID?.trim()) {
1236
+ const forge = await import("@vite-hub/forge").catch(() => void 0);
1237
+ if (!forge) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_CREDENTIALS_MISSING({
1238
+ fix: "Install @vite-hub/forge to use the GitHub App of VITEHUB_GITHUB_APP_ID, or set GITHUB_TOKEN.",
1239
+ host: "GitHub"
1240
+ }), setupExitCodes.inputNeeded, { missing: [{ field: "GITHUB_TOKEN" }] });
1241
+ const [error, token] = await forge.useForge({
1242
+ env: options.env,
1243
+ baseUrl: apiBase,
1244
+ fetch: options.fetch
1245
+ }).token({ repository });
1246
+ if (error) throw setupFailure(cliErrorDiagnostics.SETUP_GITHUB_REQUEST_FAILED({
1247
+ operation: `GitHub App token for ${repository}`,
1248
+ reason: error.message
1249
+ }), setupExitCodes.error);
1250
+ return token.token;
1251
+ }
1252
+ throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_CREDENTIALS_MISSING({
1253
+ fix: "Set GITHUB_TOKEN or GH_TOKEN to a token that can write the Actions secrets of the repository, run `gh auth login`, or set VITEHUB_GITHUB_APP_ID and the private key of a GitHub App that is installed on it.",
1254
+ host: "GitHub"
1255
+ }), setupExitCodes.inputNeeded, { missing: [{ field: "GITHUB_TOKEN" }] });
1256
+ }
1257
+ function concat(...parts) {
1258
+ const out = new Uint8Array(parts.reduce((size, part) => size + part.length, 0));
1259
+ let offset = 0;
1260
+ for (const part of parts) {
1261
+ out.set(part, offset);
1262
+ offset += part.length;
1263
+ }
1264
+ return out;
1265
+ }
1266
+ const sigma = new Uint32Array([
1267
+ 1634760805,
1268
+ 857760878,
1269
+ 2036477234,
1270
+ 1797285236
1271
+ ]);
1272
+ function words(bytes) {
1273
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1274
+ return Uint32Array.from({ length: bytes.length / 4 }, (_, index) => view.getUint32(index * 4, true));
1275
+ }
1276
+ function wordBytes(input) {
1277
+ const out = new Uint8Array(input.length * 4);
1278
+ const view = new DataView(out.buffer);
1279
+ input.forEach((word, index) => view.setUint32(index * 4, word, true));
1280
+ return out;
1281
+ }
1282
+ function boxKey(shared) {
1283
+ const out = /* @__PURE__ */ new Uint32Array(8);
1284
+ hsalsa(sigma, words(shared), /* @__PURE__ */ new Uint32Array(4), out);
1285
+ return wordBytes(out);
1286
+ }
1287
+ function x25519PublicKey(raw) {
1288
+ return createPublicKey({
1289
+ format: "jwk",
1290
+ key: {
1291
+ crv: "X25519",
1292
+ kty: "OKP",
1293
+ x: Buffer.from(raw).toString("base64url")
1294
+ }
1295
+ });
1296
+ }
1297
+ /**
1298
+ * libsodium `crypto_box_seal`, the encryption that GitHub wants for secrets: an ephemeral X25519 key pair,
1299
+ * nonce = BLAKE2b-192(ephemeral public key || recipient public key), XSalsa20-Poly1305. Output: ephemeral public key, tag, ciphertext.
1300
+ */
1301
+ function sealSecret(value, recipientPublicKey) {
1302
+ const ephemeral = generateKeyPairSync("x25519");
1303
+ const ephemeralPublicKey = Buffer.from(ephemeral.publicKey.export({ format: "jwk" }).x ?? "", "base64url");
1304
+ const nonce = blake2b(concat(ephemeralPublicKey, recipientPublicKey), { dkLen: 24 });
1305
+ const shared = diffieHellman({
1306
+ privateKey: ephemeral.privateKey,
1307
+ publicKey: x25519PublicKey(recipientPublicKey)
1308
+ });
1309
+ return concat(ephemeralPublicKey, xsalsa20poly1305(boxKey(shared), nonce).encrypt(new TextEncoder().encode(value)));
1310
+ }
1311
+ /** The Actions secrets of a repository or environment, through the GitHub REST API. Values go only in a sealed request body. */
1312
+ function githubEnv(context) {
1313
+ const [owner, name] = context.repository.split("/");
1314
+ const base = `${apiBase}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}${context.environment ? `/environments/${encodeURIComponent(context.environment)}` : "/actions"}/secrets`;
1315
+ async function request(method, path, body) {
1316
+ const response = await context.fetch(`${base}${path}`, {
1317
+ headers: {
1318
+ "accept": "application/vnd.github+json",
1319
+ "authorization": `Bearer ${context.token}`,
1320
+ "user-agent": "vitehub",
1321
+ "x-github-api-version": "2022-11-28",
1322
+ ...body ? { "content-type": "application/json" } : {}
1323
+ },
1324
+ method,
1325
+ ...body ? { body: JSON.stringify(body) } : {}
1326
+ });
1327
+ if (response.ok) return response.status === 204 || response.status === 201 ? void 0 : await response.json();
1328
+ const text = await response.text().catch(() => "");
1329
+ const message = /"message"\s*:\s*"([^"]*)"/u.exec(text)?.[1] ?? text.slice(0, 200);
1330
+ const operation = `${method} ${new URL(`${base}${path}`).pathname}`;
1331
+ const hint = response.status === 404 && context.environment ? ` The environment ${context.environment} may not exist: create it in the repository settings.` : response.status === 404 || response.status === 403 ? " The token needs write access to the repository secrets." : "";
1332
+ throw setupFailure(cliErrorDiagnostics.SETUP_GITHUB_REQUEST_FAILED({
1333
+ operation,
1334
+ reason: `${response.status} ${redact(message, [...context.secrets, context.token])}.${hint}`
1335
+ }), setupExitCodes.error);
1336
+ }
1337
+ let publicKey;
1338
+ return {
1339
+ async listSecretNames() {
1340
+ const names = [];
1341
+ for (let page = 1;; page++) {
1342
+ const body = await request("GET", `?per_page=100&page=${page}`);
1343
+ const secrets = body.secrets ?? [];
1344
+ names.push(...secrets.map((secret) => secret.name));
1345
+ if (!secrets.length || names.length >= (body.total_count ?? 0)) return names;
1346
+ }
1347
+ },
1348
+ async setSecret(secretName, value) {
1349
+ publicKey ??= request("GET", "/public-key").then((body) => ({
1350
+ key: Buffer.from(body.key, "base64"),
1351
+ key_id: body.key_id
1352
+ }));
1353
+ const { key, key_id } = await publicKey;
1354
+ const encrypted = Buffer.from(sealSecret(value, key)).toString("base64");
1355
+ await request("PUT", `/${encodeURIComponent(secretName)}`, {
1356
+ encrypted_value: encrypted,
1357
+ key_id
1358
+ });
1359
+ }
1360
+ };
1361
+ }
1362
+ // src/setup/env.ts
1363
+ var env_exports = /* @__PURE__ */ __exportAll({ runEnvCommand: () => runEnvCommand });
1364
+ const defaultStage = "production";
1365
+ const tokenNames = [
1366
+ "CLOUDFLARE_API_TOKEN",
1367
+ "VERCEL_TOKEN",
1368
+ "NETLIFY_AUTH_TOKEN",
1369
+ "DENO_DEPLOY_TOKEN"
1370
+ ];
1371
+ const hostEnvs = {
1372
+ cloudflare: cloudflareEnv,
1373
+ deno: denoEnv,
1374
+ netlify: netlifyEnv,
1375
+ vercel: vercelEnv
1376
+ };
1377
+ const noPreview = /* @__PURE__ */ new Set(["cloudflare", "deno"]);
1378
+ function readEnvArgs(args, push, usage) {
1379
+ try {
1380
+ const { values } = parseArgs({
1381
+ args: [...args],
1382
+ options: {
1383
+ help: {
1384
+ short: "h",
1385
+ type: "boolean",
1386
+ default: false
1387
+ },
1388
+ host: { type: "string" },
1389
+ json: {
1390
+ type: "boolean",
1391
+ default: false
1392
+ },
1393
+ stage: { type: "string" },
1394
+ to: { type: "string" },
1395
+ repo: { type: "string" },
1396
+ environment: { type: "string" },
1397
+ ...push ? {
1398
+ only: {
1399
+ multiple: true,
1400
+ type: "string"
1401
+ },
1402
+ yes: {
1403
+ short: "y",
1404
+ type: "boolean",
1405
+ default: false
1406
+ }
1407
+ } : {}
1408
+ },
1409
+ strict: true
1410
+ });
1411
+ const host = readLinkHostOption(typeof values.host === "string" ? values.host : void 0);
1412
+ const stage = typeof values.stage === "string" ? values.stage : defaultStage;
1413
+ const only = Array.isArray(values.only) ? values.only.filter((item) => typeof item === "string") : [];
1414
+ const repo = typeof values.repo === "string" ? values.repo : void 0;
1415
+ const environment = typeof values.environment === "string" ? values.environment : void 0;
1416
+ if (values.to !== void 0 && values.to !== "github") throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] Unknown --to ${JSON.stringify(values.to)}. The only destination is github. For a host, use --host.` });
1417
+ if (values.to === void 0 && (repo !== void 0 || environment !== void 0)) throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] --repo and --environment need --to github. Usage: ${usage}` });
1418
+ const github = values.to === "github" ? {
1419
+ ...repo === void 0 ? {} : { repo },
1420
+ ...environment === void 0 ? {} : { environment }
1421
+ } : void 0;
1422
+ return {
1423
+ help: values.help === true,
1424
+ ...host ? { host } : {},
1425
+ ...github ? { github } : {},
1426
+ json: values.json === true,
1427
+ only,
1428
+ stage,
1429
+ yes: values.yes === true
1430
+ };
1431
+ } catch (error) {
1432
+ if (isSetupFailure(error) || error instanceof Error && "why" in error) throw error;
1433
+ throw cliErrorDiagnostics.CLI_R0003({ message: `[vitehub] ${error instanceof Error ? error.message : String(error)} Usage: ${usage}` });
1434
+ }
1435
+ }
1436
+ function stageTarget(host, stage) {
1437
+ if (stage === "production") return "production";
1438
+ if (stage !== "preview" || noPreview.has(host)) throw setupFailure(cliErrorDiagnostics.SETUP_ENV_STAGE_UNSUPPORTED({
1439
+ host,
1440
+ stage
1441
+ }), setupExitCodes.conflict);
1442
+ return "preview";
1443
+ }
1444
+ function linkedTarget(links, host, command) {
1445
+ const selected = selectSetupLink(links, host);
1446
+ if ("ambiguous" in selected) throw hostRequired(selected.ambiguous, command);
1447
+ if (!selected.link) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOYMENTS_NOT_LINKED({ host }), setupExitCodes.inputNeeded, {
1448
+ missing: [{ field: "link" }],
1449
+ rerun: host ? `vitehub link --host ${host}` : "vitehub link"
1450
+ });
1451
+ return selected.link;
1452
+ }
1453
+ async function readNames(project, host, context) {
1454
+ try {
1455
+ return await readBuildOutput(project.root, host);
1456
+ } catch (error) {
1457
+ const code = isSetupFailure(error) ? Reflect.get(error, "code") : void 0;
1458
+ if (code !== "SETUP_DEPLOY_OUTPUT_MISSING" && code !== "SETUP_DEPLOY_HOST_MISMATCH") throw error;
1459
+ }
1460
+ context.stderr.write(`No build output for ${host}. Building it to read the names.\n`);
1461
+ await build(project, host, context);
1462
+ return await readBuildOutput(project.root, host);
1463
+ }
1464
+ async function configVarNames(host, outputDir) {
1465
+ return new Set(host === "cloudflare" ? await wranglerVarNames(outputDir) : []);
1466
+ }
1467
+ function hostTokens(env) {
1468
+ return tokenNames.flatMap((name) => {
1469
+ const token = env[name]?.trim();
1470
+ return token ? [token] : [];
1471
+ });
1472
+ }
1473
+ async function openTarget(args, command, context) {
1474
+ const project = await readSetupProject(context.rootDir, context.env);
1475
+ if (args.github) return await openGitHubTarget(args, args.github, project, command, context);
1476
+ const link = linkedTarget(await readSetupLinks(project.root), args.host, command);
1477
+ const host = link.host;
1478
+ const target = stageTarget(host, args.stage);
1479
+ const { env: entries, envDir, outputDir } = await readNames(project, host, context);
1480
+ const configVars = await configVarNames(host, outputDir);
1481
+ const secrets = hostTokens(context.env);
1482
+ const run = createDeployRun(context.stderr, secrets);
1483
+ return {
1484
+ configVars,
1485
+ entries,
1486
+ envDir,
1487
+ host,
1488
+ hostEnv: hostEnvs[host]({
1489
+ env: context.env,
1490
+ fetch: context.fetch ?? globalThis.fetch,
1491
+ link,
1492
+ root: project.root,
1493
+ run,
1494
+ secrets,
1495
+ target
1496
+ }),
1497
+ name: link.project.name,
1498
+ project,
1499
+ run,
1500
+ secrets,
1501
+ stage: args.stage,
1502
+ target
1503
+ };
1504
+ }
1505
+ async function openGitHubTarget(args, options, project, command, context) {
1506
+ const selected = selectSetupLink(await readSetupLinks(project.root), args.host);
1507
+ if ("ambiguous" in selected) throw hostRequired(selected.ambiguous, `${command} --to github`);
1508
+ const host = args.host ?? selected.link?.host;
1509
+ if (!host) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOYMENTS_NOT_LINKED({}), setupExitCodes.inputNeeded, {
1510
+ missing: [{ field: "host" }],
1511
+ rerun: `${command} --to github --host cloudflare`
1512
+ });
1513
+ const { env: buildEntries, envDir } = await readNames(project, host, context);
1514
+ const entries = buildEntries.flatMap((entry) => {
1515
+ const names = entry.names.filter(isGitHubSecretName);
1516
+ return names.length || entry.prefix ? [{
1517
+ ...entry,
1518
+ names
1519
+ }] : [];
1520
+ });
1521
+ const secrets = hostTokens(context.env);
1522
+ const run = createDeployRun(context.stderr, secrets);
1523
+ const fetch = context.fetch ?? globalThis.fetch;
1524
+ const repository = await resolveGitHubRepository(options.repo, {
1525
+ env: context.env,
1526
+ root: project.root,
1527
+ run
1528
+ });
1529
+ const token = await resolveGitHubToken(repository, {
1530
+ env: context.env,
1531
+ fetch,
1532
+ root: project.root,
1533
+ run
1534
+ });
1535
+ secrets.push(token);
1536
+ const github = {
1537
+ repository,
1538
+ ...options.environment ? { environment: options.environment } : {}
1539
+ };
1540
+ const name = selected.link?.project.name ?? (await readBuildOutput(project.root, host)).identityName ?? repository;
1541
+ return {
1542
+ configVars: /* @__PURE__ */ new Set(),
1543
+ entries,
1544
+ envDir,
1545
+ github,
1546
+ host,
1547
+ hostEnv: githubEnv({
1548
+ ...github,
1549
+ fetch,
1550
+ secrets,
1551
+ token
1552
+ }),
1553
+ name,
1554
+ project,
1555
+ run,
1556
+ secrets,
1557
+ stage: args.stage
1558
+ };
1559
+ }
1560
+ function diffEntry(entry) {
1561
+ return {
1562
+ names: entry.names,
1563
+ ...entry.prefix ? { prefix: entry.prefix } : {},
1564
+ ...entry.path ? { path: entry.path } : {},
1565
+ ...entry.owners?.length ? { owners: entry.owners } : {},
1566
+ secret: entry.secret
1567
+ };
1568
+ }
1569
+ function isRequired(entry) {
1570
+ return entry.required && !entry.hasDefault;
1571
+ }
1572
+ function matchesPrefix(entry, name) {
1573
+ return !!entry.prefix && name.startsWith(entry.prefix) && name.length > entry.prefix.length;
1574
+ }
1575
+ function isSet(entry, names) {
1576
+ return entry.names.some((name) => names.has(name)) || [...names].some((name) => matchesPrefix(entry, name));
1577
+ }
1578
+ /** Compares the names that the build lists with the names on the host. Hosts return no values, so it never says "changed". */
1579
+ function diffEnvNames(entries, hostNames, ignoreCase = false, configVars = /* @__PURE__ */ new Set()) {
1580
+ const normalize = (name) => ignoreCase ? name.toUpperCase() : name;
1581
+ const comparable = (entry) => ignoreCase ? {
1582
+ ...entry,
1583
+ names: entry.names.map(normalize),
1584
+ ...entry.prefix ? { prefix: normalize(entry.prefix) } : {}
1585
+ } : entry;
1586
+ const onHost = new Set([...hostNames, ...configVars].map(normalize));
1587
+ const missing = {
1588
+ optional: [],
1589
+ required: []
1590
+ };
1591
+ for (const entry of entries) {
1592
+ if (isSet(comparable(entry), onHost)) continue;
1593
+ missing[isRequired(entry) ? "required" : "optional"].push(diffEntry(entry));
1594
+ }
1595
+ const known = (name) => entries.some((entry) => {
1596
+ const compared = comparable(entry);
1597
+ return compared.names.includes(normalize(name)) || matchesPrefix(compared, normalize(name));
1598
+ });
1599
+ return {
1600
+ extra: hostNames.filter((name) => !known(name) && !configVars.has(name)).sort(),
1601
+ missing,
1602
+ ok: !missing.required.length
1603
+ };
1604
+ }
1605
+ function entryLabel(entry) {
1606
+ const names = [...entry.names, ...entry.prefix ? [`${entry.prefix}*`] : []].join(" or ");
1607
+ const from = entry.path ?? entry.owners?.join(", ");
1608
+ return from ? `${names} (${from})` : names;
1609
+ }
1610
+ function targetLabel(output) {
1611
+ if (output.github) return `the GitHub Actions secrets of ${output.github.repository}${output.github.environment ? `, environment ${output.github.environment}` : ""}, stage ${output.stage}`;
1612
+ return `${output.project} on ${output.host}, stage ${output.stage}${output.target === output.stage ? "" : ` (${output.target})`}`;
1613
+ }
1614
+ function destinationFlags(output) {
1615
+ return [...output.github ? [
1616
+ "--to github",
1617
+ `--repo ${output.github.repository}`,
1618
+ `--host ${output.host}`,
1619
+ ...output.github.environment ? [`--environment ${output.github.environment}`] : []
1620
+ ] : [`--host ${output.host}`], ...output.stage === defaultStage ? [] : [`--stage ${output.stage}`]];
1621
+ }
1622
+ function writeDiff(output, context) {
1623
+ const lines = [`Env names of ${targetLabel(output)}:`];
1624
+ const section = (title, items) => {
1625
+ if (items.length) lines.push(`${title}:`, ...items.map((item) => ` ${item}`));
1626
+ };
1627
+ section("Missing required", output.missing.required.map(entryLabel));
1628
+ section("Missing optional", output.missing.optional.map(entryLabel));
1629
+ const where = output.github ? "on GitHub" : "on the host";
1630
+ section(`Extra ${where}, read by no declaration`, output.extra);
1631
+ if (!output.missing.required.length && !output.missing.optional.length && !output.extra.length) lines.push(`Every name is ${where}.`);
1632
+ lines.push(`${output.github ? "GitHub does" : "Hosts do"} not return values, so this compares names only.`);
1633
+ if (output.missing.required.length || output.missing.optional.length) lines.push(`Run \`${["vitehub env push", ...destinationFlags(output)].join(" ")}\` to set them from the shell and .env.${output.stage}.`);
1634
+ context.stdout.write(`${lines.join("\n")}\n`);
1635
+ }
1636
+ async function runDiff(args, context) {
1637
+ const target = await openTarget(args, "vitehub env diff", context);
1638
+ const hostNames = await target.hostEnv.listSecretNames();
1639
+ const output = {
1640
+ ...destination(target),
1641
+ ...diffEnvNames(target.entries, hostNames, !!target.github, target.configVars)
1642
+ };
1643
+ if (args.json) writeSetupJson(context, output);
1644
+ else writeDiff(output, context);
1645
+ return output.ok ? setupExitCodes.done : setupExitCodes.error;
1646
+ }
1647
+ function destination(target) {
1648
+ return {
1649
+ host: target.host,
1650
+ project: target.name,
1651
+ stage: target.stage,
1652
+ ...target.target ? { target: target.target } : {},
1653
+ ...target.github ? { github: target.github } : {}
1654
+ };
1655
+ }
1656
+ function fileSource(root, path) {
1657
+ const folder = relative(root, dirname(path));
1658
+ return `${folder ? `${folder}/` : ""}.env${basename(path).slice(4)}`;
1659
+ }
1660
+ function expandedFiles(raw, env) {
1661
+ const parsed = Object.fromEntries([...raw].map(([name, file]) => [name, file.value]));
1662
+ const files = new Map([...raw].map(([name, file]) => [name, /* @__PURE__ */ new Set([file.path])]));
1663
+ for (const name of Object.keys(parsed)) {
1664
+ let result = parsed[name];
1665
+ const sources = new Set(files.get(name));
1666
+ if (env[name] && env[name] !== result) {
1667
+ parsed[name] = env[name];
1668
+ files.set(name, /* @__PURE__ */ new Set());
1669
+ continue;
1670
+ }
1671
+ const values = {
1672
+ ...parsed,
1673
+ ...env
1674
+ };
1675
+ const regex = /(?<!\\)\${([^{}]+)}|(?<!\\)\$([A-Za-z_][A-Za-z0-9_]*)/g;
1676
+ const seen = /* @__PURE__ */ new Set();
1677
+ let match;
1678
+ while ((match = regex.exec(result)) !== null) {
1679
+ seen.add(result);
1680
+ const template = match[0];
1681
+ const expression = match[1] || match[2];
1682
+ const operator = expression.match(/(:\+|\+|:-|-)/)?.[0];
1683
+ const parts = operator ? expression.split(operator) : [expression];
1684
+ const key = parts.shift();
1685
+ if (env[key] === void 0) for (const path of files.get(key) ?? []) sources.add(path);
1686
+ const alternate = operator === ":+" || operator === "+";
1687
+ const fallback = alternate && !values[key] ? "" : parts.join(operator);
1688
+ const replacement = alternate ? void 0 : values[key];
1689
+ result = result.replace(template, replacement && !seen.has(replacement) ? replacement : fallback);
1690
+ if (result === parsed[key]) break;
1691
+ regex.lastIndex = 0;
1692
+ }
1693
+ parsed[name] = result.replace(/\\\$/g, "$");
1694
+ files.set(name, sources);
1695
+ }
1696
+ return files;
1697
+ }
1698
+ /**
1699
+ * The values of `stage` as Vite loads them: `.env`, `.env.local`, `.env.<stage>`, `.env.<stage>.local` in `envDir`, with
1700
+ * later files winning and the shell winning over every file (`packages/internal/src/vite-stage.ts`). With `envDir: false`
1701
+ * only the shell counts. Each value keeps its source, and every file that it reads through `$NAME` expansion.
1702
+ */
1703
+ async function readLocalEnvValues(root, envDir, stage, env) {
1704
+ const raw = /* @__PURE__ */ new Map();
1705
+ const paths = envDir === false ? [] : [
1706
+ ".env",
1707
+ ".env.local",
1708
+ `.env.${stage}`,
1709
+ `.env.${stage}.local`
1710
+ ].map((file) => join(envDir, file));
1711
+ for (const path of paths) {
1712
+ if (!(await stat(path).catch(() => void 0))?.isFile()) continue;
1713
+ for (const [name, value] of Object.entries(parseEnv(await readFile(path, "utf8")))) if (value !== void 0) raw.set(name, {
1714
+ path,
1715
+ value
1716
+ });
1717
+ }
1718
+ const ciphertextSources = /* @__PURE__ */ new Map();
1719
+ for (const file of raw.values()) if (isEncryptedEnvValue(file.value)) ciphertextSources.set(file.value, file.path);
1720
+ const files = expandedFiles(raw, env);
1721
+ const vite = await import("vite");
1722
+ const loaded = await withViteStageEnvironment(env, async () => loadAllEnv(vite.loadEnv, stage, envDir));
1723
+ const values = /* @__PURE__ */ new Map();
1724
+ for (const [name, value] of Object.entries(loaded)) {
1725
+ if (value === "") continue;
1726
+ if (env[name] !== void 0) values.set(name, {
1727
+ encrypted: false,
1728
+ files: [],
1729
+ source: "process",
1730
+ value
1731
+ });
1732
+ else {
1733
+ const own = raw.get(name);
1734
+ if (own) {
1735
+ const origin = own.value === value ? own.path : ciphertextSources.get(value) ?? own.path;
1736
+ values.set(name, {
1737
+ encrypted: isEncryptedEnvValue(value),
1738
+ files: [...files.get(name) ?? []],
1739
+ source: fileSource(root, origin),
1740
+ value
1741
+ });
1742
+ }
1743
+ }
1744
+ }
1745
+ return values;
1746
+ }
1747
+ function planPush(entries, values, only, onHost = /* @__PURE__ */ new Set()) {
1748
+ const wanted = only.length ? new Set(only) : void 0;
1749
+ const unknown = only.filter((name) => !entries.some((entry) => entry.names.includes(name) || matchesPrefix(entry, name)));
1750
+ if (unknown.length) throw setupFailure(cliErrorDiagnostics.SETUP_ENV_NAME_UNKNOWN({ names: unknown.join(", ") }), setupExitCodes.inputNeeded);
1751
+ const planned = /* @__PURE__ */ new Map();
1752
+ const skipped = [];
1753
+ for (const entry of entries) {
1754
+ const names = entry.names.some((name) => onHost.has(name)) ? [] : wanted ? entry.names.filter((name) => wanted.has(name)) : entry.names;
1755
+ const prefixed = [...values.keys()].filter((name) => matchesPrefix(entry, name) && !onHost.has(name) && (!wanted || wanted.has(name)));
1756
+ if (!names.length && !prefixed.length && wanted) continue;
1757
+ const first = names.find((name) => values.has(name));
1758
+ const chosen = [...first ? [first] : [], ...prefixed];
1759
+ if (!chosen.length) {
1760
+ if (isSet(entry, onHost)) continue;
1761
+ skipped.push({
1762
+ ...diffEntry(entry),
1763
+ required: isRequired(entry)
1764
+ });
1765
+ continue;
1766
+ }
1767
+ for (const name of chosen) {
1768
+ const local = values.get(name);
1769
+ const current = planned.get(name);
1770
+ planned.set(name, {
1771
+ encrypted: local.encrypted,
1772
+ files: local.files,
1773
+ name,
1774
+ secret: entry.secret || (current?.secret ?? false),
1775
+ source: local.source,
1776
+ value: local.value
1777
+ });
1778
+ }
1779
+ }
1780
+ return {
1781
+ planned: [...planned.values()],
1782
+ skipped
1783
+ };
1784
+ }
1785
+ function inGitRepository(directory, env) {
1786
+ if (env.GIT_DIR) return true;
1787
+ for (let current = directory;; current = dirname(current)) {
1788
+ const marker = join(current, ".git");
1789
+ if (existsSync(marker) && (!statSync(marker).isDirectory() || existsSync(join(marker, "HEAD")))) return true;
1790
+ if (dirname(current) === current) return false;
1791
+ }
1792
+ }
1793
+ async function gitFileState(file, label, run, env) {
1794
+ const failed = (reason) => setupFailure(cliErrorDiagnostics.SETUP_ENV_GIT_FAILED({
1795
+ file: label,
1796
+ reason
1797
+ }), setupExitCodes.error);
1798
+ const git = async (args) => {
1799
+ try {
1800
+ return await run("git", args, {
1801
+ cwd: dirname(file),
1802
+ env
1803
+ });
1804
+ } catch (error) {
1805
+ throw failed(error instanceof Error ? error.message : String(error));
1806
+ }
1807
+ };
1808
+ const tracked = await git([
1809
+ "ls-files",
1810
+ "--error-unmatch",
1811
+ "--",
1812
+ basename(file)
1813
+ ]);
1814
+ if (tracked.exitCode === 0) return "tracked";
1815
+ if (tracked.exitCode !== 1) throw failed(tracked.stderr.trim() || `git ls-files exited with ${tracked.exitCode}`);
1816
+ const ignored = await git([
1817
+ "check-ignore",
1818
+ "-q",
1819
+ "--",
1820
+ basename(file)
1821
+ ]);
1822
+ if (ignored.exitCode === 0) return "ignored";
1823
+ if (ignored.exitCode === 1) return "unignored";
1824
+ throw failed(ignored.stderr.trim() || `git check-ignore exited with ${ignored.exitCode}`);
1825
+ }
1826
+ async function assertUntracked(planned, root, run, env, stderr) {
1827
+ const byFile = /* @__PURE__ */ new Map();
1828
+ for (const item of planned) {
1829
+ if (!item.secret || item.encrypted) continue;
1830
+ for (const file of item.files) {
1831
+ const real = await realpath(file);
1832
+ byFile.set(real, [.../* @__PURE__ */ new Set([...byFile.get(real) ?? [], item.name])]);
1833
+ }
1834
+ }
1835
+ const realRoot = await realpath(root).catch(() => root);
1836
+ for (const [file, names] of byFile) {
1837
+ const label = relative(realRoot, file);
1838
+ if (!inGitRepository(dirname(file), env)) {
1839
+ stderr.write(`Warning: ${label} is not in a git repository, so ViteHub cannot check that git ignores it.\n`);
1840
+ continue;
1841
+ }
1842
+ const state = await gitFileState(file, label, run, env);
1843
+ if (state === "tracked") throw setupFailure(cliErrorDiagnostics.SETUP_ENV_FILE_TRACKED({
1844
+ file: label,
1845
+ names: names.join(", ")
1846
+ }), setupExitCodes.conflict);
1847
+ if (state === "unignored") throw setupFailure(cliErrorDiagnostics.SETUP_ENV_FILE_NOT_IGNORED({
1848
+ file: label,
1849
+ names: names.join(", ")
1850
+ }), setupExitCodes.conflict);
1851
+ }
1852
+ const keysPath = join(root, envKeysFile);
1853
+ const realKeys = await realpath(keysPath).catch(() => void 0);
1854
+ if (planned.some((item) => item.encrypted) && realKeys && inGitRepository(dirname(realKeys), env) && await gitFileState(realKeys, ".env.keys", run, env) === "tracked") throw setupFailure(cliErrorDiagnostics.SETUP_ENV_KEYS_TRACKED({ file: envKeysFile }), setupExitCodes.conflict);
1855
+ }
1856
+ async function decryptPlanned(planned, root, env, secrets) {
1857
+ const { keys, values } = await decryptEnvValues(root, planned.filter((item) => item.encrypted).map((item) => ({
1858
+ file: item.source,
1859
+ name: item.name,
1860
+ value: item.value
1861
+ })), env);
1862
+ secrets.push(...keys);
1863
+ return planned.map((item) => {
1864
+ const value = values.get(item.name);
1865
+ if (value === void 0) return item;
1866
+ secrets.push(value);
1867
+ return {
1868
+ ...item,
1869
+ value
1870
+ };
1871
+ });
1872
+ }
1873
+ async function confirmPush(planned, label) {
1874
+ const terminal = createInterface({
1875
+ input: process.stdin,
1876
+ output: process.stderr
1877
+ });
1878
+ try {
1879
+ return /^y(?:es)?$/iu.test((await terminal.question(`Push ${planned.map((item) => item.name).join(", ")} to ${label}? [y/N] `)).trim());
1880
+ } finally {
1881
+ terminal.close();
1882
+ }
1883
+ }
1884
+ function pushRerun(args) {
1885
+ const github = args.github ? [
1886
+ "--to github",
1887
+ ...args.github.repo ? [`--repo ${args.github.repo}`] : [],
1888
+ ...args.github.environment ? [`--environment ${args.github.environment}`] : []
1889
+ ] : [];
1890
+ return [
1891
+ "vitehub env push",
1892
+ ...args.host ? [`--host ${args.host}`] : [],
1893
+ ...github,
1894
+ ...args.stage === defaultStage ? [] : [`--stage ${args.stage}`],
1895
+ ...args.only.map((name) => `--only ${name}`),
1896
+ "--yes",
1897
+ ...args.json ? ["--json"] : []
1898
+ ].join(" ");
1899
+ }
1900
+ function addRedactions(planned, secrets) {
1901
+ for (const item of planned) if (item.secret || item.value.length >= 4) secrets.push(item.value);
1902
+ }
1903
+ function sourceLabel(source) {
1904
+ return source === "process" ? "the shell" : source === "generated" ? "a generated value" : source === "console" ? "the Console" : source;
1905
+ }
1906
+ function writePush(output, context) {
1907
+ const lines = output.pushed.length ? [`Pushed to ${targetLabel(output)}:`, ...output.pushed.map((item) => ` ${item.name} from ${sourceLabel(item.source)}${item.encrypted ? ", decrypted" : ""}${item.replaced ? ", replaced" : ""}`)] : [`Nothing to push to ${targetLabel(output)}.`];
1908
+ if (output.skipped.length) lines.push(`No local value, so ${output.github ? "GitHub" : "the host"} keeps what it has:`, ...output.skipped.map((item) => ` ${entryLabel(item)}${item.required ? " (required)" : ""}`));
1909
+ context.stdout.write(`${lines.join("\n")}\n`);
1910
+ }
1911
+ async function runPush(args, context) {
1912
+ const target = await openTarget(args, "vitehub env push", context);
1913
+ const values = await readLocalEnvValues(target.project.root, target.envDir, target.stage, context.env);
1914
+ const { planned: stored, skipped } = planPush(target.entries, values, args.only, target.configVars);
1915
+ addRedactions(stored, target.secrets);
1916
+ const output = {
1917
+ ...destination(target),
1918
+ pushed: [],
1919
+ skipped
1920
+ };
1921
+ if (!stored.length) {
1922
+ if (args.json) writeSetupJson(context, output);
1923
+ else writePush(output, context);
1924
+ return setupExitCodes.done;
1925
+ }
1926
+ await assertUntracked(stored, target.project.root, target.run, context.env, context.stderr);
1927
+ const planned = await decryptPlanned(stored, target.project.root, context.env, target.secrets);
1928
+ if (!args.yes) {
1929
+ if (!(!args.json && !!process.stdin.isTTY && !!process.stderr.isTTY)) throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: `[vitehub] \`vitehub env push\` changes ${target.github ? "GitHub Actions secrets" : "host variables"} and was not confirmed. Without a terminal, pass --yes.` }), setupExitCodes.inputNeeded, { rerun: pushRerun(args) });
1930
+ if (!await confirmPush(planned, targetLabel(output))) throw setupFailure(cliErrorDiagnostics.CLI_R0004({ message: "[vitehub] The push was not confirmed. Nothing was pushed." }), setupExitCodes.error);
1931
+ }
1932
+ const remoteName = (name) => target.github ? name.toUpperCase() : name;
1933
+ const onHost = new Set((await target.hostEnv.listSecretNames()).map(remoteName));
1934
+ for (const item of planned) {
1935
+ await target.hostEnv.setSecret(item.name, item.value, { secret: item.secret });
1936
+ output.pushed.push({
1937
+ name: item.name,
1938
+ replaced: onHost.has(remoteName(item.name)),
1939
+ secret: item.secret,
1940
+ source: item.source,
1941
+ ...item.encrypted ? { encrypted: true } : {}
1942
+ });
1943
+ }
1944
+ if (args.json) writeSetupJson(context, output);
1945
+ else writePush(output, context);
1946
+ return setupExitCodes.done;
1947
+ }
1948
+ const appSecretName = "VITEHUB_SECRET";
1949
+ async function confirmGenerate(label) {
1950
+ const terminal = createInterface({
1951
+ input: process.stdin,
1952
+ output: process.stderr
1953
+ });
1954
+ try {
1955
+ return /^y(?:es)?$/iu.test((await terminal.question(`${appSecretName} is not set on ${label} and has no local value. Generate one and set it? [y/N] `)).trim());
1956
+ } finally {
1957
+ terminal.close();
1958
+ }
1959
+ }
1960
+ function entryNames(entries) {
1961
+ return [...new Set(entries.flatMap((entry) => [...entry.names, ...entry.prefix ? [`${entry.prefix}*`] : []]))];
1962
+ }
1963
+ async function keepGenerated(item, file, options) {
1964
+ const label = fileSource(options.root, file);
1965
+ await mkdir(dirname(file), { recursive: true });
1966
+ const directory = await realpath(dirname(file));
1967
+ const destination = join(directory, basename(file));
1968
+ if (inGitRepository(directory, options.context.env)) {
1969
+ const state = await gitFileState(destination, label, options.run, options.context.env);
1970
+ if (state === "tracked") throw setupFailure(cliErrorDiagnostics.SETUP_ENV_FILE_TRACKED({
1971
+ file: label,
1972
+ names: item.name
1973
+ }), setupExitCodes.conflict);
1974
+ if (state === "unignored") throw setupFailure(cliErrorDiagnostics.SETUP_ENV_FILE_NOT_IGNORED({
1975
+ file: label,
1976
+ names: item.name
1977
+ }), setupExitCodes.conflict);
1978
+ }
1979
+ const unsafe = () => setupFailure(cliErrorDiagnostics.SETUP_ENV_FILE_UNSAFE({
1980
+ file: label,
1981
+ names: item.name
1982
+ }), setupExitCodes.conflict);
1983
+ const existing = lstatSync(destination, { throwIfNoEntry: false });
1984
+ if (existing && (!existing.isFile() || existing.nlink !== 1)) throw unsafe();
1985
+ const flags = constants.O_RDWR | constants.O_APPEND | constants.O_CREAT;
1986
+ const noFollow = process.platform === "win32" ? 0 : constants.O_NOFOLLOW | constants.O_NONBLOCK;
1987
+ await using handle = await open(destination, flags | noFollow, 384);
1988
+ const opened = await handle.stat();
1989
+ const named = lstatSync(destination, { throwIfNoEntry: false });
1990
+ if (!opened.isFile() || opened.nlink !== 1 || !named?.isFile() || opened.dev !== named.dev || opened.ino !== named.ino) throw unsafe();
1991
+ await handle.chmod(384);
1992
+ const current = await handle.readFile("utf8");
1993
+ await handle.appendFile(`${current && !current.endsWith("\n") ? "\n" : ""}${dotenvLine$1(item.name, item.value)}\n`);
1994
+ return label;
1995
+ }
1996
+ const legacyVercelSandboxAliases = /* @__PURE__ */ new Set([
1997
+ "VERCEL_TOKEN",
1998
+ "VERCEL_TEAM_ID",
1999
+ "VERCEL_PROJECT_ID"
2000
+ ]);
2001
+ /**
2002
+ * The Env gate of `vitehub deploy`. It runs after provisioning and the build, before migrations, env writes, or publishing code. Each required entry must be on
2003
+ * the host or have a local value (the shell, then the stage env files, as `env push` reads them). Deploy sets every
2004
+ * entry that the host lacks and that has a local value; `--push-env` also replaces the names that the host has.
2005
+ * Cloudflare always re-supplies local stage values and requires a local value for every existing secret, so an
2006
+ * omitted secret cannot inherit from another stage. Other hosts use their env CLI before the deploy.
2007
+ */
2008
+ async function checkDeployEnv(options) {
2009
+ const { context, host, link } = options;
2010
+ const entries = host === "vercel" ? options.entries.flatMap((entry) => {
2011
+ if (!entry.owners?.includes("sandbox")) return [entry];
2012
+ const names = entry.names.filter((name) => !legacyVercelSandboxAliases.has(name));
2013
+ return names.length || entry.prefix ? [{
2014
+ ...entry,
2015
+ names
2016
+ }] : [];
2017
+ }) : options.entries;
2018
+ const stage = options.preview ? "preview" : defaultStage;
2019
+ const output = {
2020
+ checked: entryNames(entries),
2021
+ missing: [],
2022
+ pushed: [],
2023
+ stage
2024
+ };
2025
+ if (!entries.length) return {
2026
+ apply: async () => {},
2027
+ onHost: /* @__PURE__ */ new Set(),
2028
+ output,
2029
+ upload: {}
2030
+ };
2031
+ const target = options.preview && host !== "cloudflare" ? "preview" : "production";
2032
+ const hostContext = link ? {
2033
+ env: context.env,
2034
+ fetch: context.fetch ?? globalThis.fetch,
2035
+ link,
2036
+ root: options.root,
2037
+ run: options.run,
2038
+ secrets: options.secrets,
2039
+ target
2040
+ } : void 0;
2041
+ const hostEnv = hostContext && (host === "cloudflare" ? cloudflareEnv(hostContext, "deploy") : host === "vercel" ? vercelEnv(hostContext, options.pushEnv) : hostEnvs[host](hostContext));
2042
+ const uncheckedVercel = host === "vercel" && hostContext && !hostContext.link.project.id ? vercelProject(hostContext) : void 0;
2043
+ const newProject = uncheckedVercel && !await uncheckedVercel.exists() ? uncheckedVercel : void 0;
2044
+ const onHost = new Set(hostEnv && !newProject ? await hostEnv.listSecretNames() : []);
2045
+ const values = await readLocalEnvValues(options.root, options.envDir, stage, context.env);
2046
+ for (const [name, value] of Object.entries(host === "cloudflare" ? options.consoleKeys ?? {} : {})) if (onHost.has(name) && !values.has(name)) values.set(name, {
2047
+ encrypted: false,
2048
+ files: [],
2049
+ source: "console",
2050
+ value
2051
+ });
2052
+ const configVars = await configVarNames(host, options.outputDir);
2053
+ const stored = planPush(entries, values, [], options.pushEnv || host === "cloudflare" ? configVars : onHost).planned;
2054
+ if (host === "cloudflare") {
2055
+ for (const name of onHost) {
2056
+ const local = values.get(name);
2057
+ if (local && !stored.some((item) => item.name === name)) stored.push({
2058
+ name,
2059
+ secret: true,
2060
+ ...local
2061
+ });
2062
+ }
2063
+ const unavailable = [...onHost].filter((name) => !values.has(name));
2064
+ if (unavailable.length) throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_ENV_STAGE_UNSAFE({
2065
+ console: unavailable.some((name) => name.startsWith(consoleKeyPrefix)),
2066
+ names: unavailable.join(", "),
2067
+ stage
2068
+ }), setupExitCodes.inputNeeded);
2069
+ for (const item of stored) if (onHost.has(item.name)) item.secret = true;
2070
+ }
2071
+ const label = `${link?.project.name ?? "the new project"} on ${host}`;
2072
+ const unset = () => entries.filter((entry) => !isSet(entry, /* @__PURE__ */ new Set([
2073
+ ...onHost,
2074
+ ...configVars,
2075
+ ...stored.map((item) => item.name)
2076
+ ])));
2077
+ if (unset().find((entry) => isRequired(entry) && entry.names.includes(appSecretName)) && options.envDir !== false && (options.yes || options.interactive && await confirmGenerate(label))) {
2078
+ stored.push({
2079
+ encrypted: false,
2080
+ files: [],
2081
+ name: appSecretName,
2082
+ secret: true,
2083
+ source: "generated",
2084
+ value: randomBytes(32).toString("base64")
2085
+ });
2086
+ output.generated = [appSecretName];
2087
+ }
2088
+ addRedactions(stored, options.secrets);
2089
+ const missing = unset().filter((entry) => !options.deferConsoleKey || entry.prefix !== "VITEHUB_CONSOLE_KEY_");
2090
+ const required = missing.filter(isRequired);
2091
+ if (required.length) {
2092
+ const names = required.map((entry) => entryLabel(diffEntry(entry))).join(", ");
2093
+ throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_ENV_MISSING({
2094
+ console: required.some((entry) => entry.prefix === consoleKeyPrefix),
2095
+ firstDeploy: !link,
2096
+ host,
2097
+ names,
2098
+ stage
2099
+ }), setupExitCodes.inputNeeded, {
2100
+ data: { env: {
2101
+ ...output,
2102
+ missing: missing.map(diffEntry)
2103
+ } },
2104
+ missing: required.map((entry) => ({ field: entry.names[0] ?? `${entry.prefix}*` }))
2105
+ });
2106
+ }
2107
+ if (stored.length && !hostEnv && host !== "cloudflare") throw setupFailure(cliErrorDiagnostics.SETUP_DEPLOY_ENV_NOT_LINKED({
2108
+ host,
2109
+ names: stored.map((item) => item.name).join(", ")
2110
+ }), setupExitCodes.inputNeeded, { rerun: host === "deno" ? "vitehub link --host deno" : `vitehub link --host ${host} --create` });
2111
+ const generated = stored.find((item) => item.source === "generated");
2112
+ await assertUntracked(stored, options.root, options.run, context.env, context.stderr);
2113
+ const planned = await decryptPlanned(stored, options.root, context.env, options.secrets);
2114
+ const kept = generated && options.envDir !== false ? await keepGenerated(generated, join(options.envDir, `.env.${stage}.local`), options) : void 0;
2115
+ output.missing = missing.map(diffEntry);
2116
+ if (output.missing.length) context.stderr.write(`Warning: optional env not set on ${host}: ${output.missing.map(entryLabel).join(", ")}.\n`);
2117
+ const report = (items) => {
2118
+ output.pushed = items.map((item) => item.name);
2119
+ if (output.generated && !output.pushed.includes(appSecretName)) delete output.generated;
2120
+ for (const item of items) context.stderr.write(item.source === "generated" ? `Generated ${item.name}, saved it in ${kept}, and set it on ${host}.\n` : `Setting ${item.name} on ${host}${host === "cloudflare" ? " with the new version" : ""} from ${sourceLabel(item.source)}${item.encrypted ? ", decrypted" : ""}${onHost.has(item.name) ? ", replaced" : ""}.\n`);
2121
+ };
2122
+ if (!newProject) report(planned);
2123
+ const deployedNames = /* @__PURE__ */ new Set([
2124
+ ...onHost,
2125
+ ...configVars,
2126
+ ...planned.map((item) => item.name)
2127
+ ]);
2128
+ if (host === "cloudflare" || !hostEnv) return {
2129
+ apply: async () => {},
2130
+ onHost: deployedNames,
2131
+ output,
2132
+ upload: host === "cloudflare" ? Object.fromEntries(planned.map((item) => [item.name, item.value])) : {}
2133
+ };
2134
+ return {
2135
+ apply: async () => {
2136
+ let writes = planned;
2137
+ if (newProject && planned.length) {
2138
+ context.stderr.write(`Creating the ${newProject.name} project on ${host}, so deploy can set its variables.\n`);
2139
+ await newProject.create();
2140
+ for (const name of await hostEnv.listSecretNames()) {
2141
+ onHost.add(name);
2142
+ deployedNames.add(name);
2143
+ }
2144
+ if (!options.pushEnv) writes = planned.filter((item) => !onHost.has(item.name));
2145
+ report(writes);
2146
+ }
2147
+ for (const item of writes) await hostEnv.setSecret(item.name, item.value, { secret: item.secret });
2148
+ },
2149
+ onHost: deployedNames,
2150
+ output,
2151
+ upload: {}
2152
+ };
2153
+ }
2154
+ /** Runs `vitehub env diff` or `vitehub env push`. `feature` gives the usage and description for `--help`. */
2155
+ async function runEnvCommand(feature, args, context) {
2156
+ const json = args.includes("--json");
2157
+ const push = feature.name === "push";
2158
+ try {
2159
+ const parsed = readEnvArgs(args, push, feature.usage);
2160
+ if (parsed.help) {
2161
+ context.stdout.write(`Usage: ${feature.usage}\n\n${feature.description}\n`);
2162
+ return setupExitCodes.done;
2163
+ }
2164
+ return push ? await runPush(parsed, context) : await runDiff(parsed, context);
2165
+ } catch (error) {
2166
+ return writeSetupError(context, json, error);
2167
+ }
2168
+ }
2169
+ export { netlifyAdapter as a, listDenoDeployments as c, formatDeployConsole as d, linkDeployedApp as f, readBuildOutput as g, build as h, listNetlifyDeployments as i, cloudflareAdapter as l, readsConsoleKey as m, env_exports as n, denoAdapter as o, openDeployConsole as p, hostEnvs as r, denoOrganization as s, checkDeployEnv as t, listCloudflareDeployments as u };