@fkodelabs/vaultenv 0.0.0-stage → 0.1.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.
Files changed (3) hide show
  1. package/README.md +31 -2
  2. package/dist/index.js +2356 -0
  3. package/package.json +30 -4
package/dist/index.js ADDED
@@ -0,0 +1,2356 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import fs2 from "node:fs";
5
+ import os2 from "node:os";
6
+ import path2 from "node:path";
7
+ import { spawn } from "node:child_process";
8
+
9
+ // ../node_modules/@clack/core/dist/index.mjs
10
+ import { styleText } from "node:util";
11
+ import { stdout, stdin } from "node:process";
12
+ import * as f$1 from "node:readline";
13
+ import f__default from "node:readline";
14
+
15
+ // ../node_modules/fast-string-truncated-width/dist/utils.js
16
+ var getCodePointsLength = /* @__PURE__ */ (() => {
17
+ const SURROGATE_PAIR_RE = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
18
+ return (input) => {
19
+ let surrogatePairsNr = 0;
20
+ SURROGATE_PAIR_RE.lastIndex = 0;
21
+ while (SURROGATE_PAIR_RE.test(input)) {
22
+ surrogatePairsNr += 1;
23
+ }
24
+ return input.length - surrogatePairsNr;
25
+ };
26
+ })();
27
+ var isFullWidth = (x) => {
28
+ return x === 12288 || x >= 65281 && x <= 65376 || x >= 65504 && x <= 65510;
29
+ };
30
+ var isWideNotCJKTNotEmoji = (x) => {
31
+ return x === 8987 || x === 9001 || x >= 12272 && x <= 12287 || x >= 12289 && x <= 12350 || x >= 12441 && x <= 12543 || x >= 12549 && x <= 12591 || x >= 12593 && x <= 12686 || x >= 12688 && x <= 12771 || x >= 12783 && x <= 12830 || x >= 12832 && x <= 12871 || x >= 12880 && x <= 19903 || x >= 65040 && x <= 65049 || x >= 65072 && x <= 65106 || x >= 65108 && x <= 65126 || x >= 65128 && x <= 65131 || x >= 127488 && x <= 127490 || x >= 127504 && x <= 127547 || x >= 127552 && x <= 127560 || x >= 131072 && x <= 196605 || x >= 196608 && x <= 262141;
32
+ };
33
+
34
+ // ../node_modules/fast-string-truncated-width/dist/index.js
35
+ var ANSI_RE = /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y;
36
+ var CONTROL_RE = /[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y;
37
+ var CJKT_WIDE_RE = /(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu;
38
+ var TAB_RE = /\t{1,1000}/y;
39
+ var EMOJI_RE = new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*", "yu");
40
+ var LATIN_RE = /(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y;
41
+ var MODIFIER_RE = new RegExp("\\p{M}+", "gu");
42
+ var NO_TRUNCATION = { limit: Infinity, ellipsis: "" };
43
+ var getStringTruncatedWidth = (input, truncationOptions = {}, widthOptions = {}) => {
44
+ const LIMIT = truncationOptions.limit ?? Infinity;
45
+ const ELLIPSIS = truncationOptions.ellipsis ?? "";
46
+ const ELLIPSIS_WIDTH = truncationOptions?.ellipsisWidth ?? (ELLIPSIS ? getStringTruncatedWidth(ELLIPSIS, NO_TRUNCATION, widthOptions).width : 0);
47
+ const ANSI_WIDTH = 0;
48
+ const CONTROL_WIDTH = widthOptions.controlWidth ?? 0;
49
+ const TAB_WIDTH = widthOptions.tabWidth ?? 8;
50
+ const EMOJI_WIDTH = widthOptions.emojiWidth ?? 2;
51
+ const FULL_WIDTH_WIDTH = 2;
52
+ const REGULAR_WIDTH = widthOptions.regularWidth ?? 1;
53
+ const WIDE_WIDTH = widthOptions.wideWidth ?? FULL_WIDTH_WIDTH;
54
+ const PARSE_BLOCKS = [
55
+ [LATIN_RE, REGULAR_WIDTH],
56
+ [ANSI_RE, ANSI_WIDTH],
57
+ [CONTROL_RE, CONTROL_WIDTH],
58
+ [TAB_RE, TAB_WIDTH],
59
+ [EMOJI_RE, EMOJI_WIDTH],
60
+ [CJKT_WIDE_RE, WIDE_WIDTH]
61
+ ];
62
+ let indexPrev = 0;
63
+ let index = 0;
64
+ let length = input.length;
65
+ let lengthExtra = 0;
66
+ let truncationEnabled = false;
67
+ let truncationIndex = length;
68
+ let truncationLimit = Math.max(0, LIMIT - ELLIPSIS_WIDTH);
69
+ let unmatchedStart = 0;
70
+ let unmatchedEnd = 0;
71
+ let width = 0;
72
+ let widthExtra = 0;
73
+ outer: while (true) {
74
+ if (unmatchedEnd > unmatchedStart || index >= length && index > indexPrev) {
75
+ const unmatched = input.slice(unmatchedStart, unmatchedEnd) || input.slice(indexPrev, index);
76
+ lengthExtra = 0;
77
+ for (const char of unmatched.replaceAll(MODIFIER_RE, "")) {
78
+ const codePoint = char.codePointAt(0) || 0;
79
+ if (isFullWidth(codePoint)) {
80
+ widthExtra = FULL_WIDTH_WIDTH;
81
+ } else if (isWideNotCJKTNotEmoji(codePoint)) {
82
+ widthExtra = WIDE_WIDTH;
83
+ } else {
84
+ widthExtra = REGULAR_WIDTH;
85
+ }
86
+ if (width + widthExtra > truncationLimit) {
87
+ truncationIndex = Math.min(truncationIndex, Math.max(unmatchedStart, indexPrev) + lengthExtra);
88
+ }
89
+ if (width + widthExtra > LIMIT) {
90
+ truncationEnabled = true;
91
+ break outer;
92
+ }
93
+ lengthExtra += char.length;
94
+ width += widthExtra;
95
+ }
96
+ unmatchedStart = unmatchedEnd = 0;
97
+ }
98
+ if (index >= length) {
99
+ break outer;
100
+ }
101
+ for (let i2 = 0, l = PARSE_BLOCKS.length; i2 < l; i2++) {
102
+ const [BLOCK_RE, BLOCK_WIDTH] = PARSE_BLOCKS[i2];
103
+ BLOCK_RE.lastIndex = index;
104
+ if (BLOCK_RE.test(input)) {
105
+ lengthExtra = BLOCK_RE === CJKT_WIDE_RE ? getCodePointsLength(input.slice(index, BLOCK_RE.lastIndex)) : BLOCK_RE === EMOJI_RE ? 1 : BLOCK_RE.lastIndex - index;
106
+ widthExtra = lengthExtra * BLOCK_WIDTH;
107
+ if (width + widthExtra > truncationLimit) {
108
+ truncationIndex = Math.min(truncationIndex, index + Math.floor((truncationLimit - width) / BLOCK_WIDTH));
109
+ }
110
+ if (width + widthExtra > LIMIT) {
111
+ truncationEnabled = true;
112
+ break outer;
113
+ }
114
+ width += widthExtra;
115
+ unmatchedStart = indexPrev;
116
+ unmatchedEnd = index;
117
+ index = indexPrev = BLOCK_RE.lastIndex;
118
+ continue outer;
119
+ }
120
+ }
121
+ index += 1;
122
+ }
123
+ return {
124
+ width: truncationEnabled ? truncationLimit : width,
125
+ index: truncationEnabled ? truncationIndex : length,
126
+ truncated: truncationEnabled,
127
+ ellipsed: truncationEnabled && LIMIT >= ELLIPSIS_WIDTH
128
+ };
129
+ };
130
+ var dist_default = getStringTruncatedWidth;
131
+
132
+ // ../node_modules/fast-string-width/dist/index.js
133
+ var NO_TRUNCATION2 = {
134
+ limit: Infinity,
135
+ ellipsis: "",
136
+ ellipsisWidth: 0
137
+ };
138
+ var fastStringWidth = (input, options = {}) => {
139
+ return dist_default(input, NO_TRUNCATION2, options).width;
140
+ };
141
+ var dist_default2 = fastStringWidth;
142
+
143
+ // ../node_modules/fast-wrap-ansi/lib/main.js
144
+ var ESC = "\x1B";
145
+ var CSI = "\x9B";
146
+ var END_CODE = 39;
147
+ var ANSI_ESCAPE_BELL = "\x07";
148
+ var ANSI_CSI = "[";
149
+ var ANSI_OSC = "]";
150
+ var ANSI_SGR_TERMINATOR = "m";
151
+ var ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;
152
+ var GROUP_REGEX = new RegExp(`(?:\\${ANSI_CSI}(?<code>\\d+)m|\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`, "y");
153
+ var getClosingCode = (openingCode) => {
154
+ if (openingCode >= 30 && openingCode <= 37)
155
+ return 39;
156
+ if (openingCode >= 90 && openingCode <= 97)
157
+ return 39;
158
+ if (openingCode >= 40 && openingCode <= 47)
159
+ return 49;
160
+ if (openingCode >= 100 && openingCode <= 107)
161
+ return 49;
162
+ if (openingCode === 1 || openingCode === 2)
163
+ return 22;
164
+ if (openingCode === 3)
165
+ return 23;
166
+ if (openingCode === 4)
167
+ return 24;
168
+ if (openingCode === 7)
169
+ return 27;
170
+ if (openingCode === 8)
171
+ return 28;
172
+ if (openingCode === 9)
173
+ return 29;
174
+ if (openingCode === 0)
175
+ return 0;
176
+ return void 0;
177
+ };
178
+ var wrapAnsiCode = (code) => `${ESC}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;
179
+ var wrapAnsiHyperlink = (url) => `${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`;
180
+ var wrapWord = (rows, word, columns) => {
181
+ const characters = word[Symbol.iterator]();
182
+ let isInsideEscape = false;
183
+ let isInsideLinkEscape = false;
184
+ let lastRow = rows.at(-1);
185
+ let visible = lastRow === void 0 ? 0 : dist_default2(lastRow);
186
+ let currentCharacter = characters.next();
187
+ let nextCharacter = characters.next();
188
+ let rawCharacterIndex = 0;
189
+ while (!currentCharacter.done) {
190
+ const character = currentCharacter.value;
191
+ const characterLength = dist_default2(character);
192
+ if (visible + characterLength <= columns) {
193
+ rows[rows.length - 1] += character;
194
+ } else {
195
+ rows.push(character);
196
+ visible = 0;
197
+ }
198
+ if (character === ESC || character === CSI) {
199
+ isInsideEscape = true;
200
+ isInsideLinkEscape = word.startsWith(ANSI_ESCAPE_LINK, rawCharacterIndex + 1);
201
+ }
202
+ if (isInsideEscape) {
203
+ if (isInsideLinkEscape) {
204
+ if (character === ANSI_ESCAPE_BELL) {
205
+ isInsideEscape = false;
206
+ isInsideLinkEscape = false;
207
+ }
208
+ } else if (character === ANSI_SGR_TERMINATOR) {
209
+ isInsideEscape = false;
210
+ }
211
+ } else {
212
+ visible += characterLength;
213
+ if (visible === columns && !nextCharacter.done) {
214
+ rows.push("");
215
+ visible = 0;
216
+ }
217
+ }
218
+ currentCharacter = nextCharacter;
219
+ nextCharacter = characters.next();
220
+ rawCharacterIndex += character.length;
221
+ }
222
+ lastRow = rows.at(-1);
223
+ if (!visible && lastRow !== void 0 && lastRow.length && rows.length > 1) {
224
+ rows[rows.length - 2] += rows.pop();
225
+ }
226
+ };
227
+ var stringVisibleTrimSpacesRight = (string) => {
228
+ const words = string.split(" ");
229
+ let last = words.length;
230
+ while (last) {
231
+ if (dist_default2(words[last - 1])) {
232
+ break;
233
+ }
234
+ last--;
235
+ }
236
+ if (last === words.length) {
237
+ return string;
238
+ }
239
+ return words.slice(0, last).join(" ") + words.slice(last).join("");
240
+ };
241
+ var exec = (string, columns, options = {}) => {
242
+ if (options.trim !== false && string.trim() === "") {
243
+ return "";
244
+ }
245
+ let returnValue = "";
246
+ let escapeCode;
247
+ let escapeUrl;
248
+ const words = string.split(" ");
249
+ let rows = [""];
250
+ let rowLength = 0;
251
+ for (let index = 0; index < words.length; index++) {
252
+ const word = words[index];
253
+ if (options.trim !== false) {
254
+ const row = rows.at(-1) ?? "";
255
+ const trimmed = row.trimStart();
256
+ if (row.length !== trimmed.length) {
257
+ rows[rows.length - 1] = trimmed;
258
+ rowLength = dist_default2(trimmed);
259
+ }
260
+ }
261
+ if (index !== 0) {
262
+ if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
263
+ rows.push("");
264
+ rowLength = 0;
265
+ }
266
+ if (rowLength || options.trim === false) {
267
+ rows[rows.length - 1] += " ";
268
+ rowLength++;
269
+ }
270
+ }
271
+ const wordLength = dist_default2(word);
272
+ if (options.hard && wordLength > columns) {
273
+ const remainingColumns = columns - rowLength;
274
+ const breaksStartingThisLine = 1 + Math.floor((wordLength - remainingColumns - 1) / columns);
275
+ const breaksStartingNextLine = Math.floor((wordLength - 1) / columns);
276
+ if (breaksStartingNextLine < breaksStartingThisLine) {
277
+ rows.push("");
278
+ }
279
+ wrapWord(rows, word, columns);
280
+ rowLength = dist_default2(rows.at(-1) ?? "");
281
+ continue;
282
+ }
283
+ if (rowLength + wordLength > columns && rowLength && wordLength) {
284
+ if (options.wordWrap === false && rowLength < columns) {
285
+ wrapWord(rows, word, columns);
286
+ rowLength = dist_default2(rows.at(-1) ?? "");
287
+ continue;
288
+ }
289
+ rows.push("");
290
+ rowLength = 0;
291
+ }
292
+ if (rowLength + wordLength > columns && options.wordWrap === false) {
293
+ wrapWord(rows, word, columns);
294
+ rowLength = dist_default2(rows.at(-1) ?? "");
295
+ continue;
296
+ }
297
+ rows[rows.length - 1] += word;
298
+ rowLength += wordLength;
299
+ }
300
+ if (options.trim !== false) {
301
+ rows = rows.map((row) => stringVisibleTrimSpacesRight(row));
302
+ }
303
+ const preString = rows.join("\n");
304
+ let inSurrogate = false;
305
+ for (let i2 = 0; i2 < preString.length; i2++) {
306
+ const character = preString[i2];
307
+ returnValue += character;
308
+ if (!inSurrogate) {
309
+ inSurrogate = character >= "\uD800" && character <= "\uDBFF";
310
+ if (inSurrogate) {
311
+ continue;
312
+ }
313
+ } else {
314
+ inSurrogate = false;
315
+ }
316
+ if (character === ESC || character === CSI) {
317
+ GROUP_REGEX.lastIndex = i2 + 1;
318
+ const groupsResult = GROUP_REGEX.exec(preString);
319
+ const groups = groupsResult?.groups;
320
+ if (groups?.code !== void 0) {
321
+ const code = Number.parseFloat(groups.code);
322
+ escapeCode = code === END_CODE ? void 0 : code;
323
+ } else if (groups?.uri !== void 0) {
324
+ escapeUrl = groups.uri.length === 0 ? void 0 : groups.uri;
325
+ }
326
+ }
327
+ if (preString[i2 + 1] === "\n") {
328
+ if (escapeUrl) {
329
+ returnValue += wrapAnsiHyperlink("");
330
+ }
331
+ const closingCode = escapeCode ? getClosingCode(escapeCode) : void 0;
332
+ if (escapeCode && closingCode) {
333
+ returnValue += wrapAnsiCode(closingCode);
334
+ }
335
+ } else if (character === "\n") {
336
+ if (escapeCode && getClosingCode(escapeCode)) {
337
+ returnValue += wrapAnsiCode(escapeCode);
338
+ }
339
+ if (escapeUrl) {
340
+ returnValue += wrapAnsiHyperlink(escapeUrl);
341
+ }
342
+ }
343
+ }
344
+ return returnValue;
345
+ };
346
+ var CRLF_OR_LF = /\r?\n/;
347
+ function wrapAnsi(string, columns, options) {
348
+ return String(string).normalize().split(CRLF_OR_LF).map((line) => exec(line, columns, options)).join("\n");
349
+ }
350
+
351
+ // ../node_modules/sisteransi/dist/index.js
352
+ var ESC2 = "\x1B";
353
+ var CSI2 = `${ESC2}[`;
354
+ var cursor = {
355
+ to(x, y) {
356
+ if (!y)
357
+ return `${CSI2}${x + 1}G`;
358
+ return `${CSI2}${y + 1};${x + 1}H`;
359
+ },
360
+ move(x, y) {
361
+ let ret = "";
362
+ if (x < 0)
363
+ ret += `${CSI2}${-x}D`;
364
+ else if (x > 0)
365
+ ret += `${CSI2}${x}C`;
366
+ if (y < 0)
367
+ ret += `${CSI2}${-y}A`;
368
+ else if (y > 0)
369
+ ret += `${CSI2}${y}B`;
370
+ return ret;
371
+ },
372
+ up: (count = 1) => `${CSI2}${count}A`,
373
+ down: (count = 1) => `${CSI2}${count}B`,
374
+ forward: (count = 1) => `${CSI2}${count}C`,
375
+ backward: (count = 1) => `${CSI2}${count}D`,
376
+ nextLine: (count = 1) => `${CSI2}E`.repeat(count),
377
+ prevLine: (count = 1) => `${CSI2}F`.repeat(count),
378
+ left: `${CSI2}G`,
379
+ hide: `${CSI2}?25l`,
380
+ show: `${CSI2}?25h`,
381
+ save: `${ESC2}7`,
382
+ restore: `${ESC2}8`
383
+ };
384
+ var erase = {
385
+ screen: `${CSI2}2J`,
386
+ up: (count = 1) => `${CSI2}1J`.repeat(count),
387
+ down: (count = 1) => `${CSI2}J`.repeat(count),
388
+ line: `${CSI2}2K`,
389
+ lineEnd: `${CSI2}K`,
390
+ lineStart: `${CSI2}1K`,
391
+ lines(count) {
392
+ let clear2 = "";
393
+ for (let i2 = 0; i2 < count; i2++)
394
+ clear2 += this.line + (i2 < count - 1 ? cursor.up() : "");
395
+ if (count)
396
+ clear2 += cursor.left;
397
+ return clear2;
398
+ }
399
+ };
400
+ var clear = {
401
+ screen: `${ESC2}c`
402
+ };
403
+
404
+ // ../node_modules/@clack/core/dist/index.mjs
405
+ import { ReadStream } from "node:tty";
406
+ function findCursor(o, s, l) {
407
+ if (!l.some((r2) => !r2.disabled))
408
+ return o;
409
+ const t2 = o + s, n3 = Math.max(l.length - 1, 0), e = t2 < 0 ? n3 : t2 > n3 ? 0 : t2;
410
+ return l[e]?.disabled ? findCursor(e, s < 0 ? -1 : 1, l) : e;
411
+ }
412
+ var a$1 = ["up", "down", "left", "right", "space", "enter", "cancel"];
413
+ var t = [
414
+ "January",
415
+ "February",
416
+ "March",
417
+ "April",
418
+ "May",
419
+ "June",
420
+ "July",
421
+ "August",
422
+ "September",
423
+ "October",
424
+ "November",
425
+ "December"
426
+ ];
427
+ var settings = {
428
+ actions: new Set(a$1),
429
+ aliases: /* @__PURE__ */ new Map([
430
+ // vim support
431
+ ["k", "up"],
432
+ ["j", "down"],
433
+ ["h", "left"],
434
+ ["l", "right"],
435
+ ["", "cancel"],
436
+ // opinionated defaults!
437
+ ["escape", "cancel"]
438
+ ]),
439
+ messages: {
440
+ cancel: "Canceled",
441
+ error: "Something went wrong"
442
+ },
443
+ withGuide: true,
444
+ accessible: void 0,
445
+ date: {
446
+ monthNames: [...t],
447
+ messages: {
448
+ required: "Please enter a valid date",
449
+ invalidMonth: "There are only 12 months in a year",
450
+ invalidDay: (n3, e) => `There are only ${n3} days in ${e}`,
451
+ afterMin: (n3) => `Date must be on or after ${n3.toISOString().slice(0, 10)}`,
452
+ beforeMax: (n3) => `Date must be on or before ${n3.toISOString().slice(0, 10)}`
453
+ }
454
+ }
455
+ };
456
+ function isAccessible(n3) {
457
+ if (n3 !== void 0) return n3;
458
+ if (settings.accessible !== void 0) return settings.accessible;
459
+ const e = process.env.ACCESSIBLE;
460
+ return e !== void 0 && e !== "" && e !== "0" && e !== "false";
461
+ }
462
+ function isActionKey(n3, e) {
463
+ if (typeof n3 == "string")
464
+ return settings.aliases.get(n3) === e;
465
+ for (const s of n3)
466
+ if (s !== void 0 && isActionKey(s, e))
467
+ return true;
468
+ return false;
469
+ }
470
+ function diffLines(i2, s) {
471
+ if (i2 === s) return;
472
+ const e = i2.split(`
473
+ `), t2 = s.split(`
474
+ `), r2 = Math.max(e.length, t2.length), f = [];
475
+ for (let n3 = 0; n3 < r2; n3++)
476
+ e[n3] !== t2[n3] && f.push(n3);
477
+ return {
478
+ lines: f,
479
+ numLinesBefore: e.length,
480
+ numLinesAfter: t2.length,
481
+ numLines: r2
482
+ };
483
+ }
484
+ var R = globalThis.process.platform.startsWith("win");
485
+ var CANCEL_SYMBOL = /* @__PURE__ */ Symbol("clack:cancel");
486
+ function isCancel(e) {
487
+ return e === CANCEL_SYMBOL;
488
+ }
489
+ function setRawMode(e, r2) {
490
+ const o = e;
491
+ o.isTTY && o.setRawMode(r2);
492
+ }
493
+ function block({
494
+ input: e = stdin,
495
+ output: r2 = stdout,
496
+ overwrite: o = true,
497
+ hideCursor: n3 = true
498
+ } = {}) {
499
+ const s = f$1.createInterface({
500
+ input: e,
501
+ output: r2,
502
+ prompt: "",
503
+ tabSize: 1
504
+ });
505
+ f$1.emitKeypressEvents(e, s), e instanceof ReadStream && e.isTTY && e.setRawMode(true);
506
+ const t2 = (l, { name: i2, sequence: p }) => {
507
+ const w = String(l);
508
+ if (isActionKey([w, i2, p], "cancel")) {
509
+ n3 && r2.write(cursor.show), process.exit(0);
510
+ return;
511
+ }
512
+ if (!o) return;
513
+ const c3 = i2 === "return" ? 0 : -1, a2 = i2 === "return" ? -1 : 0;
514
+ f$1.moveCursor(r2, c3, a2, () => {
515
+ f$1.clearLine(r2, 1, () => {
516
+ e.once("keypress", t2);
517
+ });
518
+ });
519
+ };
520
+ return n3 && r2.write(cursor.hide), e.once("keypress", t2), () => {
521
+ e.off("keypress", t2), n3 && r2.write(cursor.show), e instanceof ReadStream && e.isTTY && !R && e.setRawMode(false), s.terminal = false, s.close();
522
+ };
523
+ }
524
+ var getColumns = (e) => "columns" in e && typeof e.columns == "number" ? e.columns : 80;
525
+ var getRows = (e) => "rows" in e && typeof e.rows == "number" ? e.rows : 20;
526
+ function wrapTextWithPrefix(e, r2, o, n3 = o, s = o, t2) {
527
+ const l = getColumns(e ?? stdout), i2 = dist_default2(o);
528
+ return wrapAnsi(r2, l - i2, {
529
+ hard: true,
530
+ trim: false
531
+ }).split(`
532
+ `).map((c3, a2, g) => {
533
+ const m = t2 ? t2(c3, a2) : c3;
534
+ return a2 === 0 ? `${n3}${m}` : a2 === g.length - 1 ? `${s}${m}` : `${o}${m}`;
535
+ }).join(`
536
+ `);
537
+ }
538
+ function runValidation(e, a2) {
539
+ if ("~standard" in e) {
540
+ const n3 = e["~standard"].validate(a2);
541
+ return n3 instanceof Promise ? n3.then((r2) => r2.issues?.at(0)?.message) : n3.issues?.at(0)?.message;
542
+ }
543
+ return e(a2);
544
+ }
545
+ var C$1 = class C {
546
+ input;
547
+ output;
548
+ _abortSignal;
549
+ rl;
550
+ opts;
551
+ _render;
552
+ _track = false;
553
+ _prevFrame = "";
554
+ _subscribers = /* @__PURE__ */ new Map();
555
+ _cursor = 0;
556
+ state = "initial";
557
+ error = "";
558
+ value;
559
+ userInput = "";
560
+ /**
561
+ * Whether accessible (static, screen-reader friendly) output is enabled for
562
+ * this prompt, resolved from the `accessible` option, the global setting,
563
+ * and the `ACCESSIBLE` env var.
564
+ */
565
+ get accessible() {
566
+ return isAccessible(this.opts.accessible);
567
+ }
568
+ constructor(t2, e = true) {
569
+ const { input: i2 = stdin, output: s = stdout, render: r2, signal: n3, ...o } = t2;
570
+ this.opts = o, this.onKeypress = this.onKeypress.bind(this), this.close = this.close.bind(this), this.render = this.render.bind(this), this._render = r2.bind(this), this._track = e, this._abortSignal = n3, this.input = i2, this.output = s;
571
+ }
572
+ /**
573
+ * Unsubscribe all listeners
574
+ */
575
+ unsubscribe() {
576
+ this._subscribers.clear();
577
+ }
578
+ /**
579
+ * Set a subscriber with opts
580
+ * @param event - The event name
581
+ */
582
+ setSubscriber(t2, e) {
583
+ const i2 = this._subscribers.get(t2) ?? [];
584
+ i2.push(e), this._subscribers.set(t2, i2);
585
+ }
586
+ /**
587
+ * Subscribe to an event
588
+ * @param event - The event name
589
+ * @param cb - The callback
590
+ */
591
+ on(t2, e) {
592
+ this.setSubscriber(t2, { cb: e });
593
+ }
594
+ /**
595
+ * Subscribe to an event once
596
+ * @param event - The event name
597
+ * @param cb - The callback
598
+ */
599
+ once(t2, e) {
600
+ this.setSubscriber(t2, { cb: e, once: true });
601
+ }
602
+ /**
603
+ * Emit an event with data
604
+ * @param event - The event name
605
+ * @param data - The data to pass to the callback
606
+ */
607
+ emit(t2, ...e) {
608
+ const i2 = this._subscribers.get(t2) ?? [], s = [];
609
+ for (const r2 of i2)
610
+ r2.cb(...e), r2.once && s.push(() => i2.splice(i2.indexOf(r2), 1));
611
+ for (const r2 of s)
612
+ r2();
613
+ }
614
+ prompt() {
615
+ return new Promise((t2) => {
616
+ if (this._abortSignal) {
617
+ if (this._abortSignal.aborted)
618
+ return this.state = "cancel", this.close(), t2(CANCEL_SYMBOL);
619
+ this._abortSignal.addEventListener(
620
+ "abort",
621
+ () => {
622
+ this.state = "cancel", this.close();
623
+ },
624
+ { once: true }
625
+ );
626
+ }
627
+ this.rl = f__default.createInterface({
628
+ input: this.input,
629
+ tabSize: 2,
630
+ prompt: "",
631
+ escapeCodeTimeout: 50,
632
+ terminal: true
633
+ }), this.rl.prompt(), this.opts.initialUserInput !== void 0 && this._setUserInput(this.opts.initialUserInput, true), this.input.on("keypress", this.onKeypress), setRawMode(this.input, true), this.output.on("resize", this.render), this.render(), this.once("submit", () => {
634
+ this.output.write(cursor.show), this.output.off("resize", this.render), setRawMode(this.input, false), t2(this.value);
635
+ }), this.once("cancel", () => {
636
+ this.output.write(cursor.show), this.output.off("resize", this.render), setRawMode(this.input, false), t2(CANCEL_SYMBOL);
637
+ });
638
+ });
639
+ }
640
+ _isActionKey(t2, e) {
641
+ return t2 === " ";
642
+ }
643
+ _shouldSubmit(t2, e) {
644
+ return true;
645
+ }
646
+ _setValue(t2) {
647
+ this.value = t2, this.emit("value", this.value);
648
+ }
649
+ _setUserInput(t2, e) {
650
+ this.userInput = t2 ?? "", this.emit("userInput", this.userInput), e && this._track && this.rl && (this.rl.write(this.userInput), this._cursor = this.rl.cursor);
651
+ }
652
+ _clearUserInput() {
653
+ this.rl?.write(null, { ctrl: true, name: "u" }), this._setUserInput("");
654
+ }
655
+ async onKeypress(t2, e) {
656
+ if (this.state !== "validating") {
657
+ if (this._track && e.name !== "return" && (e.name && this._isActionKey(t2, e) && this.rl?.write(null, { ctrl: true, name: "h" }), this._cursor = this.rl?.cursor ?? 0, this._setUserInput(this.rl?.line)), this.state === "error" && (this.state = "active"), e?.name && (!this._track && settings.aliases.has(e.name) && this.emit("cursor", settings.aliases.get(e.name)), settings.actions.has(e.name) && this.emit("cursor", e.name)), t2 && (t2.toLowerCase() === "y" || t2.toLowerCase() === "n") && this.emit("confirm", t2.toLowerCase() === "y"), this.emit("key", t2, e), e?.name === "return" && this._shouldSubmit(t2, e)) {
658
+ if (this.opts.validate) {
659
+ const i2 = runValidation(this.opts.validate, this.value);
660
+ let s;
661
+ i2 instanceof Promise ? (this.state = "validating", this.render(), s = await i2) : s = i2, s && (this.error = s instanceof Error ? s.message : s, this.state = "error", this.rl?.write(this.userInput));
662
+ }
663
+ this.state !== "error" && (this.state = "submit");
664
+ }
665
+ isActionKey([t2, e?.name, e?.sequence], "cancel") && (this.state = "cancel"), (this.state === "submit" || this.state === "cancel") && this.emit("finalize"), this.render(), (this.state === "submit" || this.state === "cancel") && this.close();
666
+ }
667
+ }
668
+ close() {
669
+ this.input.unpipe(), this.input.removeListener("keypress", this.onKeypress), this.output.write(`
670
+ `), setRawMode(this.input, false), this.rl?.close(), this.rl = void 0, this.emit(`${this.state}`, this.value), this.unsubscribe();
671
+ }
672
+ restoreCursor() {
673
+ const t2 = wrapAnsi(this._prevFrame, getColumns(this.output), { hard: true, trim: false }).split(`
674
+ `).length - 1;
675
+ this.output.write(cursor.move(-999, t2 * -1));
676
+ }
677
+ render() {
678
+ const t2 = wrapAnsi(this._render(this) ?? "", getColumns(this.output), {
679
+ hard: true,
680
+ trim: false
681
+ });
682
+ if (t2 !== this._prevFrame) {
683
+ if (this.state === "initial")
684
+ this.output.write(cursor.hide);
685
+ else {
686
+ const e = diffLines(this._prevFrame, t2), i2 = getRows(this.output);
687
+ if (this.restoreCursor(), e) {
688
+ const s = Math.max(0, e.numLinesAfter - i2), r2 = Math.max(0, e.numLinesBefore - i2);
689
+ let n3 = e.lines.find((o) => o >= s);
690
+ if (n3 === void 0) {
691
+ this._prevFrame = t2;
692
+ return;
693
+ }
694
+ if (e.lines.length === 1) {
695
+ this.output.write(cursor.move(0, n3 - r2)), this.output.write(erase.lines(1));
696
+ const o = t2.split(`
697
+ `);
698
+ this.output.write(o[n3]), this._prevFrame = t2, this.output.write(cursor.move(0, o.length - n3 - 1));
699
+ return;
700
+ } else if (e.lines.length > 1) {
701
+ if (s < r2)
702
+ n3 = s;
703
+ else {
704
+ const h2 = n3 - r2;
705
+ h2 > 0 && this.output.write(cursor.move(0, h2));
706
+ }
707
+ this.output.write(erase.down());
708
+ const m = t2.split(`
709
+ `).slice(n3);
710
+ this.output.write(m.join(`
711
+ `)), this._prevFrame = t2;
712
+ return;
713
+ }
714
+ }
715
+ this.output.write(erase.down());
716
+ }
717
+ this.output.write(t2), this.state === "initial" && (this.state = "active"), this._prevFrame = t2;
718
+ }
719
+ }
720
+ };
721
+ var r = class extends C$1 {
722
+ get cursor() {
723
+ return this.value ? 0 : 1;
724
+ }
725
+ get _value() {
726
+ return this.cursor === 0;
727
+ }
728
+ constructor(t2) {
729
+ super(t2, false), this.value = !!t2.initialValue, this.on("userInput", () => {
730
+ this.value = this._value;
731
+ }), this.on("confirm", (i2) => {
732
+ this.output.write(cursor.move(0, -1)), this.value = i2, this.state = "submit", this.close();
733
+ }), this.on("cursor", () => {
734
+ this.value = !this.value;
735
+ });
736
+ }
737
+ };
738
+ var u = class extends C$1 {
739
+ _mask = "\u2022";
740
+ get cursor() {
741
+ return this._cursor;
742
+ }
743
+ get masked() {
744
+ return this.userInput.replaceAll(/./g, this._mask);
745
+ }
746
+ get userInputWithCursor() {
747
+ if (this.state === "submit" || this.state === "cancel")
748
+ return this.masked;
749
+ const t2 = this.userInput;
750
+ if (this.cursor >= t2.length)
751
+ return `${this.masked}${styleText(["inverse", "hidden"], "_")}`;
752
+ const s = this.masked, r2 = s.slice(0, this.cursor), i2 = s.slice(this.cursor, this.cursor + 1), o = s.slice(this.cursor + 1);
753
+ return `${r2}${styleText("inverse", i2)}${o}`;
754
+ }
755
+ clear() {
756
+ this._clearUserInput();
757
+ }
758
+ constructor({ mask: t2, ...s }) {
759
+ super(s), this._mask = t2 ?? "\u2022", this.on("userInput", (r2) => {
760
+ this._setValue(r2);
761
+ }), this.on("finalize", () => {
762
+ this.value === void 0 && (this.value = "");
763
+ });
764
+ }
765
+ };
766
+ var n$1 = class n extends C$1 {
767
+ options;
768
+ cursor = 0;
769
+ get _selectedValue() {
770
+ return this.options[this.cursor];
771
+ }
772
+ changeValue() {
773
+ const e = this._selectedValue;
774
+ this.value = e === void 0 ? void 0 : e.value;
775
+ }
776
+ constructor(e) {
777
+ super(e, false), this.options = e.options;
778
+ const o = this.options.findIndex(({ value: s }) => s === e.initialValue), t2 = o === -1 ? 0 : o;
779
+ this.cursor = this.options[t2]?.disabled ? findCursor(t2, 1, this.options) : t2, this.changeValue(), this.on("cursor", (s) => {
780
+ switch (s) {
781
+ case "left":
782
+ case "up":
783
+ this.cursor = findCursor(this.cursor, -1, this.options);
784
+ break;
785
+ case "down":
786
+ case "right":
787
+ this.cursor = findCursor(this.cursor, 1, this.options);
788
+ break;
789
+ }
790
+ this.changeValue();
791
+ });
792
+ }
793
+ };
794
+ var n2 = class extends C$1 {
795
+ get userInputWithCursor() {
796
+ if (this.state === "submit")
797
+ return this.userInput;
798
+ const t2 = this.userInput;
799
+ if (this.cursor >= t2.length)
800
+ return `${this.userInput}\u2588`;
801
+ const r2 = t2.slice(0, this.cursor), s = t2.slice(this.cursor, this.cursor + 1), e = t2.slice(this.cursor + 1);
802
+ return `${r2}${styleText("inverse", s)}${e}`;
803
+ }
804
+ get cursor() {
805
+ return this._cursor;
806
+ }
807
+ constructor(t2) {
808
+ super({
809
+ ...t2,
810
+ initialUserInput: t2.initialUserInput ?? t2.initialValue
811
+ }), this.on("userInput", (r2) => {
812
+ this._setValue(r2);
813
+ }), this.on("finalize", () => {
814
+ this.value || (this.value = t2.defaultValue), this.value === void 0 && (this.value = "");
815
+ });
816
+ }
817
+ };
818
+
819
+ // ../node_modules/@clack/prompts/dist/index.mjs
820
+ import { styleText as styleText2, stripVTControlCharacters } from "node:util";
821
+ import process$1 from "node:process";
822
+ function isUnicodeSupported() {
823
+ if (process$1.platform !== "win32") {
824
+ return process$1.env.TERM !== "linux";
825
+ }
826
+ return Boolean(process$1.env.CI) || Boolean(process$1.env.WT_SESSION) || Boolean(process$1.env.TERMINUS_SUBLIME) || process$1.env.ConEmuTask === "{cmd::Cmder}" || process$1.env.TERM_PROGRAM === "Terminus-Sublime" || process$1.env.TERM_PROGRAM === "vscode" || process$1.env.TERM === "xterm-256color" || process$1.env.TERM === "alacritty" || process$1.env.TERMINAL_EMULATOR === "JetBrains-JediTerm";
827
+ }
828
+ var unicode = isUnicodeSupported();
829
+ var isCI = () => process.env.CI === "true";
830
+ var unicodeOr = (e, o) => unicode ? e : o;
831
+ var S_STEP_ACTIVE = unicodeOr("\u25C6", "*");
832
+ var S_STEP_CANCEL = unicodeOr("\u25A0", "x");
833
+ var S_STEP_ERROR = unicodeOr("\u25B2", "x");
834
+ var S_STEP_SUBMIT = unicodeOr("\u25C7", "o");
835
+ var S_BAR_START = unicodeOr("\u250C", "T");
836
+ var S_BAR = unicodeOr("\u2502", "|");
837
+ var S_BAR_END = unicodeOr("\u2514", "\u2014");
838
+ var S_BAR_START_RIGHT = unicodeOr("\u2510", "T");
839
+ var S_BAR_END_RIGHT = unicodeOr("\u2518", "\u2014");
840
+ var S_RADIO_ACTIVE = unicodeOr("\u25CF", ">");
841
+ var S_RADIO_INACTIVE = unicodeOr("\u25CB", " ");
842
+ var S_CHECKBOX_ACTIVE = unicodeOr("\u25FB", "[\u2022]");
843
+ var S_CHECKBOX_SELECTED = unicodeOr("\u25FC", "[+]");
844
+ var S_CHECKBOX_INACTIVE = unicodeOr("\u25FB", "[ ]");
845
+ var S_PASSWORD_MASK = unicodeOr("\u25AA", "\u2022");
846
+ var S_BAR_H = unicodeOr("\u2500", "-");
847
+ var S_CORNER_TOP_RIGHT = unicodeOr("\u256E", "+");
848
+ var S_CONNECT_LEFT = unicodeOr("\u251C", "+");
849
+ var S_CORNER_BOTTOM_RIGHT = unicodeOr("\u256F", "+");
850
+ var S_CORNER_BOTTOM_LEFT = unicodeOr("\u2570", "+");
851
+ var S_CORNER_TOP_LEFT = unicodeOr("\u256D", "+");
852
+ var S_INFO = unicodeOr("\u25CF", "\u2022");
853
+ var S_SUCCESS = unicodeOr("\u25C6", "*");
854
+ var S_WARN = unicodeOr("\u25B2", "!");
855
+ var S_ERROR = unicodeOr("\u25A0", "x");
856
+ var symbol = (e) => {
857
+ switch (e) {
858
+ case "initial":
859
+ case "active":
860
+ return styleText2("cyan", S_STEP_ACTIVE);
861
+ case "cancel":
862
+ return styleText2("red", S_STEP_CANCEL);
863
+ case "error":
864
+ return styleText2("yellow", S_STEP_ERROR);
865
+ case "submit":
866
+ return styleText2("green", S_STEP_SUBMIT);
867
+ case "validating":
868
+ return styleText2("dim", S_STEP_ACTIVE);
869
+ }
870
+ };
871
+ var symbolBar = (e) => {
872
+ switch (e) {
873
+ case "initial":
874
+ case "active":
875
+ return styleText2("cyan", S_BAR);
876
+ case "cancel":
877
+ return styleText2("red", S_BAR);
878
+ case "error":
879
+ return styleText2("yellow", S_BAR);
880
+ case "submit":
881
+ return styleText2("green", S_BAR);
882
+ }
883
+ };
884
+ function formatInstructionFooter(e, o, r2) {
885
+ const s = r2 ? `${styleText2("cyan", S_BAR)} ` : "", n3 = wrapTextWithPrefix(e, o.join(" \u2022 "), s).split(`
886
+ `);
887
+ return r2 && n3.push(styleText2("cyan", S_BAR_END)), n3;
888
+ }
889
+ var E$1 = (l, e, w, p, b, C3 = false) => {
890
+ let r2 = e, O = 0;
891
+ if (C3)
892
+ for (let i2 = p - 1; i2 >= w; i2--) {
893
+ const m = l[i2];
894
+ if (m && (r2 -= m.length), O++, r2 <= b) break;
895
+ }
896
+ else
897
+ for (let i2 = w; i2 < p; i2++) {
898
+ const m = l[i2];
899
+ if (m && (r2 -= m.length), O++, r2 <= b) break;
900
+ }
901
+ return { lineCount: r2, removals: O };
902
+ };
903
+ var limitOptions = ({
904
+ cursor: l,
905
+ options: e,
906
+ style: w,
907
+ output: p = process.stdout,
908
+ maxItems: b = Number.POSITIVE_INFINITY,
909
+ columnPadding: C3 = 0,
910
+ rowPadding: r2 = 4
911
+ }) => {
912
+ const i2 = getColumns(p) - C3, m = getRows(p), M = styleText2("dim", "..."), v = Math.max(m - r2, 0), a2 = Math.max(Math.min(b, v), 5);
913
+ let f = 0;
914
+ l >= a2 - 3 && (f = Math.max(
915
+ Math.min(l - a2 + 3, e.length - a2),
916
+ 0
917
+ ));
918
+ let d = a2 < e.length && f > 0, c3 = a2 < e.length && f + a2 < e.length;
919
+ const I = Math.min(
920
+ f + a2,
921
+ e.length
922
+ ), s = [];
923
+ let g = 0;
924
+ d && g++, c3 && g++;
925
+ const T = f + (d ? 1 : 0), W2 = I - (c3 ? 1 : 0);
926
+ for (let t2 = T; t2 < W2; t2++) {
927
+ const n3 = e[t2], o = n3 !== void 0 ? w(n3, t2 === l) : "", h2 = wrapAnsi(o, i2, {
928
+ hard: true,
929
+ trim: false
930
+ }).split(`
931
+ `);
932
+ s.push(h2), g += h2.length;
933
+ }
934
+ if (g > v) {
935
+ let t2 = 0, n3 = 0, o = g;
936
+ const h2 = l - T;
937
+ let u3 = v;
938
+ const L = () => E$1(s, o, 0, h2, u3), y = () => E$1(
939
+ s,
940
+ o,
941
+ h2 + 1,
942
+ s.length,
943
+ u3,
944
+ true
945
+ );
946
+ d ? ({ lineCount: o, removals: t2 } = L(), o > u3 && (c3 || (u3 -= 1), { lineCount: o, removals: n3 } = y())) : (c3 || (u3 -= 1), { lineCount: o, removals: n3 } = y(), o > u3 && (u3 -= 1, { lineCount: o, removals: t2 } = L())), t2 > 0 && (d = true, s.splice(0, t2)), n3 > 0 && (c3 = true, s.splice(s.length - n3, n3));
947
+ }
948
+ const x = [];
949
+ d && x.push(M);
950
+ for (const t2 of s)
951
+ for (const n3 of t2)
952
+ x.push(n3);
953
+ return c3 && x.push(M), x;
954
+ };
955
+ var confirm = (e) => {
956
+ const a2 = e.active ?? "Yes", o = e.inactive ?? "No";
957
+ return new r({
958
+ active: a2,
959
+ inactive: o,
960
+ signal: e.signal,
961
+ input: e.input,
962
+ output: e.output,
963
+ initialValue: e.initialValue ?? true,
964
+ render() {
965
+ const i2 = e.withGuide ?? settings.withGuide, u3 = `${symbol(this.state)} `, l = i2 ? `${styleText2("gray", S_BAR)} ` : "", f = wrapTextWithPrefix(
966
+ e.output,
967
+ e.message,
968
+ l,
969
+ u3
970
+ ), s = `${i2 ? `${styleText2("gray", S_BAR)}
971
+ ` : ""}${f}
972
+ `, c3 = this.value ? a2 : o;
973
+ switch (this.state) {
974
+ case "submit": {
975
+ const r2 = i2 ? `${styleText2("gray", S_BAR)} ` : "";
976
+ return `${s}${r2}${styleText2("dim", c3)}`;
977
+ }
978
+ case "cancel": {
979
+ const r2 = i2 ? `${styleText2("gray", S_BAR)} ` : "";
980
+ return `${s}${r2}${styleText2(["strikethrough", "dim"], c3)}${i2 ? `
981
+ ${styleText2("gray", S_BAR)}` : ""}`;
982
+ }
983
+ default: {
984
+ const r2 = i2 ? `${styleText2("cyan", S_BAR)} ` : "", g = i2 ? styleText2("cyan", S_BAR_END) : "";
985
+ return `${s}${r2}${this.value ? `${styleText2("green", S_RADIO_ACTIVE)} ${a2}` : `${styleText2("dim", S_RADIO_INACTIVE)} ${styleText2("dim", a2)}`}${e.vertical ? i2 ? `
986
+ ${styleText2("cyan", S_BAR)} ` : `
987
+ ` : ` ${styleText2("dim", "/")} `}${this.value ? `${styleText2("dim", S_RADIO_INACTIVE)} ${styleText2("dim", o)}` : `${styleText2("green", S_RADIO_ACTIVE)} ${o}`}
988
+ ${g}
989
+ `;
990
+ }
991
+ }
992
+ }
993
+ }).prompt();
994
+ };
995
+ var MULTISELECT_INSTRUCTIONS = [
996
+ `${styleText2("dim", "\u2191/\u2193")} to navigate`,
997
+ `${styleText2("dim", "Space:")} select`,
998
+ `${styleText2("dim", "Enter:")} confirm`
999
+ ];
1000
+ var log = {
1001
+ message: (s = [], {
1002
+ symbol: e = styleText2("gray", S_BAR),
1003
+ secondarySymbol: r2 = styleText2("gray", S_BAR),
1004
+ output: m = process.stdout,
1005
+ spacing: l = 1,
1006
+ withGuide: c3
1007
+ } = {}) => {
1008
+ const t2 = [], o = c3 ?? settings.withGuide, f = o ? r2 : "", O = o ? `${e} ` : "", u3 = o ? `${r2} ` : "";
1009
+ for (let i2 = 0; i2 < l; i2++)
1010
+ t2.push(f);
1011
+ const g = Array.isArray(s) ? s : s.split(`
1012
+ `);
1013
+ if (g.length > 0) {
1014
+ const [i2, ...y] = g;
1015
+ i2.length > 0 ? t2.push(`${O}${i2}`) : t2.push(o ? e : "");
1016
+ for (const p of y)
1017
+ p.length > 0 ? t2.push(`${u3}${p}`) : t2.push(o ? r2 : "");
1018
+ }
1019
+ m.write(`${t2.join(`
1020
+ `)}
1021
+ `);
1022
+ },
1023
+ info: (s, e) => {
1024
+ log.message(s, { ...e, symbol: styleText2("blue", S_INFO) });
1025
+ },
1026
+ success: (s, e) => {
1027
+ log.message(s, { ...e, symbol: styleText2("green", S_SUCCESS) });
1028
+ },
1029
+ step: (s, e) => {
1030
+ log.message(s, { ...e, symbol: styleText2("green", S_STEP_SUBMIT) });
1031
+ },
1032
+ warn: (s, e) => {
1033
+ log.message(s, { ...e, symbol: styleText2("yellow", S_WARN) });
1034
+ },
1035
+ /** alias for `log.warn()`. */
1036
+ warning: (s, e) => {
1037
+ log.warn(s, e);
1038
+ },
1039
+ error: (s, e) => {
1040
+ log.message(s, { ...e, symbol: styleText2("red", S_ERROR) });
1041
+ }
1042
+ };
1043
+ var cancel = (o = "", t2) => {
1044
+ const i2 = t2?.output ?? process.stdout, e = t2?.withGuide ?? settings.withGuide ? `${styleText2("gray", S_BAR_END)} ` : "";
1045
+ i2.write(`${e}${styleText2("red", o)}
1046
+
1047
+ `);
1048
+ };
1049
+ var intro = (o = "", t2) => {
1050
+ const i2 = t2?.output ?? process.stdout, e = t2?.withGuide ?? settings.withGuide ? `${styleText2("gray", S_BAR_START)} ` : "";
1051
+ i2.write(`${e}${o}
1052
+ `);
1053
+ };
1054
+ var outro = (o = "", t2) => {
1055
+ const i2 = t2?.output ?? process.stdout, e = t2?.withGuide ?? settings.withGuide ? `${styleText2("gray", S_BAR)}
1056
+ ${styleText2("gray", S_BAR_END)} ` : "";
1057
+ i2.write(`${e}${o}
1058
+
1059
+ `);
1060
+ };
1061
+ var W = (o) => o;
1062
+ var C2 = (o, e, s) => {
1063
+ const a2 = {
1064
+ hard: true,
1065
+ trim: false
1066
+ }, i2 = wrapAnsi(o, e, a2).split(`
1067
+ `), c3 = i2.reduce((n3, t2) => Math.max(dist_default2(t2), n3), 0), u3 = i2.map(s).reduce((n3, t2) => Math.max(dist_default2(t2), n3), 0), g = e - (u3 - c3);
1068
+ return wrapAnsi(o, g, a2);
1069
+ };
1070
+ var note = (o = "", e = "", s) => {
1071
+ const a2 = s?.output ?? process$1.stdout, i2 = s?.withGuide ?? settings.withGuide, c3 = s?.format ?? W, g = ["", ...C2(o, getColumns(a2) - 6, c3).split(`
1072
+ `).map(c3), ""], n3 = dist_default2(e), t2 = Math.max(
1073
+ g.reduce((m, F) => {
1074
+ const O = dist_default2(F);
1075
+ return O > m ? O : m;
1076
+ }, 0),
1077
+ n3
1078
+ ) + 2, h2 = g.map(
1079
+ (m) => `${styleText2("gray", S_BAR)} ${m}${" ".repeat(t2 - dist_default2(m))}${styleText2("gray", S_BAR)}`
1080
+ ).join(`
1081
+ `), T = i2 ? `${styleText2("gray", S_BAR)}
1082
+ ` : "", l$1 = i2 ? S_CONNECT_LEFT : S_CORNER_BOTTOM_LEFT;
1083
+ a2.write(
1084
+ `${T}${styleText2("green", S_STEP_SUBMIT)} ${styleText2("reset", e)} ${styleText2(
1085
+ "gray",
1086
+ S_BAR_H.repeat(Math.max(t2 - n3 - 1, 1)) + S_CORNER_TOP_RIGHT
1087
+ )}
1088
+ ${h2}
1089
+ ${styleText2("gray", l$1 + S_BAR_H.repeat(t2 + 2) + S_CORNER_BOTTOM_RIGHT)}
1090
+ `
1091
+ );
1092
+ };
1093
+ var password = (e) => new u({
1094
+ validate: e.validate,
1095
+ mask: e.mask ?? S_PASSWORD_MASK,
1096
+ signal: e.signal,
1097
+ input: e.input,
1098
+ output: e.output,
1099
+ render() {
1100
+ const r2 = e.withGuide ?? settings.withGuide, o = `${r2 ? `${styleText2("gray", S_BAR)}
1101
+ ` : ""}${symbol(this.state)} ${e.message}
1102
+ `, m = this.userInputWithCursor, i2 = this.masked;
1103
+ switch (this.state) {
1104
+ case "error": {
1105
+ const s = r2 ? `${styleText2("yellow", S_BAR)} ` : "", n3 = r2 ? `${styleText2("yellow", S_BAR_END)} ` : "", d = i2 ?? "";
1106
+ return e.clearOnError && this.clear(), `${o.trim()}
1107
+ ${s}${d}
1108
+ ${n3}${styleText2("yellow", this.error)}
1109
+ `;
1110
+ }
1111
+ case "submit": {
1112
+ const s = r2 ? `${styleText2("gray", S_BAR)} ` : "", n3 = i2 ? styleText2("dim", i2) : "";
1113
+ return `${o}${s}${n3}`;
1114
+ }
1115
+ case "cancel": {
1116
+ const s = r2 ? `${styleText2("gray", S_BAR)} ` : "", n3 = i2 ? styleText2(["strikethrough", "dim"], i2) : "";
1117
+ return `${o}${s}${n3}${i2 && r2 ? `
1118
+ ${styleText2("gray", S_BAR)}` : ""}`;
1119
+ }
1120
+ default: {
1121
+ const s = r2 ? `${styleText2("cyan", S_BAR)} ` : "", n3 = r2 ? styleText2("cyan", S_BAR_END) : "";
1122
+ return `${o}${s}${m}
1123
+ ${n3}
1124
+ `;
1125
+ }
1126
+ }
1127
+ }
1128
+ }).prompt();
1129
+ var Y = 3e4;
1130
+ var Z = (c3) => styleText2("magenta", c3);
1131
+ var spinner = ({
1132
+ indicator: c3 = "dots",
1133
+ onCancel: b,
1134
+ output: n3 = process.stdout,
1135
+ cancelMessage: _,
1136
+ errorMessage: C3,
1137
+ frames: M = unicode ? ["\u25D2", "\u25D0", "\u25D3", "\u25D1"] : ["\u2022", "o", "O", "0"],
1138
+ delay: O = unicode ? 80 : 120,
1139
+ signal: g,
1140
+ ...E
1141
+ } = {}) => {
1142
+ const u3 = isCI(), h2 = isAccessible(E.accessible);
1143
+ let x, I, p = false, l = false, r2 = "", v, w = performance.now();
1144
+ const y = getColumns(n3), F = E?.styleFrame ?? Z, S = (e) => {
1145
+ const s = e > 1 ? C3 ?? settings.messages.error : _ ?? settings.messages.cancel;
1146
+ l = e === 1, p && (m(s, e), l && typeof b == "function" && b());
1147
+ }, $ = () => S(2), a2 = () => S(1), H = () => {
1148
+ process.on("uncaughtExceptionMonitor", $), process.on("unhandledRejection", $), process.on("SIGINT", a2), process.on("SIGTERM", a2), process.on("exit", S), g && g.addEventListener("abort", a2);
1149
+ }, B = () => {
1150
+ process.removeListener("uncaughtExceptionMonitor", $), process.removeListener("unhandledRejection", $), process.removeListener("SIGINT", a2), process.removeListener("SIGTERM", a2), process.removeListener("exit", S), g && g.removeEventListener("abort", a2);
1151
+ }, R2 = () => {
1152
+ if (v === void 0) return;
1153
+ u3 && n3.write(`
1154
+ `);
1155
+ const s = wrapAnsi(v, y, {
1156
+ hard: true,
1157
+ trim: false
1158
+ }).split(`
1159
+ `);
1160
+ s.length > 1 && n3.write(cursor.up(s.length - 1)), n3.write(cursor.to(0)), n3.write(erase.down());
1161
+ }, L = (e) => e.replace(/\.+$/, ""), T = (e) => {
1162
+ const s = (performance.now() - e) / 1e3, i2 = Math.floor(s / 60), t2 = Math.floor(s % 60);
1163
+ return i2 > 0 ? `[${i2}m ${t2}s]` : `[${t2}s]`;
1164
+ }, N = E.withGuide ?? settings.withGuide, P = (e = "") => {
1165
+ if (p = true, l = false, r2 = L(e), w = performance.now(), H(), h2) {
1166
+ r2 !== "" && n3.write(`${r2}
1167
+ `), I = setInterval(() => {
1168
+ n3.write(r2 === "" ? `still working
1169
+ ` : `still working: ${r2}
1170
+ `);
1171
+ }, Y);
1172
+ return;
1173
+ }
1174
+ x = block({ output: n3 }), N && n3.write(`${styleText2("gray", S_BAR)}
1175
+ `);
1176
+ let s = 0, i2 = 0;
1177
+ I = setInterval(() => {
1178
+ if (u3 && r2 === v)
1179
+ return;
1180
+ R2(), v = r2;
1181
+ const t2 = F(M[s]);
1182
+ let o;
1183
+ if (u3)
1184
+ o = `${t2} ${r2}...`;
1185
+ else if (c3 === "timer")
1186
+ o = `${t2} ${r2} ${T(w)}`;
1187
+ else {
1188
+ const j = ".".repeat(Math.floor(i2)).slice(0, 3);
1189
+ o = `${t2} ${r2}${j}`;
1190
+ }
1191
+ const D = wrapAnsi(o, y, {
1192
+ hard: true,
1193
+ trim: false
1194
+ });
1195
+ n3.write(D), s = s + 1 < M.length ? s + 1 : 0, i2 = i2 < 4 ? i2 + 0.125 : 0;
1196
+ }, O);
1197
+ }, m = (e = "", s = 0, i2 = false) => {
1198
+ if (p) {
1199
+ if (p = false, l = s === 1, clearInterval(I), h2 || R2(), r2 = e ?? r2, !i2)
1200
+ if (h2) {
1201
+ const t2 = s === 1 ? _ ?? settings.messages.cancel : s === 2 ? C3 ?? settings.messages.error : "Done", o = r2 || t2;
1202
+ c3 === "timer" ? n3.write(`${o} ${T(w)}
1203
+ `) : n3.write(`${o}
1204
+ `);
1205
+ } else {
1206
+ const t2 = s === 0 ? styleText2("green", S_STEP_SUBMIT) : s === 1 ? styleText2("red", S_STEP_CANCEL) : styleText2("red", S_STEP_ERROR);
1207
+ c3 === "timer" ? n3.write(`${t2} ${r2} ${T(w)}
1208
+ `) : n3.write(`${t2} ${r2}
1209
+ `);
1210
+ }
1211
+ B(), x?.();
1212
+ }
1213
+ };
1214
+ return {
1215
+ start: P,
1216
+ stop: (e = "") => m(e, 0),
1217
+ message: (e = "") => {
1218
+ r2 = L(e ?? r2);
1219
+ },
1220
+ cancel: (e = "") => m(e, 1),
1221
+ error: (e = "") => m(e, 2),
1222
+ clear: () => m("", 0, true),
1223
+ get isCancelled() {
1224
+ return l;
1225
+ }
1226
+ };
1227
+ };
1228
+ var u2 = {
1229
+ light: unicodeOr("\u2500", "-"),
1230
+ heavy: unicodeOr("\u2501", "="),
1231
+ block: unicodeOr("\u2588", "#")
1232
+ };
1233
+ var SELECT_INSTRUCTIONS = [
1234
+ `${styleText2("dim", "\u2191/\u2193")} to navigate`,
1235
+ `${styleText2("dim", "Enter:")} confirm`
1236
+ ];
1237
+ var c2 = (t2, o) => t2.includes(`
1238
+ `) ? t2.split(`
1239
+ `).map((d) => o(d)).join(`
1240
+ `) : o(t2);
1241
+ var select = (t2) => {
1242
+ const o = (n3, m) => {
1243
+ if (n3 === void 0)
1244
+ return "";
1245
+ const s = n3.label ?? String(n3.value);
1246
+ switch (m) {
1247
+ case "disabled":
1248
+ return `${styleText2("gray", S_RADIO_INACTIVE)} ${c2(s, (i2) => styleText2("gray", i2))}${n3.hint ? ` ${styleText2("dim", `(${n3.hint ?? "disabled"})`)}` : ""}`;
1249
+ case "selected":
1250
+ return `${c2(s, (i2) => styleText2("dim", i2))}`;
1251
+ case "active":
1252
+ return `${styleText2("green", S_RADIO_ACTIVE)} ${s}${n3.hint ? ` ${styleText2("dim", `(${n3.hint})`)}` : ""}`;
1253
+ case "cancelled":
1254
+ return `${c2(s, (i2) => styleText2(["strikethrough", "dim"], i2))}`;
1255
+ default:
1256
+ return `${styleText2("dim", S_RADIO_INACTIVE)} ${c2(s, (i2) => styleText2("dim", i2))}`;
1257
+ }
1258
+ }, d = t2.showInstructions ?? true;
1259
+ return new n$1({
1260
+ options: t2.options,
1261
+ signal: t2.signal,
1262
+ input: t2.input,
1263
+ output: t2.output,
1264
+ initialValue: t2.initialValue,
1265
+ render() {
1266
+ const n3 = t2.withGuide ?? settings.withGuide, m = `${symbol(this.state)} `, s = `${symbolBar(this.state)} `, i2 = wrapTextWithPrefix(
1267
+ t2.output,
1268
+ t2.message,
1269
+ s,
1270
+ m
1271
+ ), u3 = `${n3 ? `${styleText2("gray", S_BAR)}
1272
+ ` : ""}${i2}
1273
+ `;
1274
+ switch (this.state) {
1275
+ case "submit": {
1276
+ const r2 = n3 ? `${styleText2("gray", S_BAR)} ` : "", a2 = wrapTextWithPrefix(
1277
+ t2.output,
1278
+ o(this.options[this.cursor], "selected"),
1279
+ r2
1280
+ );
1281
+ return `${u3}${a2}`;
1282
+ }
1283
+ case "cancel": {
1284
+ const r2 = n3 ? `${styleText2("gray", S_BAR)} ` : "", a2 = wrapTextWithPrefix(
1285
+ t2.output,
1286
+ o(this.options[this.cursor], "cancelled"),
1287
+ r2
1288
+ );
1289
+ return `${u3}${a2}${n3 ? `
1290
+ ${styleText2("gray", S_BAR)}` : ""}`;
1291
+ }
1292
+ default: {
1293
+ const r2 = n3 ? `${styleText2("cyan", S_BAR)} ` : "", a2 = u3.split(`
1294
+ `).length, p = d ? formatInstructionFooter(t2.output, SELECT_INSTRUCTIONS, n3) : n3 ? [styleText2("cyan", S_BAR_END)] : [], f = p.join(`
1295
+ `), b = p.length + 1;
1296
+ return `${u3}${r2}${limitOptions({
1297
+ output: t2.output,
1298
+ cursor: this.cursor,
1299
+ options: this.options,
1300
+ maxItems: t2.maxItems,
1301
+ columnPadding: r2.length,
1302
+ rowPadding: a2 + b,
1303
+ style: (g, x) => o(g, g.disabled ? "disabled" : x ? "active" : "inactive")
1304
+ }).join(`
1305
+ ${r2}`)}
1306
+ ${f}
1307
+ `;
1308
+ }
1309
+ }
1310
+ }
1311
+ }).prompt();
1312
+ };
1313
+ var i = `${styleText2("gray", S_BAR)} `;
1314
+ var text = (t2) => new n2({
1315
+ validate: t2.validate,
1316
+ placeholder: t2.placeholder,
1317
+ defaultValue: t2.defaultValue,
1318
+ initialValue: t2.initialValue,
1319
+ output: t2.output,
1320
+ signal: t2.signal,
1321
+ input: t2.input,
1322
+ render() {
1323
+ const r2 = t2?.withGuide ?? settings.withGuide, l = `${`${r2 ? `${styleText2("gray", S_BAR)}
1324
+ ` : ""}${symbol(this.state)} `}${t2.message}
1325
+ `, d = t2.placeholder && t2.placeholder.length > 0 ? (
1326
+ // biome-ignore lint/style/noNonNullAssertion: guarded by placeholder.length > 0
1327
+ styleText2("inverse", t2.placeholder[0]) + styleText2("dim", t2.placeholder.slice(1))
1328
+ ) : styleText2(["inverse", "hidden"], "_"), o = this.userInput ? this.userInputWithCursor : d, s = this.value ?? "";
1329
+ switch (this.state) {
1330
+ case "validating": {
1331
+ const n3 = r2 ? `${styleText2("cyan", S_BAR)} ` : "", i2 = r2 ? styleText2("cyan", S_BAR_END) : "", c3 = styleText2("dim", o), $ = styleText2("dim", "Validating...");
1332
+ return `${l}${n3}${c3}
1333
+ ${i2} ${$}
1334
+ `;
1335
+ }
1336
+ case "error": {
1337
+ const n3 = this.error ? ` ${styleText2("yellow", this.error)}` : "", i2 = r2 ? `${styleText2("yellow", S_BAR)} ` : "", c3 = r2 ? styleText2("yellow", S_BAR_END) : "";
1338
+ return `${l.trim()}
1339
+ ${i2}${o}
1340
+ ${c3}${n3}
1341
+ `;
1342
+ }
1343
+ case "submit": {
1344
+ const n3 = s ? `${r2 ? " " : ""}${styleText2("dim", s)}` : "", i2 = r2 ? styleText2("gray", S_BAR) : "";
1345
+ return `${l}${i2}${n3}`;
1346
+ }
1347
+ case "cancel": {
1348
+ const n3 = s ? ` ${styleText2(["strikethrough", "dim"], s)}` : "", i2 = r2 ? styleText2("gray", S_BAR) : "";
1349
+ return `${l}${i2}${n3}${s.trim() ? `
1350
+ ${i2}` : ""}`;
1351
+ }
1352
+ default: {
1353
+ const n3 = r2 ? `${styleText2("cyan", S_BAR)} ` : "", i2 = r2 ? styleText2("cyan", S_BAR_END) : "";
1354
+ return `${l}${n3}${o}
1355
+ ${i2}
1356
+ `;
1357
+ }
1358
+ }
1359
+ }
1360
+ }).prompt();
1361
+
1362
+ // ../lib/crypto.ts
1363
+ var KEY_PREFIX = "vlt_key_";
1364
+ function getCrypto() {
1365
+ if (typeof globalThis !== "undefined" && globalThis.crypto && globalThis.crypto.subtle) {
1366
+ return globalThis.crypto;
1367
+ }
1368
+ throw new Error("WebCrypto API is not available in this runtime.");
1369
+ }
1370
+ function bytesToHex(bytes) {
1371
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
1372
+ }
1373
+ function hexToBytes(hex) {
1374
+ const clean = hex.trim().toLowerCase();
1375
+ if (clean.length % 2 !== 0 || !/^[0-9a-f]+$/.test(clean)) {
1376
+ throw new Error("Invalid hexadecimal key material.");
1377
+ }
1378
+ const out = new Uint8Array(clean.length / 2);
1379
+ for (let i2 = 0; i2 < out.length; i2++) {
1380
+ out[i2] = parseInt(clean.slice(i2 * 2, i2 * 2 + 2), 16);
1381
+ }
1382
+ return out;
1383
+ }
1384
+ function bytesToBase64(bytes) {
1385
+ if (typeof Buffer !== "undefined") {
1386
+ return Buffer.from(bytes).toString("base64");
1387
+ }
1388
+ let binary = "";
1389
+ for (let i2 = 0; i2 < bytes.length; i2++) {
1390
+ binary += String.fromCharCode(bytes[i2]);
1391
+ }
1392
+ return btoa(binary);
1393
+ }
1394
+ function base64ToBytes(b64) {
1395
+ if (typeof Buffer !== "undefined") {
1396
+ return new Uint8Array(Buffer.from(b64, "base64"));
1397
+ }
1398
+ const binary = atob(b64);
1399
+ const out = new Uint8Array(binary.length);
1400
+ for (let i2 = 0; i2 < binary.length; i2++) {
1401
+ out[i2] = binary.charCodeAt(i2);
1402
+ }
1403
+ return out;
1404
+ }
1405
+ function toArrayBuffer(bytes) {
1406
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
1407
+ }
1408
+ function buildVaultAad(projectId, envSlug) {
1409
+ return `vaultenv:v1:${projectId}:${envSlug}`;
1410
+ }
1411
+ function generateProjectMasterKey() {
1412
+ const random = new Uint8Array(32);
1413
+ getCrypto().getRandomValues(random);
1414
+ return `${KEY_PREFIX}${bytesToHex(random)}`;
1415
+ }
1416
+ function isValidProjectMasterKey(key) {
1417
+ const trimmed = key.trim();
1418
+ return /^vlt_key_[0-9a-f]{64}$/i.test(trimmed);
1419
+ }
1420
+ function extractRawKeyBytes(vaultKey) {
1421
+ const trimmed = vaultKey.trim();
1422
+ if (!isValidProjectMasterKey(trimmed)) {
1423
+ throw new Error("Invalid VAULT_KEY format. Expected vlt_key_ followed by 64 hex characters.");
1424
+ }
1425
+ return hexToBytes(trimmed.slice(KEY_PREFIX.length));
1426
+ }
1427
+ async function computeKeyFingerprint(vaultKey) {
1428
+ const raw = extractRawKeyBytes(vaultKey);
1429
+ const hash = await getCrypto().subtle.digest("SHA-256", toArrayBuffer(raw));
1430
+ return bytesToHex(new Uint8Array(hash)).slice(0, 16);
1431
+ }
1432
+ async function importAesKey(rawBytes, usages) {
1433
+ return getCrypto().subtle.importKey("raw", toArrayBuffer(rawBytes), { name: "AES-GCM" }, false, usages);
1434
+ }
1435
+ async function encryptVaultPayload(plaintext, vaultKey, projectId, envSlug) {
1436
+ const cryptoApi = getCrypto();
1437
+ const key = await importAesKey(extractRawKeyBytes(vaultKey), ["encrypt"]);
1438
+ const ivBytes = new Uint8Array(12);
1439
+ cryptoApi.getRandomValues(ivBytes);
1440
+ const aad = buildVaultAad(projectId, envSlug);
1441
+ const encoder = new TextEncoder();
1442
+ const encrypted = await cryptoApi.subtle.encrypt(
1443
+ {
1444
+ name: "AES-GCM",
1445
+ iv: toArrayBuffer(ivBytes),
1446
+ additionalData: toArrayBuffer(encoder.encode(aad)),
1447
+ tagLength: 128
1448
+ },
1449
+ key,
1450
+ toArrayBuffer(encoder.encode(plaintext))
1451
+ );
1452
+ return {
1453
+ iv: bytesToBase64(ivBytes),
1454
+ ciphertext: bytesToBase64(new Uint8Array(encrypted)),
1455
+ aad
1456
+ };
1457
+ }
1458
+ async function decryptVaultPayload(blob, vaultKey, expectedProjectId, expectedEnvSlug) {
1459
+ const expectedAad = buildVaultAad(expectedProjectId, expectedEnvSlug);
1460
+ if (blob.aad !== expectedAad) {
1461
+ throw new Error(
1462
+ `AAD mismatch: expected "${expectedAad}" but received "${blob.aad}". Possible cross-environment replay.`
1463
+ );
1464
+ }
1465
+ const cryptoApi = getCrypto();
1466
+ const key = await importAesKey(extractRawKeyBytes(vaultKey), ["decrypt"]);
1467
+ const ivBytes = base64ToBytes(blob.iv);
1468
+ const cipherBytes = base64ToBytes(blob.ciphertext);
1469
+ const encoder = new TextEncoder();
1470
+ try {
1471
+ const decrypted = await cryptoApi.subtle.decrypt(
1472
+ {
1473
+ name: "AES-GCM",
1474
+ iv: toArrayBuffer(ivBytes),
1475
+ additionalData: toArrayBuffer(encoder.encode(expectedAad)),
1476
+ tagLength: 128
1477
+ },
1478
+ key,
1479
+ toArrayBuffer(cipherBytes)
1480
+ );
1481
+ return new TextDecoder().decode(decrypted);
1482
+ } catch {
1483
+ throw new Error("Decryption failed: invalid VAULT_KEY or tampered ciphertext/authentication tag.");
1484
+ }
1485
+ }
1486
+ async function decryptPrivateKeyWithPassphrase(encryptedBundleJson, passphrase) {
1487
+ const cryptoApi = getCrypto();
1488
+ const bundle = JSON.parse(encryptedBundleJson);
1489
+ const encoder = new TextEncoder();
1490
+ const baseKey = await cryptoApi.subtle.importKey(
1491
+ "raw",
1492
+ toArrayBuffer(encoder.encode(passphrase)),
1493
+ "PBKDF2",
1494
+ false,
1495
+ ["deriveKey"]
1496
+ );
1497
+ const wrappingKey = await cryptoApi.subtle.deriveKey(
1498
+ {
1499
+ name: "PBKDF2",
1500
+ salt: toArrayBuffer(base64ToBytes(bundle.salt)),
1501
+ iterations: bundle.iterations,
1502
+ hash: "SHA-256"
1503
+ },
1504
+ baseKey,
1505
+ { name: "AES-GCM", length: 256 },
1506
+ false,
1507
+ ["decrypt"]
1508
+ );
1509
+ const plain = await cryptoApi.subtle.decrypt(
1510
+ { name: "AES-GCM", iv: toArrayBuffer(base64ToBytes(bundle.iv)) },
1511
+ wrappingKey,
1512
+ toArrayBuffer(base64ToBytes(bundle.ciphertext))
1513
+ );
1514
+ return bytesToBase64(new Uint8Array(plain));
1515
+ }
1516
+ async function wrapProjectKeyForTeammate(vaultKey, recipientPublicKeySpkiB64) {
1517
+ extractRawKeyBytes(vaultKey);
1518
+ const cryptoApi = getCrypto();
1519
+ const recipientPubKey = await cryptoApi.subtle.importKey(
1520
+ "spki",
1521
+ toArrayBuffer(base64ToBytes(recipientPublicKeySpkiB64)),
1522
+ { name: "ECDH", namedCurve: "P-256" },
1523
+ false,
1524
+ []
1525
+ );
1526
+ const ephemeral = await cryptoApi.subtle.generateKey(
1527
+ { name: "ECDH", namedCurve: "P-256" },
1528
+ true,
1529
+ ["deriveKey"]
1530
+ );
1531
+ const sharedKey = await cryptoApi.subtle.deriveKey(
1532
+ { name: "ECDH", public: recipientPubKey },
1533
+ ephemeral.privateKey,
1534
+ { name: "AES-GCM", length: 256 },
1535
+ false,
1536
+ ["encrypt"]
1537
+ );
1538
+ const iv = new Uint8Array(12);
1539
+ cryptoApi.getRandomValues(iv);
1540
+ const wrapped = await cryptoApi.subtle.encrypt(
1541
+ { name: "AES-GCM", iv: toArrayBuffer(iv) },
1542
+ sharedKey,
1543
+ toArrayBuffer(new TextEncoder().encode(vaultKey))
1544
+ );
1545
+ const ephemeralPubSpki = new Uint8Array(
1546
+ await cryptoApi.subtle.exportKey("spki", ephemeral.publicKey)
1547
+ );
1548
+ return bytesToBase64(
1549
+ new TextEncoder().encode(
1550
+ JSON.stringify({
1551
+ alg: "ECDH-P256-AES256GCM",
1552
+ epk: bytesToBase64(ephemeralPubSpki),
1553
+ iv: bytesToBase64(iv),
1554
+ ct: bytesToBase64(new Uint8Array(wrapped))
1555
+ })
1556
+ )
1557
+ );
1558
+ }
1559
+ async function unwrapProjectKeyForTeammate(wrappedEnvelopeB64, recipientPrivateKeyPkcs8B64) {
1560
+ const cryptoApi = getCrypto();
1561
+ const envelope = JSON.parse(
1562
+ new TextDecoder().decode(base64ToBytes(wrappedEnvelopeB64))
1563
+ );
1564
+ const privateKey = await cryptoApi.subtle.importKey(
1565
+ "pkcs8",
1566
+ toArrayBuffer(base64ToBytes(recipientPrivateKeyPkcs8B64)),
1567
+ { name: "ECDH", namedCurve: "P-256" },
1568
+ false,
1569
+ ["deriveKey"]
1570
+ );
1571
+ const ephemeralPub = await cryptoApi.subtle.importKey(
1572
+ "spki",
1573
+ toArrayBuffer(base64ToBytes(envelope.epk)),
1574
+ { name: "ECDH", namedCurve: "P-256" },
1575
+ false,
1576
+ []
1577
+ );
1578
+ const sharedKey = await cryptoApi.subtle.deriveKey(
1579
+ { name: "ECDH", public: ephemeralPub },
1580
+ privateKey,
1581
+ { name: "AES-GCM", length: 256 },
1582
+ false,
1583
+ ["decrypt"]
1584
+ );
1585
+ const decrypted = await cryptoApi.subtle.decrypt(
1586
+ { name: "AES-GCM", iv: toArrayBuffer(base64ToBytes(envelope.iv)) },
1587
+ sharedKey,
1588
+ toArrayBuffer(base64ToBytes(envelope.ct))
1589
+ );
1590
+ return new TextDecoder().decode(decrypted);
1591
+ }
1592
+
1593
+ // ../lib/dotenv.ts
1594
+ function parseDotenv(input) {
1595
+ const lines = input.replace(/\r\n/g, "\n").split("\n");
1596
+ const results = [];
1597
+ const indexByKey = /* @__PURE__ */ new Map();
1598
+ for (const rawLine of lines) {
1599
+ const trimmed = rawLine.trim();
1600
+ if (!trimmed || trimmed.startsWith("#")) {
1601
+ continue;
1602
+ }
1603
+ const withoutExport = trimmed.startsWith("export ") ? trimmed.slice(7).trim() : trimmed;
1604
+ const eqIndex = withoutExport.indexOf("=");
1605
+ if (eqIndex <= 0) continue;
1606
+ const key = withoutExport.slice(0, eqIndex).trim();
1607
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue;
1608
+ let rawValue = withoutExport.slice(eqIndex + 1).trim();
1609
+ let comment;
1610
+ if (rawValue.startsWith('"') && rawValue.endsWith('"') && rawValue.length >= 2 || rawValue.startsWith("'") && rawValue.endsWith("'") && rawValue.length >= 2) {
1611
+ const quote = rawValue[0];
1612
+ rawValue = rawValue.slice(1, -1);
1613
+ if (quote === '"') {
1614
+ rawValue = rawValue.replace(/\\n/g, "\n").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
1615
+ }
1616
+ } else {
1617
+ const inlineCommentIdx = rawValue.indexOf(" #");
1618
+ if (inlineCommentIdx !== -1) {
1619
+ comment = rawValue.slice(inlineCommentIdx + 2).trim();
1620
+ rawValue = rawValue.slice(0, inlineCommentIdx).trim();
1621
+ }
1622
+ }
1623
+ const pair = { key, value: rawValue, ...comment ? { comment } : {} };
1624
+ if (indexByKey.has(key)) {
1625
+ results[indexByKey.get(key)] = pair;
1626
+ } else {
1627
+ indexByKey.set(key, results.length);
1628
+ results.push(pair);
1629
+ }
1630
+ }
1631
+ return results;
1632
+ }
1633
+ function serializeDotenv(pairs) {
1634
+ return pairs.filter((p) => p.key.trim().length > 0).map((p) => {
1635
+ const key = p.key.trim();
1636
+ const needsQuotes = /[\s#"'\n=]/.test(p.value) || p.value === "";
1637
+ const escaped = p.value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
1638
+ const formattedVal = needsQuotes ? `"${escaped}"` : p.value;
1639
+ return `${key}=${formattedVal}`;
1640
+ }).join("\n");
1641
+ }
1642
+ function diffSecretLists(left, right) {
1643
+ const leftMap = new Map(left.map((p) => [p.key, p.value]));
1644
+ const rightMap = new Map(right.map((p) => [p.key, p.value]));
1645
+ const keys = Array.from(/* @__PURE__ */ new Set([...leftMap.keys(), ...rightMap.keys()])).sort();
1646
+ return keys.map((key) => {
1647
+ const l = leftMap.get(key);
1648
+ const r2 = rightMap.get(key);
1649
+ if (l === void 0 && r2 !== void 0) {
1650
+ return { key, status: "added", rightValue: r2 };
1651
+ }
1652
+ if (l !== void 0 && r2 === void 0) {
1653
+ return { key, status: "removed", leftValue: l };
1654
+ }
1655
+ if (l !== r2) {
1656
+ return { key, status: "changed", leftValue: l, rightValue: r2 };
1657
+ }
1658
+ return { key, status: "unchanged", leftValue: l, rightValue: r2 };
1659
+ });
1660
+ }
1661
+
1662
+ // src/config.ts
1663
+ import fs from "node:fs";
1664
+ import os from "node:os";
1665
+ import path from "node:path";
1666
+ import { execFileSync } from "node:child_process";
1667
+ var CONFIG_DIR = process.env.VAULTENV_CONFIG_DIR || path.join(os.homedir(), ".vaultenv");
1668
+ var CREDENTIALS_FILE = path.join(CONFIG_DIR, "credentials.json");
1669
+ var IDENTITY_FILE = path.join(CONFIG_DIR, "identity.json");
1670
+ var PROJECT_FILE = ".vaultenv.json";
1671
+ function ensureDir() {
1672
+ fs.mkdirSync(CONFIG_DIR, { recursive: true });
1673
+ }
1674
+ function readJson(file) {
1675
+ try {
1676
+ return JSON.parse(fs.readFileSync(file, "utf8"));
1677
+ } catch {
1678
+ return null;
1679
+ }
1680
+ }
1681
+ function writeJson(file, value) {
1682
+ ensureDir();
1683
+ fs.writeFileSync(file, JSON.stringify(value, null, 2), { encoding: "utf8", mode: 384 });
1684
+ try {
1685
+ fs.chmodSync(file, 384);
1686
+ } catch {
1687
+ }
1688
+ }
1689
+ function getCredentials() {
1690
+ return readJson(CREDENTIALS_FILE);
1691
+ }
1692
+ function saveCredentials(credentials) {
1693
+ writeJson(CREDENTIALS_FILE, credentials);
1694
+ }
1695
+ function getIdentity() {
1696
+ return readJson(IDENTITY_FILE);
1697
+ }
1698
+ function saveIdentity(identity) {
1699
+ writeJson(IDENTITY_FILE, identity);
1700
+ }
1701
+ function clearLocalAuth() {
1702
+ fs.rmSync(CREDENTIALS_FILE, { force: true });
1703
+ fs.rmSync(IDENTITY_FILE, { force: true });
1704
+ }
1705
+ function readProjectConfig() {
1706
+ return readJson(path.join(process.cwd(), PROJECT_FILE));
1707
+ }
1708
+ function writeProjectConfig(config) {
1709
+ fs.writeFileSync(path.join(process.cwd(), PROJECT_FILE), JSON.stringify(config, null, 2));
1710
+ }
1711
+ function detectGitRepo() {
1712
+ try {
1713
+ const remote = execFileSync("git", ["config", "--get", "remote.origin.url"], {
1714
+ encoding: "utf8",
1715
+ stdio: ["ignore", "pipe", "ignore"]
1716
+ }).trim();
1717
+ const match = remote.match(/github\.com[:/]([^/]+)\/([^/.]+)(?:\.git)?$/i);
1718
+ return match ? `${match[1]}/${match[2]}` : null;
1719
+ } catch {
1720
+ return null;
1721
+ }
1722
+ }
1723
+ function ensureGitignore() {
1724
+ const file = path.join(process.cwd(), ".gitignore");
1725
+ const existing = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
1726
+ const lines = new Set(existing.split(/\r?\n/).map((line) => line.trim()).filter(Boolean));
1727
+ const add = [];
1728
+ if (!lines.has(".env*")) add.push(".env*");
1729
+ if (!lines.has("!.env.example")) add.push("!.env.example");
1730
+ if (add.length === 0) return false;
1731
+ const next = `${existing.replace(/\s*$/, "")}
1732
+ ${add.join("\n")}
1733
+ `;
1734
+ fs.writeFileSync(file, next, "utf8");
1735
+ return true;
1736
+ }
1737
+
1738
+ // src/api.ts
1739
+ var ApiError = class extends Error {
1740
+ constructor(message, status, body) {
1741
+ super(message);
1742
+ this.name = "ApiError";
1743
+ this.status = status;
1744
+ this.body = body;
1745
+ }
1746
+ };
1747
+ function apiBase() {
1748
+ return (process.env.VAULTENV_API_URL || getCredentials()?.apiUrl || "https://env-vault.fkodelabs.com").replace(/\/+$/, "");
1749
+ }
1750
+ async function request(path3, options = {}) {
1751
+ const base = (options.base || apiBase()).replace(/\/+$/, "");
1752
+ const token = options.token === void 0 ? getCredentials()?.token ?? null : options.token;
1753
+ const headers = { Accept: "application/json" };
1754
+ if (options.body !== void 0) headers["Content-Type"] = "application/json";
1755
+ if (token) headers.Authorization = `Bearer ${token}`;
1756
+ const response = await fetch(`${base}${path3}`, {
1757
+ method: options.method || "GET",
1758
+ headers,
1759
+ body: options.body === void 0 ? void 0 : JSON.stringify(options.body),
1760
+ signal: AbortSignal.timeout(2e4)
1761
+ });
1762
+ const text2 = await response.text();
1763
+ let parsed = null;
1764
+ try {
1765
+ parsed = text2 ? JSON.parse(text2) : null;
1766
+ } catch {
1767
+ parsed = text2;
1768
+ }
1769
+ if (!response.ok) {
1770
+ const message = parsed && typeof parsed === "object" && "error" in parsed ? String(parsed.error) : `Request failed with status ${response.status}.`;
1771
+ throw new ApiError(message, response.status, parsed);
1772
+ }
1773
+ return parsed;
1774
+ }
1775
+
1776
+ // src/index.ts
1777
+ var VERSION = "0.1.0";
1778
+ function parseArgs(argv) {
1779
+ const [command = "help", ...rest] = argv;
1780
+ const positionals = [];
1781
+ const flags = /* @__PURE__ */ new Map();
1782
+ for (let index = 0; index < rest.length; index += 1) {
1783
+ const value = rest[index];
1784
+ if (!value.startsWith("--")) {
1785
+ positionals.push(value);
1786
+ continue;
1787
+ }
1788
+ const [name, inline] = value.slice(2).split("=", 2);
1789
+ if (inline !== void 0) {
1790
+ flags.set(name, inline);
1791
+ } else if (rest[index + 1] && !rest[index + 1].startsWith("-")) {
1792
+ flags.set(name, rest[index + 1]);
1793
+ index += 1;
1794
+ } else {
1795
+ flags.set(name, true);
1796
+ }
1797
+ }
1798
+ return { command, positionals, flags };
1799
+ }
1800
+ var flag = (args, name) => {
1801
+ const value = args.flags.get(name);
1802
+ return typeof value === "string" ? value : void 0;
1803
+ };
1804
+ var hasFlag = (args, name) => args.flags.has(name);
1805
+ function fail(message) {
1806
+ cancel(message);
1807
+ process.exit(1);
1808
+ }
1809
+ function sleep(ms) {
1810
+ return new Promise((resolve) => setTimeout(resolve, ms));
1811
+ }
1812
+ function openBrowser(url) {
1813
+ try {
1814
+ if (process.platform === "win32") {
1815
+ spawn("cmd", ["/c", "start", "", url], { detached: true, stdio: "ignore" }).unref();
1816
+ } else if (process.platform === "darwin") {
1817
+ spawn("open", [url], { detached: true, stdio: "ignore" }).unref();
1818
+ } else {
1819
+ spawn("xdg-open", [url], { detached: true, stdio: "ignore" }).unref();
1820
+ }
1821
+ } catch {
1822
+ }
1823
+ }
1824
+ function requireCredentials() {
1825
+ const credentials = getCredentials();
1826
+ if (!credentials) {
1827
+ fail("No CLI session found. Run `vaultenv login` first.");
1828
+ }
1829
+ return credentials;
1830
+ }
1831
+ async function getMe(token) {
1832
+ return request("/api/auth/me", { token });
1833
+ }
1834
+ async function getWorkspace(token) {
1835
+ return request("/api/v1/workspace", { token });
1836
+ }
1837
+ async function unlockIdentity() {
1838
+ const existing = getIdentity();
1839
+ if (existing) return existing;
1840
+ const credentials = requireCredentials();
1841
+ const me = await getMe(credentials.token);
1842
+ const fromEnv = process.env.VAULTENV_PASSPHRASE;
1843
+ let passphrase = fromEnv;
1844
+ if (!passphrase) {
1845
+ if (!process.stdin.isTTY) {
1846
+ fail("Set VAULTENV_PASSPHRASE to unlock a vault in a non-interactive shell.");
1847
+ }
1848
+ const answer = await password({
1849
+ message: `Vault passphrase for ${me.user.email}`,
1850
+ mask: "\u2022",
1851
+ validate: (value) => value && value.length >= 6 ? void 0 : "At least six characters."
1852
+ });
1853
+ if (isCancel(answer)) fail("Unlock cancelled.");
1854
+ passphrase = answer;
1855
+ }
1856
+ try {
1857
+ const privateKeyPkcs8 = await decryptPrivateKeyWithPassphrase(
1858
+ me.user.encryptedPrivateKey,
1859
+ passphrase
1860
+ );
1861
+ const identity = {
1862
+ privateKeyPkcs8,
1863
+ publicKey: me.user.publicKey,
1864
+ fingerprint: me.user.publicKeyFingerprint
1865
+ };
1866
+ saveIdentity(identity);
1867
+ return identity;
1868
+ } catch {
1869
+ fail("That passphrase could not open the private key.");
1870
+ }
1871
+ }
1872
+ async function resolveProject(workspace, overrideId) {
1873
+ const config = readProjectConfig();
1874
+ const projectId = overrideId || config?.projectId;
1875
+ if (!projectId) fail("No project linked. Run `vaultenv init` or `vaultenv use`.");
1876
+ const project = workspace.projects.find((item) => item.id === projectId);
1877
+ if (!project) fail("The linked project no longer exists. Run `vaultenv use` to relink.");
1878
+ return project;
1879
+ }
1880
+ async function projectKey(project, identity) {
1881
+ const workspace = await getWorkspace();
1882
+ const envelope = project.keyEnvelopes.find(
1883
+ (item) => item.userId === workspace.currentUser.id
1884
+ );
1885
+ if (!envelope) {
1886
+ fail("This account has no key envelope for the project. Open the dashboard once to reconcile access.");
1887
+ }
1888
+ const key = await unwrapProjectKeyForTeammate(envelope.wrappedProjectKey, identity.privateKeyPkcs8);
1889
+ const fingerprint = await computeKeyFingerprint(key);
1890
+ if (project.keyFingerprint && fingerprint !== project.keyFingerprint) {
1891
+ fail("The project key fingerprint does not match. Refusing to encrypt or decrypt.");
1892
+ }
1893
+ return key;
1894
+ }
1895
+ function envFileFor(envSlug) {
1896
+ const explicit = `.env.${envSlug}`;
1897
+ if (fs2.existsSync(explicit)) return explicit;
1898
+ if (fs2.existsSync(".env")) return ".env";
1899
+ return explicit;
1900
+ }
1901
+ async function pushFile(file, envSlug) {
1902
+ const credentials = requireCredentials();
1903
+ const workspace = await getWorkspace(credentials.token);
1904
+ const project = await resolveProject(workspace);
1905
+ if (!project.environments.some((environment) => environment.slug === envSlug)) {
1906
+ fail(`Environment "${envSlug}" does not exist on ${project.name}.`);
1907
+ }
1908
+ if (!fs2.existsSync(file)) fail(`File not found: ${file}`);
1909
+ const identity = await unlockIdentity();
1910
+ const key = await projectKey(project, identity);
1911
+ const pairs = parseDotenv(fs2.readFileSync(file, "utf8"));
1912
+ if (pairs.length === 0) fail(`No variables found in ${file}.`);
1913
+ const plaintext = serializeDotenv(pairs);
1914
+ const encrypted = await encryptVaultPayload(plaintext, key, project.id, envSlug);
1915
+ const result = await request(
1916
+ "/api/v1/vault/push",
1917
+ {
1918
+ method: "POST",
1919
+ token: credentials.token,
1920
+ body: {
1921
+ projectId: project.id,
1922
+ environmentSlug: envSlug,
1923
+ iv: encrypted.iv,
1924
+ ciphertext: encrypted.ciphertext,
1925
+ aad: encrypted.aad,
1926
+ secretCount: pairs.length,
1927
+ source: "cli-push",
1928
+ commitNote: `CLI import from ${path2.basename(file)}`
1929
+ }
1930
+ }
1931
+ );
1932
+ outro(
1933
+ `Sealed ${result.version.secretCount} variables into ${project.githubRepo} / ${envSlug} (v${result.version.version}).`
1934
+ );
1935
+ }
1936
+ async function pullEnv(envSlug, outFile, assumeYes, serviceToken, serviceKey) {
1937
+ if (serviceToken) {
1938
+ if (!serviceKey) {
1939
+ fail("Service-token mode requires VAULTENV_KEY or --key.");
1940
+ }
1941
+ const key2 = serviceKey.trim();
1942
+ if (!isValidProjectMasterKey(key2)) {
1943
+ fail("Invalid VAULTENV_KEY format. Expected vlt_key_ followed by 64 hex characters.");
1944
+ }
1945
+ const remote2 = await request(
1946
+ `/api/v1/vault/pull?env=${encodeURIComponent(envSlug)}&source=service-token`,
1947
+ { token: serviceToken }
1948
+ );
1949
+ const plaintext2 = await decryptVaultPayload(
1950
+ { iv: remote2.iv, ciphertext: remote2.ciphertext, aad: remote2.aad },
1951
+ key2,
1952
+ remote2.projectId,
1953
+ remote2.environmentSlug
1954
+ );
1955
+ const target2 = outFile || `.env.${remote2.environmentSlug}`;
1956
+ if (fs2.existsSync(target2) && !assumeYes) {
1957
+ fail(`${target2} already exists. Use --yes to overwrite it.`);
1958
+ }
1959
+ fs2.writeFileSync(target2, plaintext2, { encoding: "utf8", mode: 384 });
1960
+ try {
1961
+ fs2.chmodSync(target2, 384);
1962
+ } catch {
1963
+ }
1964
+ outro(
1965
+ `Pulled ${remote2.secretCount} variables from ${remote2.environmentSlug} (v${remote2.version}) with a service token into ${target2}.`
1966
+ );
1967
+ return;
1968
+ }
1969
+ const credentials = requireCredentials();
1970
+ const workspace = await getWorkspace(credentials.token);
1971
+ const project = await resolveProject(workspace);
1972
+ if (!project.environments.some((environment) => environment.slug === envSlug)) {
1973
+ fail(`Environment "${envSlug}" does not exist on ${project.name}.`);
1974
+ }
1975
+ const identity = await unlockIdentity();
1976
+ const key = await projectKey(project, identity);
1977
+ const remote = await request(
1978
+ `/api/v1/vault/pull?projectId=${encodeURIComponent(project.id)}&env=${encodeURIComponent(envSlug)}&source=cli-pull`,
1979
+ { token: credentials.token }
1980
+ );
1981
+ const plaintext = await decryptVaultPayload(
1982
+ { iv: remote.iv, ciphertext: remote.ciphertext, aad: remote.aad },
1983
+ key,
1984
+ project.id,
1985
+ envSlug
1986
+ );
1987
+ const target = outFile || `.env.${envSlug}`;
1988
+ if (fs2.existsSync(target) && !assumeYes) {
1989
+ const current = parseDotenv(fs2.readFileSync(target, "utf8"));
1990
+ const incoming = parseDotenv(plaintext);
1991
+ const diff = diffSecretLists(current, incoming);
1992
+ const added = diff.filter((item) => item.status === "added").length;
1993
+ const removed = diff.filter((item) => item.status === "removed").length;
1994
+ const changed = diff.filter((item) => item.status === "changed").length;
1995
+ log.info(`Existing ${target}: +${added} -${removed} ~${changed} compared with v${remote.version}.`);
1996
+ if (!process.stdin.isTTY) {
1997
+ fail("Refusing to overwrite a file without confirmation. Use --yes.");
1998
+ }
1999
+ const overwrite = await confirm({ message: `Overwrite ${target}?` });
2000
+ if (isCancel(overwrite) || !overwrite) {
2001
+ outro("Nothing written.");
2002
+ return;
2003
+ }
2004
+ }
2005
+ fs2.writeFileSync(target, plaintext, { encoding: "utf8", mode: 384 });
2006
+ try {
2007
+ fs2.chmodSync(target, 384);
2008
+ } catch {
2009
+ }
2010
+ outro(`Pulled ${remote.secretCount} variables from ${project.githubRepo} / ${envSlug} (v${remote.version}) into ${target}.`);
2011
+ }
2012
+ async function login(args) {
2013
+ intro(`VaultEnv CLI ${VERSION}`);
2014
+ const base = apiBase();
2015
+ const started = await request(
2016
+ "/api/auth/cli/start",
2017
+ {
2018
+ method: "POST",
2019
+ base,
2020
+ token: null,
2021
+ body: { deviceName: `${os2.hostname()} (${process.platform})` }
2022
+ }
2023
+ );
2024
+ const approvalUrl = new URL(started.url);
2025
+ const apiUrl = new URL(base);
2026
+ approvalUrl.protocol = apiUrl.protocol;
2027
+ approvalUrl.host = apiUrl.host;
2028
+ note(`${approvalUrl.toString()}
2029
+
2030
+ Device code: ${started.code}`, "Approve this device");
2031
+ if (!hasFlag(args, "no-open")) openBrowser(approvalUrl.toString());
2032
+ const waiting = spinner();
2033
+ waiting.start("Waiting for browser approval");
2034
+ let sessionToken = null;
2035
+ const deadline = Date.now() + 10 * 6e4;
2036
+ while (Date.now() < deadline) {
2037
+ const status = await request(
2038
+ `/api/auth/cli/status?code=${encodeURIComponent(started.code)}&pollToken=${encodeURIComponent(started.pollToken)}`,
2039
+ { base, token: null }
2040
+ );
2041
+ if (status.status === "approved" && status.token) {
2042
+ sessionToken = status.token;
2043
+ break;
2044
+ }
2045
+ if (status.status === "expired" || status.status === "not_found") {
2046
+ waiting.stop("Device request expired.");
2047
+ fail("Run `vaultenv login` again for a fresh link.");
2048
+ }
2049
+ await sleep(2e3);
2050
+ }
2051
+ if (!sessionToken) {
2052
+ waiting.stop("Timed out.");
2053
+ fail("No approval after ten minutes. Run `vaultenv login` again.");
2054
+ }
2055
+ waiting.stop("Device approved.");
2056
+ const me = await getMe(sessionToken);
2057
+ saveCredentials({
2058
+ apiUrl: base,
2059
+ token: sessionToken,
2060
+ user: { id: me.user.id, email: me.user.email, name: me.user.name }
2061
+ });
2062
+ outro(`Logged in as ${me.user.email}`);
2063
+ if (!hasFlag(args, "no-unlock")) {
2064
+ await unlockIdentity();
2065
+ note("Vault identity unlocked on this machine. Use `vaultenv logout` to remove it.", "Unlocked");
2066
+ }
2067
+ }
2068
+ async function logout() {
2069
+ const credentials = getCredentials();
2070
+ if (credentials) {
2071
+ try {
2072
+ await request("/api/auth/logout", { method: "POST", token: credentials.token });
2073
+ } catch {
2074
+ }
2075
+ }
2076
+ clearLocalAuth();
2077
+ outro("Logged out. Local credentials and vault identity removed.");
2078
+ }
2079
+ async function whoami() {
2080
+ const credentials = requireCredentials();
2081
+ const me = await getMe(credentials.token);
2082
+ const workspace = await getWorkspace(credentials.token);
2083
+ const config = readProjectConfig();
2084
+ const project = config ? workspace.projects.find((item) => item.id === config.projectId) : null;
2085
+ note(
2086
+ [
2087
+ `Account ${me.user.name} <${me.user.email}>`,
2088
+ `API ${apiBase()}`,
2089
+ `Workspace ${workspace.workspace.name}`,
2090
+ `Projects ${workspace.projects.length}`,
2091
+ `Linked ${project ? `${project.name} (${project.githubRepo})` : "none"}`,
2092
+ `Identity ${getIdentity() ? "unlocked on this machine" : "locked"}`
2093
+ ].join("\n"),
2094
+ "VaultEnv"
2095
+ );
2096
+ }
2097
+ async function initProject(args) {
2098
+ const credentials = requireCredentials();
2099
+ const me = await getMe(credentials.token);
2100
+ const workspace = await getWorkspace(credentials.token);
2101
+ let repo = flag(args, "repo") || detectGitRepo();
2102
+ if (!repo) {
2103
+ if (!process.stdin.isTTY) fail("No GitHub remote found. Pass --repo owner/name.");
2104
+ const answer = await text({
2105
+ message: "GitHub repository",
2106
+ placeholder: "owner/name",
2107
+ validate: (value) => value?.includes("/") ? void 0 : "Use owner/name."
2108
+ });
2109
+ if (isCancel(answer)) fail("Init cancelled.");
2110
+ repo = answer;
2111
+ }
2112
+ let project = workspace.projects.find(
2113
+ (item) => item.githubRepo.toLowerCase() === repo.toLowerCase()
2114
+ );
2115
+ if (!project) {
2116
+ const canCreate = hasFlag(args, "create") || hasFlag(args, "yes");
2117
+ if (!canCreate) {
2118
+ if (!process.stdin.isTTY) fail("Project not found. Add --create to create it.");
2119
+ const create = await confirm({
2120
+ message: `No VaultEnv project matches ${repo}. Create it now?`
2121
+ });
2122
+ if (isCancel(create) || !create) fail("Init cancelled.");
2123
+ }
2124
+ const projectKey2 = generateProjectMasterKey();
2125
+ const keyFingerprint = await computeKeyFingerprint(projectKey2);
2126
+ const wrappedProjectKey = await wrapProjectKeyForTeammate(projectKey2, me.user.publicKey);
2127
+ const repoName = repo.split("/")[1] || "project";
2128
+ const defaultBranch = flag(args, "branch") || "main";
2129
+ const created = await request(
2130
+ "/api/v1/projects",
2131
+ {
2132
+ method: "POST",
2133
+ token: credentials.token,
2134
+ body: {
2135
+ name: repoName,
2136
+ slug: repoName,
2137
+ githubRepo: repo,
2138
+ defaultBranch,
2139
+ framework: "Next.js",
2140
+ visibility: "private",
2141
+ branchMapping: {
2142
+ development: "dev",
2143
+ staging: "staging",
2144
+ production: defaultBranch
2145
+ },
2146
+ keyFingerprint,
2147
+ wrappedProjectKey
2148
+ }
2149
+ }
2150
+ );
2151
+ project = created.snapshot.projects.find((item) => item.id === created.projectId);
2152
+ if (!project) fail("Project was created but could not be read back.");
2153
+ }
2154
+ writeProjectConfig({
2155
+ projectId: project.id,
2156
+ projectSlug: project.slug,
2157
+ githubRepo: project.githubRepo,
2158
+ environments: Object.fromEntries(project.environments.map((environment) => [environment.slug, environment.slug]))
2159
+ });
2160
+ const ignored = ensureGitignore();
2161
+ note(
2162
+ [
2163
+ `Project ${project.name}`,
2164
+ `Repository ${project.githubRepo}`,
2165
+ `Environments ${project.environments.map((environment) => environment.slug).join(", ")}`,
2166
+ `Config .vaultenv.json${ignored ? " (+ .gitignore)" : ""}`,
2167
+ "",
2168
+ "Next: `vaultenv import .env.production --env production`"
2169
+ ].join("\n"),
2170
+ "Linked"
2171
+ );
2172
+ outro("Project ready.");
2173
+ }
2174
+ async function selectProject(workspace, message = "Choose a project") {
2175
+ if (workspace.projects.length === 0) {
2176
+ fail("No projects yet. Run `vaultenv init --create` or create one in the dashboard.");
2177
+ }
2178
+ if (workspace.projects.length === 1) return workspace.projects[0];
2179
+ if (!process.stdin.isTTY) {
2180
+ fail("Multiple projects found. Pass a project slug, e.g. `vaultenv use my-project`.");
2181
+ }
2182
+ const choice = await select({
2183
+ message,
2184
+ options: workspace.projects.map((project2) => ({
2185
+ value: project2.id,
2186
+ label: project2.name,
2187
+ hint: `${project2.githubRepo} \xB7 ${project2.environments.map((environment) => environment.slug).join(", ")}`
2188
+ }))
2189
+ });
2190
+ if (isCancel(choice)) fail("Selection cancelled.");
2191
+ const project = workspace.projects.find((item) => item.id === choice);
2192
+ if (!project) fail("Project not found.");
2193
+ return project;
2194
+ }
2195
+ async function projects() {
2196
+ const credentials = requireCredentials();
2197
+ const workspace = await getWorkspace(credentials.token);
2198
+ const config = readProjectConfig();
2199
+ if (workspace.projects.length === 0) {
2200
+ outro("No projects yet. Run `vaultenv init --create` or create one in the dashboard.");
2201
+ return;
2202
+ }
2203
+ note(
2204
+ workspace.projects.map((project) => {
2205
+ const current = project.id === config?.projectId ? " *" : "";
2206
+ return `${current}${project.slug} ${project.githubRepo} [${project.environments.map((environment) => environment.slug).join(", ")}]`;
2207
+ }).join("\n"),
2208
+ `${workspace.workspace.name} / projects`
2209
+ );
2210
+ outro("Use `vaultenv use <slug>` to link one to this folder.");
2211
+ }
2212
+ async function linkProject(args) {
2213
+ const credentials = requireCredentials();
2214
+ const workspace = await getWorkspace(credentials.token);
2215
+ const wanted = args.positionals[0];
2216
+ const project = wanted ? workspace.projects.find(
2217
+ (item) => item.slug === wanted || item.id === wanted || item.name.toLowerCase() === wanted.toLowerCase()
2218
+ ) : await selectProject(workspace);
2219
+ if (!project) fail(`No project matches "${wanted}".`);
2220
+ writeProjectConfig({
2221
+ projectId: project.id,
2222
+ projectSlug: project.slug,
2223
+ githubRepo: project.githubRepo,
2224
+ environments: Object.fromEntries(project.environments.map((environment) => [environment.slug, environment.slug]))
2225
+ });
2226
+ outro(`Linked ${project.name} (${project.githubRepo}) to this folder.`);
2227
+ }
2228
+ async function pushCommand(args, importMode) {
2229
+ if (process.env.VAULTENV_TOKEN || flag(args, "token")) {
2230
+ fail("Service tokens are read-only. Run `vaultenv login` on this machine to import.");
2231
+ }
2232
+ const fileFlag = flag(args, "file");
2233
+ const envFlag = flag(args, "env");
2234
+ const first = args.positionals[0];
2235
+ let file = fileFlag;
2236
+ let envSlug = envFlag || "production";
2237
+ if (importMode) {
2238
+ file = file || (first && first.includes(".env") ? first : void 0);
2239
+ if (!envFlag && file?.startsWith(".env.")) envSlug = file.slice(5);
2240
+ } else {
2241
+ envSlug = envFlag || first || "production";
2242
+ }
2243
+ file = file || envFileFor(envSlug);
2244
+ intro("VaultEnv import");
2245
+ await pushFile(file, envSlug);
2246
+ }
2247
+ async function pullCommand(args, exportMode) {
2248
+ const first = args.positionals[0];
2249
+ const envSlug = flag(args, "env") || (exportMode ? first : first) || "production";
2250
+ const out = flag(args, "out");
2251
+ const serviceToken = flag(args, "token") || process.env.VAULTENV_TOKEN;
2252
+ const serviceKey = flag(args, "key") || process.env.VAULTENV_KEY;
2253
+ intro("VaultEnv export");
2254
+ await pullEnv(
2255
+ envSlug,
2256
+ out,
2257
+ hasFlag(args, "yes") || hasFlag(args, "force"),
2258
+ serviceToken,
2259
+ serviceKey
2260
+ );
2261
+ }
2262
+ function help() {
2263
+ console.log(`VaultEnv CLI ${VERSION}
2264
+
2265
+ Usage:
2266
+ vaultenv login [--no-open] [--no-unlock] Approve this machine in the browser
2267
+ vaultenv logout Revoke the session and remove local keys
2268
+ vaultenv unlock Decrypt your key backup into this machine
2269
+ vaultenv whoami Show account, workspace and linked project
2270
+ vaultenv init [--create] [--repo owner/name] [--branch main]
2271
+ Link this git repository to a VaultEnv project
2272
+ vaultenv projects List projects
2273
+ vaultenv use [slug] Choose the project for this folder
2274
+ vaultenv import [file] [--env production] Encrypt and upload a .env file
2275
+ vaultenv push [env] [--file .env] Alias for import using .env.<env>
2276
+ vaultenv export [env] [--out .env.prod] Download and decrypt a vault environment
2277
+ vaultenv pull [env] [--out .env.prod] Alias for export
2278
+ vaultenv export [env] --token vlt_ci_... --key vlt_key_...
2279
+ Decrypt with a read-only CI service token
2280
+ vaultenv --help Show this help
2281
+
2282
+ Environment:
2283
+ VAULTENV_API_URL API origin (default https://env-vault.fkodelabs.com)
2284
+ VAULTENV_CONFIG_DIR Local credentials directory (default ~/.vaultenv)
2285
+ VAULTENV_PASSPHRASE Vault passphrase for non-interactive shells
2286
+ VAULTENV_TOKEN Read-only CI service token for export/pull
2287
+ VAULTENV_KEY Project VAULT_KEY for service-token export
2288
+ `);
2289
+ }
2290
+ async function main() {
2291
+ const args = parseArgs(process.argv.slice(2));
2292
+ if (flag(args, "api")) process.env.VAULTENV_API_URL = flag(args, "api");
2293
+ try {
2294
+ switch (args.command) {
2295
+ case "login":
2296
+ await login(args);
2297
+ break;
2298
+ case "logout":
2299
+ await logout();
2300
+ break;
2301
+ case "unlock":
2302
+ await unlockIdentity();
2303
+ outro("Vault identity unlocked on this machine.");
2304
+ break;
2305
+ case "whoami":
2306
+ await whoami();
2307
+ break;
2308
+ case "init":
2309
+ await initProject(args);
2310
+ break;
2311
+ case "projects":
2312
+ await projects();
2313
+ break;
2314
+ case "use":
2315
+ await linkProject(args);
2316
+ break;
2317
+ case "push":
2318
+ await pushCommand(args, false);
2319
+ break;
2320
+ case "import":
2321
+ await pushCommand(args, true);
2322
+ break;
2323
+ case "pull":
2324
+ await pullCommand(args, false);
2325
+ break;
2326
+ case "export":
2327
+ await pullCommand(args, true);
2328
+ break;
2329
+ case "help":
2330
+ case "--help":
2331
+ case "-h":
2332
+ help();
2333
+ break;
2334
+ case "version":
2335
+ case "--version":
2336
+ case "-v":
2337
+ console.log(VERSION);
2338
+ break;
2339
+ default:
2340
+ help();
2341
+ process.exitCode = 1;
2342
+ }
2343
+ } catch (error) {
2344
+ if (error instanceof ApiError) {
2345
+ if (error.status === 401) {
2346
+ if (process.env.VAULTENV_TOKEN || flag(args, "token")) {
2347
+ fail("Service token is invalid or revoked. Create a new token in the dashboard.");
2348
+ }
2349
+ fail("Your session expired. Run `vaultenv login` again.");
2350
+ }
2351
+ fail(error.message);
2352
+ }
2353
+ fail(error instanceof Error ? error.message : "Unexpected error.");
2354
+ }
2355
+ }
2356
+ void main();