@e-n-v/env 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4098 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (all) => {
9
+ let target = {};
10
+ for (var name in all) __defProp(target, name, {
11
+ get: all[name],
12
+ enumerable: true
13
+ });
14
+ return target;
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
18
+ key = keys[i];
19
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
20
+ get: ((k) => from[k]).bind(null, key),
21
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
22
+ });
23
+ }
24
+ return to;
25
+ };
26
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
27
+ value: mod,
28
+ enumerable: true
29
+ }) : target, mod));
30
+
31
+ //#endregion
32
+ let node_fs = require("node:fs");
33
+ node_fs = __toESM(node_fs);
34
+ let node_path = require("node:path");
35
+ node_path = __toESM(node_path);
36
+ let node_fs_promises = require("node:fs/promises");
37
+ node_fs_promises = __toESM(node_fs_promises);
38
+ let fs = require("fs");
39
+ fs = __toESM(fs);
40
+ let zod = require("zod");
41
+ zod = __toESM(zod);
42
+ let zod_v4_core = require("zod/v4/core");
43
+ zod_v4_core = __toESM(zod_v4_core);
44
+ let node_process = require("node:process");
45
+ node_process = __toESM(node_process);
46
+ let __clack_core = require("@clack/core");
47
+ __clack_core = __toESM(__clack_core);
48
+ let node_url = require("node:url");
49
+ node_url = __toESM(node_url);
50
+ let picocolors = require("picocolors");
51
+ picocolors = __toESM(picocolors);
52
+ let node_readline = require("node:readline");
53
+ node_readline = __toESM(node_readline);
54
+
55
+ //#region ../files/src/utils.ts
56
+ function normalizeContent(content) {
57
+ return content.replace(/\r\n/g, "\n");
58
+ }
59
+ function splitLines(content) {
60
+ return content === "" ? [] : content.split("\n");
61
+ }
62
+ function validateKey(key) {
63
+ const trimmed = key.trim();
64
+ if (!trimmed) throw new TypeError("Environment variable name cannot be empty");
65
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(trimmed)) throw new TypeError(`Invalid environment variable name: ${trimmed}`);
66
+ return trimmed;
67
+ }
68
+ function parseAssignmentEndingAt(lines, endIndex) {
69
+ const lastLine = lines[endIndex];
70
+ if (typeof lastLine !== "string" || isSkippableLine(lastLine)) return null;
71
+ const block = [];
72
+ let start = endIndex;
73
+ while (start >= 0) {
74
+ const currentLine = lines[start];
75
+ if (typeof currentLine !== "string") break;
76
+ block.unshift(currentLine);
77
+ if (containsAssignmentOperator(currentLine)) {
78
+ const parsed = tryParseAssignmentBlock(block);
79
+ if (!parsed) return null;
80
+ return {
81
+ ...parsed,
82
+ startIndex: start,
83
+ endIndex
84
+ };
85
+ }
86
+ start -= 1;
87
+ }
88
+ return null;
89
+ }
90
+ function isSkippableLine(line) {
91
+ const trimmed = line.trim();
92
+ return trimmed.length === 0 || trimmed.startsWith("#");
93
+ }
94
+ function containsAssignmentOperator(line) {
95
+ const trimmed = line.trimStart();
96
+ if (trimmed.length === 0 || trimmed.startsWith("#")) return false;
97
+ const commentIndex = trimmed.indexOf("#");
98
+ return (commentIndex === -1 ? trimmed : trimmed.slice(0, commentIndex)).includes("=");
99
+ }
100
+ function tryParseAssignmentBlock(blockLines) {
101
+ if (blockLines.length === 0) return null;
102
+ const firstLine = blockLines[0];
103
+ const leadingMatch = firstLine.match(/^\s*/);
104
+ const leading = leadingMatch ? leadingMatch[0] : "";
105
+ let remainder = firstLine.slice(leading.length);
106
+ if (remainder.length === 0 || remainder.startsWith("#")) return null;
107
+ let exportPrefix = "";
108
+ if (remainder.startsWith("export")) {
109
+ const afterExport = remainder.slice(6);
110
+ if (/^\s/.test(afterExport)) {
111
+ const spacingMatch = afterExport.match(/^\s+/);
112
+ const spacing = spacingMatch ? spacingMatch[0] : " ";
113
+ exportPrefix = `export${spacing}`;
114
+ remainder = afterExport.slice(spacing.length);
115
+ }
116
+ }
117
+ const equalsIndex = remainder.indexOf("=");
118
+ if (equalsIndex === -1) return null;
119
+ const key = validateKey(remainder.slice(0, equalsIndex).trim());
120
+ const parsedValue = parseValueSource([remainder.slice(equalsIndex + 1).replace(/^\s+/, ""), ...blockLines.slice(1)].join("\n"));
121
+ if (!parsedValue) return null;
122
+ const trailingTrimmed = parsedValue.trailing.trim();
123
+ if (trailingTrimmed.length > 0 && !trailingTrimmed.startsWith("#")) return null;
124
+ return {
125
+ key,
126
+ value: parsedValue.value,
127
+ leading,
128
+ exportPrefix,
129
+ trailing: parsedValue.trailing,
130
+ lines: [...blockLines]
131
+ };
132
+ }
133
+ function parseValueSource(source) {
134
+ if (source.length === 0) return {
135
+ value: "",
136
+ trailing: ""
137
+ };
138
+ const firstChar = source[0];
139
+ if (firstChar === "\"") return parseDoubleQuotedValue(source);
140
+ if (firstChar === "'") return parseSingleQuotedValue(source);
141
+ if (source.includes("\n")) return null;
142
+ const commentIndex = source.indexOf(" #");
143
+ const raw = commentIndex === -1 ? source : source.slice(0, commentIndex);
144
+ const trailing = commentIndex === -1 ? source.slice(raw.length) : source.slice(commentIndex);
145
+ return {
146
+ value: raw.trim(),
147
+ trailing
148
+ };
149
+ }
150
+ function parseDoubleQuotedValue(source) {
151
+ let value = "";
152
+ let escaping = false;
153
+ for (let i = 1; i < source.length; i += 1) {
154
+ const char = source[i] ?? "";
155
+ if (escaping) {
156
+ switch (char) {
157
+ case "n":
158
+ value += "\n";
159
+ break;
160
+ case "r":
161
+ value += "\r";
162
+ break;
163
+ case "t":
164
+ value += " ";
165
+ break;
166
+ case "\"":
167
+ value += "\"";
168
+ break;
169
+ case "\\":
170
+ value += "\\";
171
+ break;
172
+ default:
173
+ value += char;
174
+ break;
175
+ }
176
+ escaping = false;
177
+ continue;
178
+ }
179
+ if (char === "\\") {
180
+ escaping = true;
181
+ continue;
182
+ }
183
+ if (char === "\"") {
184
+ const trailing = source.slice(i + 1);
185
+ return {
186
+ value,
187
+ trailing
188
+ };
189
+ }
190
+ if (char === "\n") {
191
+ value += "\n";
192
+ continue;
193
+ }
194
+ value += char;
195
+ }
196
+ return null;
197
+ }
198
+ function parseSingleQuotedValue(source) {
199
+ let value = "";
200
+ for (let i = 1; i < source.length; i += 1) {
201
+ const char = source[i] ?? "";
202
+ if (char === "'") {
203
+ const trailing = source.slice(i + 1);
204
+ return {
205
+ value,
206
+ trailing
207
+ };
208
+ }
209
+ if (char === "\n") {
210
+ value += "\n";
211
+ continue;
212
+ }
213
+ value += char;
214
+ }
215
+ return null;
216
+ }
217
+
218
+ //#endregion
219
+ //#region ../files/src/get.ts
220
+ function get(content, arg) {
221
+ const lines = splitLines(normalizeContent(content));
222
+ if (typeof arg === "undefined") {
223
+ const map = scanAll(lines);
224
+ return Object.fromEntries(map);
225
+ }
226
+ if (typeof arg === "string") return scanForSingle(lines, arg);
227
+ const normalizedTargets = Array.from(new Set(arg.map((name) => validateKey(name))));
228
+ const lookup = scanForMany(lines, new Set(normalizedTargets));
229
+ const ordered = normalizedTargets.map((key) => [key, lookup.get(key)]);
230
+ return Object.fromEntries(ordered);
231
+ }
232
+ function scanAll(lines) {
233
+ const result = /* @__PURE__ */ new Map();
234
+ iterateAssignments(lines, (assignment) => {
235
+ if (!result.has(assignment.key)) result.set(assignment.key, assignment.value);
236
+ });
237
+ return result;
238
+ }
239
+ function scanForSingle(lines, target) {
240
+ const name = validateKey(target);
241
+ let found;
242
+ iterateAssignments(lines, (assignment) => {
243
+ if (assignment.key === name) {
244
+ found = assignment.value;
245
+ return true;
246
+ }
247
+ });
248
+ return found;
249
+ }
250
+ function scanForMany(lines, targets) {
251
+ const normalizedTargets = /* @__PURE__ */ new Set();
252
+ for (const target of targets) normalizedTargets.add(validateKey(target));
253
+ const found = /* @__PURE__ */ new Map();
254
+ const remaining = new Set(normalizedTargets);
255
+ iterateAssignments(lines, (assignment) => {
256
+ if (!remaining.has(assignment.key) || found.has(assignment.key)) return;
257
+ found.set(assignment.key, assignment.value);
258
+ remaining.delete(assignment.key);
259
+ if (remaining.size === 0) return true;
260
+ });
261
+ return found;
262
+ }
263
+ function iterateAssignments(lines, callback) {
264
+ for (let i = lines.length - 1; i >= 0;) {
265
+ const parsed = parseAssignmentEndingAt(lines, i);
266
+ if (!parsed) {
267
+ i -= 1;
268
+ continue;
269
+ }
270
+ if (callback(parsed) === true) return;
271
+ i = parsed.startIndex - 1;
272
+ }
273
+ }
274
+
275
+ //#endregion
276
+ //#region ../files/src/set.ts
277
+ function set(content, arg, value) {
278
+ const normalized = normalizeContent(content);
279
+ const lines = splitLines(normalized);
280
+ const entries = normalizeWriteArguments(arg, value);
281
+ if (entries.length === 0) return ensureTrailingNewline(normalized);
282
+ const replacements = new Map(entries);
283
+ const touched = /* @__PURE__ */ new Set();
284
+ for (let i = lines.length - 1; i >= 0;) {
285
+ if (replacements.size === 0) break;
286
+ const parsed = parseAssignmentEndingAt(lines, i);
287
+ if (!parsed) {
288
+ i -= 1;
289
+ continue;
290
+ }
291
+ const { key, startIndex, endIndex, leading, exportPrefix, trailing, value: currentValue } = parsed;
292
+ const nextValue = replacements.get(key);
293
+ if (typeof nextValue === "undefined" || touched.has(key)) {
294
+ i = startIndex - 1;
295
+ continue;
296
+ }
297
+ if (nextValue === currentValue) {
298
+ touched.add(key);
299
+ replacements.delete(key);
300
+ i = startIndex - 1;
301
+ continue;
302
+ }
303
+ const block = buildAssignmentLines(key, nextValue, {
304
+ leading,
305
+ exportPrefix,
306
+ trailing
307
+ });
308
+ lines.splice(startIndex, endIndex - startIndex + 1, ...block);
309
+ touched.add(key);
310
+ replacements.delete(key);
311
+ i = startIndex - 1;
312
+ }
313
+ for (const [key, val] of entries) {
314
+ if (touched.has(key)) continue;
315
+ const block = buildAssignmentLines(key, val);
316
+ const insertIndex = lines.length > 0 && lines[lines.length - 1] === "" ? lines.length - 1 : lines.length;
317
+ lines.splice(insertIndex, 0, ...block);
318
+ touched.add(key);
319
+ }
320
+ return ensureTrailingNewline(lines.join("\n"));
321
+ }
322
+ function ensureTrailingNewline(content) {
323
+ if (content.length === 0) return "";
324
+ if (!content.endsWith("\n")) return `${content}\n`;
325
+ return content;
326
+ }
327
+ function isObjectRecord(value) {
328
+ return typeof value === "object" && value !== null && !Array.isArray(value);
329
+ }
330
+ function normalizeWriteArguments(arg, value) {
331
+ if (typeof arg === "string") {
332
+ if (typeof value === "undefined") throw new TypeError(`Value for variable "${arg}" must be provided`);
333
+ return [[validateKey(arg), formatValueInput(value)]];
334
+ }
335
+ if (!isObjectRecord(arg)) throw new TypeError("Argument must be a string name or an object of key-value pairs");
336
+ const entries = [];
337
+ for (const [key, rawValue] of Object.entries(arg)) {
338
+ if (typeof rawValue === "undefined") throw new TypeError(`Value for variable "${key}" must be provided`);
339
+ entries.push([validateKey(key), formatValueInput(rawValue)]);
340
+ }
341
+ return entries;
342
+ }
343
+ function formatValueInput(value) {
344
+ if (typeof value === "bigint") return value.toString();
345
+ return String(value);
346
+ }
347
+ function serializeValue(value) {
348
+ const normalized = value.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
349
+ if (!(normalized.length === 0 || /[\s"'\\#]/.test(normalized) || normalized.includes("\n"))) return normalized;
350
+ let result = "\"";
351
+ for (const char of normalized) {
352
+ if (char === "\"") {
353
+ result += "\\\"";
354
+ continue;
355
+ }
356
+ if (char === "\\") {
357
+ result += "\\\\";
358
+ continue;
359
+ }
360
+ if (char === "\n") {
361
+ result += "\n";
362
+ continue;
363
+ }
364
+ result += char;
365
+ }
366
+ result += "\"";
367
+ return result;
368
+ }
369
+ function buildAssignmentLines(key, value, style = {}) {
370
+ const leading = style.leading ?? "";
371
+ const exportPrefix = style.exportPrefix ?? "";
372
+ const trailing = style.trailing ?? "";
373
+ const segments = serializeValue(value).split("\n");
374
+ return segments.map((segment, index) => {
375
+ if (index === 0) return `${leading}${exportPrefix}${key}=${segment}${segments.length === 1 ? trailing : ""}`;
376
+ if (index === segments.length - 1 && trailing && segments.length > 1) return `${segment}${trailing}`;
377
+ return segment;
378
+ });
379
+ }
380
+
381
+ //#endregion
382
+ //#region ../files/src/EnvSource.ts
383
+ var EnvSource = class {
384
+ filePath;
385
+ constructor(filePath) {
386
+ this.filePath = (0, node_path.resolve)(process.cwd(), filePath);
387
+ }
388
+ readSync(arg) {
389
+ const content = this.readContentSync();
390
+ if (typeof arg === "undefined") return get(content);
391
+ if (typeof arg === "string") return get(content, arg);
392
+ return get(content, arg);
393
+ }
394
+ async read(arg) {
395
+ const content = await this.readContent();
396
+ if (typeof arg === "undefined") return get(content);
397
+ if (typeof arg === "string") return get(content, arg);
398
+ return get(content, arg);
399
+ }
400
+ writeSync(arg, value) {
401
+ const originalContent = this.readContentSync();
402
+ let nextContent;
403
+ if (typeof arg === "string") nextContent = set(originalContent, arg, value);
404
+ else nextContent = set(originalContent, arg);
405
+ if (nextContent === originalContent) return;
406
+ this.ensureDirectorySync();
407
+ (0, node_fs.writeFileSync)(this.filePath, nextContent, "utf8");
408
+ }
409
+ async write(arg, value) {
410
+ const originalContent = await this.readContent();
411
+ let nextContent;
412
+ if (typeof arg === "string") nextContent = set(originalContent, arg, value);
413
+ else nextContent = set(originalContent, arg);
414
+ if (nextContent === originalContent) return;
415
+ await this.ensureDirectory();
416
+ await node_fs.promises.writeFile(this.filePath, nextContent, "utf8");
417
+ }
418
+ readContentSync() {
419
+ try {
420
+ return (0, node_fs.readFileSync)(this.filePath, "utf8").replace(/\r\n/g, "\n");
421
+ } catch (error) {
422
+ if (error.code === "ENOENT") return "";
423
+ throw error;
424
+ }
425
+ }
426
+ async readContent() {
427
+ try {
428
+ return (await node_fs.promises.readFile(this.filePath, "utf8")).replace(/\r\n/g, "\n");
429
+ } catch (error) {
430
+ if (error.code === "ENOENT") return "";
431
+ throw error;
432
+ }
433
+ }
434
+ ensureDirectorySync() {
435
+ try {
436
+ (0, node_fs.mkdirSync)((0, node_path.dirname)(this.filePath), { recursive: true });
437
+ } catch (error) {
438
+ if (error.code !== "EEXIST") throw error;
439
+ }
440
+ }
441
+ async ensureDirectory() {
442
+ try {
443
+ await node_fs.promises.mkdir((0, node_path.dirname)(this.filePath), { recursive: true });
444
+ } catch (error) {
445
+ if (error.code !== "EEXIST") throw error;
446
+ }
447
+ }
448
+ };
449
+
450
+ //#endregion
451
+ //#region ../channels/src/channels/default/DefaultEnvChannel.ts
452
+ /**
453
+ * Default implementation of EnvChannel that works with .env files using envrw
454
+ */
455
+ var DefaultEnvChannel = class {
456
+ envSource;
457
+ /**
458
+ * Create a new DefaultEnvChannel
459
+ * @param filePath - Path to the .env file to manage
460
+ */
461
+ constructor(filePath) {
462
+ this.envSource = new EnvSource(filePath);
463
+ }
464
+ /**
465
+ * Get all environment variables
466
+ * @returns Promise that resolves to object containing all environment variable key-value pairs
467
+ */
468
+ async get() {
469
+ return await this.envSource.read();
470
+ }
471
+ /**
472
+ * Set multiple environment variables
473
+ * @param values - Object containing key-value pairs to set
474
+ * @returns Promise that resolves when the values have been set
475
+ */
476
+ async set(values) {
477
+ await this.envSource.write(values);
478
+ }
479
+ };
480
+
481
+ //#endregion
482
+ //#region ../channels/src/channels/dotenv/DotEnvChannel.ts
483
+ function isFileNotFound(error) {
484
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
485
+ }
486
+ function normalizeParsed(parsed) {
487
+ if (!parsed) return {};
488
+ const result = {};
489
+ for (const [key, value] of Object.entries(parsed)) {
490
+ if (typeof value === "undefined") continue;
491
+ result[key] = value;
492
+ }
493
+ return result;
494
+ }
495
+ var DotEnvChannel = class {
496
+ dotenv;
497
+ targetPath;
498
+ absolutePath;
499
+ encoding;
500
+ parseOptions;
501
+ envSource;
502
+ constructor(dotenv, defaultPath = ".env", getOptions = {}, parseOptions = {}) {
503
+ this.dotenv = dotenv;
504
+ this.targetPath = (typeof getOptions.path === "string" ? getOptions.path : void 0) ?? defaultPath;
505
+ this.absolutePath = (0, node_path.resolve)(process.cwd(), this.targetPath);
506
+ this.encoding = getOptions.encoding ?? "utf8";
507
+ this.parseOptions = { ...parseOptions };
508
+ this.envSource = new EnvSource(this.targetPath);
509
+ }
510
+ async get() {
511
+ try {
512
+ const content = await (0, node_fs_promises.readFile)(this.absolutePath, { encoding: this.encoding });
513
+ return normalizeParsed(this.dotenv.parse(content, this.parseOptions));
514
+ } catch (error) {
515
+ if (isFileNotFound(error)) return {};
516
+ throw error;
517
+ }
518
+ }
519
+ async set(values) {
520
+ await this.envSource.write(values);
521
+ const parsed = await this.get();
522
+ const mismatches = [];
523
+ for (const [key, expected] of Object.entries(values)) {
524
+ const actual = parsed[key];
525
+ if (actual !== expected) mismatches.push(`${key}=expected(${JSON.stringify(expected)}) actual(${JSON.stringify(actual)})`);
526
+ }
527
+ if (mismatches.length > 0) throw new Error(`Failed to correctly write values to ${this.targetPath}: ${mismatches.join(", ")}`);
528
+ }
529
+ getPrimaryPath() {
530
+ return this.targetPath;
531
+ }
532
+ clearCache() {}
533
+ };
534
+
535
+ //#endregion
536
+ //#region ../channels/src/channels/dotenvx/DotEnvXChannel.ts
537
+ /**
538
+ * Simple DotEnvX implementation of EnvChannel that wraps @dotenvx/dotenvx library
539
+ * This is just an API mapping wrapper without caching or complex state management
540
+ */
541
+ var DotEnvXChannel = class {
542
+ dotenvx;
543
+ getOptions;
544
+ setOptions;
545
+ defaultPath;
546
+ /**
547
+ * Create a new DotEnvXChannel
548
+ * @param dotenvx - The dotenvx instance to use
549
+ * @param defaultPath - Default path for env files
550
+ * @param getOptions - Options for get operations
551
+ * @param setOptions - Options for set operations
552
+ */
553
+ constructor(dotenvx, defaultPath = ".env", getOptions = {}, setOptions = {}) {
554
+ this.dotenvx = dotenvx;
555
+ this.defaultPath = defaultPath;
556
+ this.getOptions = getOptions;
557
+ this.setOptions = setOptions;
558
+ }
559
+ /**
560
+ * Get all environment variables
561
+ * @returns Promise that resolves to object containing all environment variable key-value pairs
562
+ */
563
+ async get() {
564
+ try {
565
+ return this.dotenvx.config({
566
+ processEnv: {},
567
+ quiet: true,
568
+ ignore: ["MISSING_ENV_FILE"],
569
+ path: this.defaultPath,
570
+ ...this.getOptions
571
+ }).parsed || {};
572
+ } catch {
573
+ return {};
574
+ }
575
+ }
576
+ /**
577
+ * Set multiple environment variables
578
+ * @param values - Object containing key-value pairs to set
579
+ * @returns Promise that resolves when the values have been set
580
+ */
581
+ async set(values) {
582
+ if (!(0, fs.existsSync)(this.defaultPath)) (0, fs.writeFileSync)(this.defaultPath, "", "utf8");
583
+ try {
584
+ const options = {
585
+ path: this.defaultPath,
586
+ ...this.setOptions
587
+ };
588
+ for (const [key, value] of Object.entries(values)) this.dotenvx.set(key, value, options);
589
+ } catch (error) {
590
+ throw new Error(`Failed to set environment variables: ${error}`);
591
+ }
592
+ }
593
+ /**
594
+ * Get the primary path being used for env files
595
+ * @returns The primary path
596
+ */
597
+ getPrimaryPath() {
598
+ return this.defaultPath;
599
+ }
600
+ /**
601
+ * Clear any cached data (no-op for this implementation since we don't cache)
602
+ */
603
+ clearCache() {}
604
+ };
605
+
606
+ //#endregion
607
+ //#region ../channels/src/channels/processenv/ProcessEnvChannel.ts
608
+ /**
609
+ * EnvChannel implementation that works with process.env
610
+ * This channel reads from and writes to the current process environment
611
+ */
612
+ var ProcessEnvChannel = class {
613
+ /**
614
+ * Get all environment variables from process.env
615
+ * @returns Promise that resolves to object containing all environment variable key-value pairs
616
+ */
617
+ async get() {
618
+ const env = {};
619
+ for (const [key, value] of Object.entries(process.env)) if (value !== void 0) env[key] = value;
620
+ return env;
621
+ }
622
+ /**
623
+ * Set multiple environment variables in process.env
624
+ * @param values - Object containing key-value pairs to set
625
+ * @returns Promise that resolves when the values have been set
626
+ */
627
+ async set(values) {
628
+ for (const [key, value] of Object.entries(values)) process.env[key] = value;
629
+ }
630
+ };
631
+
632
+ //#endregion
633
+ //#region ../channels/src/resolveChannel.ts
634
+ /**
635
+ * Resolve channel options into an EnvChannel instance
636
+ * @param options - The channel options to resolve
637
+ * @param defaultPath - Default path to use for env files (default: ".env")
638
+ * @returns An EnvChannel instance
639
+ */
640
+ function resolveChannel(options, defaultPath = ".env") {
641
+ if (options === void 0 || options === "default") return new DefaultEnvChannel(defaultPath);
642
+ if (options === "processenv") return new ProcessEnvChannel();
643
+ if (typeof options === "object" && options !== null) {
644
+ if ("dotenv" in options) {
645
+ const { dotenv, get: getOptions = {}, parse: parseOptions = {}, path } = options;
646
+ if (!dotenv) throw new Error("Dotenv instance is required for dotenv channel");
647
+ const resolvedPath = path ?? defaultPath;
648
+ const mergedGetOptions = { ...getOptions };
649
+ if (typeof mergedGetOptions.path !== "string") mergedGetOptions.path = resolvedPath;
650
+ return new DotEnvChannel(dotenv, resolvedPath, mergedGetOptions, parseOptions ?? {});
651
+ }
652
+ if ("dotenvx" in options) {
653
+ const { dotenvx, get: getOptions = {}, set: setOptions = {} } = options;
654
+ if (!dotenvx) throw new Error("DotEnvX instance is required for dotenvx channel");
655
+ return new DotEnvXChannel(dotenvx, defaultPath, getOptions, setOptions);
656
+ }
657
+ if ("process" in options) {
658
+ if (options.process && typeof options.process === "object" && "env" in options.process) return new ProcessEnvChannel();
659
+ throw new Error("Invalid process object provided to channel config");
660
+ }
661
+ if ("name" in options) if (options.name === "default") return new DefaultEnvChannel(defaultPath);
662
+ else if (options.name === "processenv") return new ProcessEnvChannel();
663
+ else throw new Error(`Unknown channel name: ${options.name}`);
664
+ }
665
+ throw new Error(`Invalid channel options: ${options}`);
666
+ }
667
+
668
+ //#endregion
669
+ //#region ../core/src/schemas/EnvVarSchemaBase.ts
670
+ var EnvVarSchemaBase = class {
671
+ required;
672
+ default;
673
+ description;
674
+ process;
675
+ constructor(input) {
676
+ this.required = input?.required ?? true;
677
+ this.default = input?.default;
678
+ this.description = input?.description;
679
+ this.process = input.process;
680
+ }
681
+ };
682
+
683
+ //#endregion
684
+ //#region ../core/src/processing/processors.ts
685
+ /**
686
+ * Default processors for environment variable types.
687
+ * Each processor factory returns a function that takes a value and returns T | undefined.
688
+ * Returns undefined for empty/null values, throws descriptive errors for invalid values.
689
+ */
690
+ /**
691
+ * Create a string processor - pass through as-is
692
+ */
693
+ const stringProcessor = () => (value) => {
694
+ if (typeof value !== "string") throw new Error("Value must be a string");
695
+ return value === "" ? void 0 : value;
696
+ };
697
+ /**
698
+ * Create a number processor using parseFloat
699
+ */
700
+ const numberProcessor = () => (value) => {
701
+ if (typeof value !== "string") throw new Error("Value must be a string");
702
+ const trimmed = value.trim();
703
+ if (trimmed === "") return;
704
+ const parsed = parseFloat(trimmed);
705
+ if (isNaN(parsed)) throw new Error(`"${value}" is not a valid number`);
706
+ return parsed;
707
+ };
708
+ /**
709
+ * Create a boolean processor from string representation
710
+ */
711
+ const booleanProcessor = () => (value) => {
712
+ if (typeof value !== "string") throw new Error("Value must be a string");
713
+ const trimmed = value.trim().toLowerCase();
714
+ if (trimmed === "") return;
715
+ if (trimmed === "true" || trimmed === "1" || trimmed === "yes" || trimmed === "on") return true;
716
+ if (trimmed === "false" || trimmed === "0" || trimmed === "no" || trimmed === "off") return false;
717
+ throw new Error(`"${value}" is not a valid boolean. Use: true/false, 1/0, yes/no, or on/off`);
718
+ };
719
+ /**
720
+ * Create an enum processor that validates values against allowed options
721
+ */
722
+ const enumProcessor = (allowedValues) => (value) => {
723
+ if (typeof value !== "string") throw new Error("Value must be a string");
724
+ const trimmed = value.trim();
725
+ if (trimmed === "") return;
726
+ if (!allowedValues.includes(trimmed)) throw new Error(`"${value}" is not a valid option. Must be one of: ${allowedValues.join(", ")}`);
727
+ return trimmed;
728
+ };
729
+ /**
730
+ * Default processors map for each environment variable type
731
+ */
732
+ const processors = {
733
+ string: stringProcessor,
734
+ number: numberProcessor,
735
+ boolean: booleanProcessor,
736
+ enum: enumProcessor
737
+ };
738
+
739
+ //#endregion
740
+ //#region ../core/src/schemas/typed/BooleanEnvVarSchema.ts
741
+ var BooleanEnvVarSchema = class extends EnvVarSchemaBase {
742
+ type = "boolean";
743
+ constructor(input = {}) {
744
+ super({
745
+ ...input,
746
+ process: input.process ?? processors.boolean()
747
+ });
748
+ }
749
+ };
750
+
751
+ //#endregion
752
+ //#region ../core/src/schemas/typed/EnumEnvVarSchema.ts
753
+ var EnumEnvVarSchema = class extends EnvVarSchemaBase {
754
+ type = "enum";
755
+ values;
756
+ constructor(input) {
757
+ super({
758
+ ...input,
759
+ process: input.process ?? processors.enum(input.values)
760
+ });
761
+ this.values = input.values;
762
+ }
763
+ };
764
+
765
+ //#endregion
766
+ //#region ../core/src/schemas/typed/NumberEnvVarSchema.ts
767
+ var NumberEnvVarSchema = class extends EnvVarSchemaBase {
768
+ type = "number";
769
+ constructor(input = {}) {
770
+ super({
771
+ ...input,
772
+ process: input.process ?? processors.number()
773
+ });
774
+ }
775
+ };
776
+
777
+ //#endregion
778
+ //#region ../core/src/schemas/typed/StringEnvVarSchema.ts
779
+ var StringEnvVarSchema = class extends EnvVarSchemaBase {
780
+ type = "string";
781
+ secret;
782
+ constructor(input = {}) {
783
+ super({
784
+ ...input,
785
+ process: input.process ?? processors.string()
786
+ });
787
+ this.secret = input.secret;
788
+ }
789
+ };
790
+
791
+ //#endregion
792
+ //#region ../core/src/schemas/EnvVarSchema.ts
793
+ /**
794
+ * Type guard to check if a value is a EnvVarSchema instance
795
+ */
796
+ function isEnvVarSchema(value) {
797
+ return value instanceof StringEnvVarSchema || value instanceof NumberEnvVarSchema || value instanceof BooleanEnvVarSchema || value instanceof EnumEnvVarSchema;
798
+ }
799
+
800
+ //#endregion
801
+ //#region ../core/src/processing/preprocessors.ts
802
+ const defaultBooleanPreprocessorOptions = {
803
+ true: [
804
+ "on",
805
+ "enabled",
806
+ "active",
807
+ "yes"
808
+ ],
809
+ false: [
810
+ "off",
811
+ "disabled",
812
+ "inactive",
813
+ "no"
814
+ ]
815
+ };
816
+ /**
817
+ * Create a string preprocessor - pass through unchanged
818
+ */
819
+ const stringPreprocessor = () => (value) => value;
820
+ /**
821
+ * Create a number preprocessor that strips commas and whitespace
822
+ */
823
+ const numberPreprocessor = () => (value) => {
824
+ try {
825
+ const cleaned = value.replace(/,/g, "").trim();
826
+ if (/^-?\d*\.?\d+$/.test(cleaned)) return cleaned;
827
+ } catch {}
828
+ return value;
829
+ };
830
+ /**
831
+ * Create a boolean preprocessor that normalizes common truthy/falsy phrases
832
+ */
833
+ const booleanPreprocessor = (options = defaultBooleanPreprocessorOptions) => {
834
+ const normalize = (candidate) => candidate.toLowerCase().trim();
835
+ const trueValues = new Set(options.true.map(normalize));
836
+ const falseValues = new Set(options.false.map(normalize));
837
+ for (const candidate of trueValues) if (falseValues.has(candidate)) throw new Error(`Boolean preprocessor option value "${candidate}" cannot map to both true and false`);
838
+ return (value) => {
839
+ try {
840
+ const cleaned = normalize(value);
841
+ if (trueValues.has(cleaned)) return true;
842
+ if (falseValues.has(cleaned)) return false;
843
+ } catch {}
844
+ return value;
845
+ };
846
+ };
847
+ /**
848
+ * Create an enum preprocessor - pass through unchanged
849
+ */
850
+ const enumPreprocessor = () => (value) => value;
851
+ /**
852
+ * Default preprocessors map for each environment variable type
853
+ */
854
+ const preprocessors = {
855
+ string: stringPreprocessor,
856
+ number: numberPreprocessor,
857
+ boolean: booleanPreprocessor,
858
+ enum: enumPreprocessor
859
+ };
860
+
861
+ //#endregion
862
+ //#region ../core/src/processing/Preprocessor.ts
863
+ const optionKeyMap = {
864
+ string: "string",
865
+ number: "number",
866
+ boolean: "boolean",
867
+ enum: "enum"
868
+ };
869
+ const explicitPreprocessorFactories = {
870
+ string: stringPreprocessor,
871
+ number: numberPreprocessor,
872
+ boolean: booleanPreprocessor,
873
+ enum: enumPreprocessor
874
+ };
875
+ function createDefaultPreprocessor(envVarType) {
876
+ switch (envVarType) {
877
+ case "number": return numberPreprocessor();
878
+ case "boolean": return booleanPreprocessor();
879
+ default: return;
880
+ }
881
+ }
882
+ function createExplicitPreprocessor(envVarType) {
883
+ const factory = explicitPreprocessorFactories[envVarType];
884
+ if (!factory) return;
885
+ return factory();
886
+ }
887
+ /**
888
+ * Resolve the effective preprocessor for a given environment variable type.
889
+ * Respects custom overrides and falls back to built-in defaults (number, boolean).
890
+ */
891
+ function resolvePreprocessor(envVarType, preprocessorOptions) {
892
+ if (envVarType === "boolean") {
893
+ const override = preprocessorOptions?.boolean;
894
+ if (override === void 0) return createDefaultPreprocessor(envVarType);
895
+ if (override === false) return;
896
+ if (override === true) return createExplicitPreprocessor(envVarType);
897
+ if (typeof override === "function") return override;
898
+ return booleanPreprocessor(override);
899
+ }
900
+ const key = optionKeyMap[envVarType];
901
+ const custom = preprocessorOptions?.[key];
902
+ if (custom === void 0) return createDefaultPreprocessor(envVarType);
903
+ if (custom === false) return;
904
+ if (custom === true) return createExplicitPreprocessor(envVarType);
905
+ return custom;
906
+ }
907
+
908
+ //#endregion
909
+ //#region ../converters/src/converters/zod/ZodV3Converter.ts
910
+ /**
911
+ * Zod v3 schema converter implementation
912
+ */
913
+ var ZodV3Converter = class {
914
+ applies(schema) {
915
+ return isZodV3Schema(schema);
916
+ }
917
+ convert(schema) {
918
+ return convertFromZodV3Schema(schema);
919
+ }
920
+ };
921
+ /**
922
+ * Check if a schema is a Zod v3 schema
923
+ */
924
+ function isZodV3Schema(schema) {
925
+ if (!schema || typeof schema !== "object") return false;
926
+ const candidate = schema;
927
+ return Boolean(candidate._def && !("_zod" in candidate) && (candidate._def.typeName || typeof candidate.parse === "function"));
928
+ }
929
+ /**
930
+ * Extract definition from Zod v3 schema
931
+ */
932
+ function getV3Def(schema) {
933
+ return schema._def || {};
934
+ }
935
+ /**
936
+ * Get the type name from a Zod v3 definition
937
+ */
938
+ function getV3TypeName(def) {
939
+ return def.typeName || "unknown";
940
+ }
941
+ /**
942
+ * Check if a type is a wrapper type that should be unwrapped
943
+ */
944
+ function isV3WrapperType(typeName) {
945
+ return [
946
+ "ZodOptional",
947
+ "ZodDefault",
948
+ "ZodEffects",
949
+ "ZodNullable",
950
+ "ZodNullish",
951
+ "ZodReadonly",
952
+ "ZodBranded",
953
+ "ZodCatch"
954
+ ].includes(typeName);
955
+ }
956
+ /**
957
+ * Get inner schema from wrapper
958
+ */
959
+ function getV3InnerSchema(def) {
960
+ return def.innerType || def.schema;
961
+ }
962
+ /**
963
+ * Get default value from definition
964
+ */
965
+ function getV3DefaultValue(def) {
966
+ if (def.defaultValue === void 0) return void 0;
967
+ return typeof def.defaultValue === "function" ? def.defaultValue() : def.defaultValue;
968
+ }
969
+ /**
970
+ * Extract enum values from schema
971
+ */
972
+ function extractV3EnumValues(def) {
973
+ if (!Array.isArray(def.values)) return void 0;
974
+ return def.values.map((v) => String(v));
975
+ }
976
+ /**
977
+ * Get description from schema
978
+ */
979
+ function getV3Description(schema, def) {
980
+ const directDesc = schema.description;
981
+ if (typeof directDesc === "string" && directDesc.length > 0) return directDesc;
982
+ if (typeof def.description === "string" && def.description.length > 0) return def.description;
983
+ }
984
+ /**
985
+ * Resolve environment variable type from schema
986
+ */
987
+ function resolveV3EnvVarType(schema) {
988
+ const def = getV3Def(schema);
989
+ switch (getV3TypeName(def)) {
990
+ case "ZodString": return "string";
991
+ case "ZodNumber": return "number";
992
+ case "ZodBoolean": return "boolean";
993
+ case "ZodEnum": return "enum";
994
+ default:
995
+ if (def.values) return "enum";
996
+ return "string";
997
+ }
998
+ }
999
+ function peelV3Schema(schema) {
1000
+ let current = schema;
1001
+ let required = true;
1002
+ let defaultValue = void 0;
1003
+ let description = void 0;
1004
+ for (let i = 0; i < 20; i++) {
1005
+ const def = getV3Def(current);
1006
+ const typeName = getV3TypeName(def);
1007
+ if (!description) description = getV3Description(current, def);
1008
+ if (!isV3WrapperType(typeName)) break;
1009
+ if (typeName === "ZodOptional" || typeName === "ZodNullish") required = false;
1010
+ if (typeName === "ZodDefault" && defaultValue === void 0) defaultValue = getV3DefaultValue(def);
1011
+ const inner = getV3InnerSchema(def);
1012
+ if (!inner) break;
1013
+ current = inner;
1014
+ }
1015
+ return {
1016
+ schema: current,
1017
+ required,
1018
+ default: defaultValue,
1019
+ description
1020
+ };
1021
+ }
1022
+ /**
1023
+ * Create a process function for Zod v3 schemas
1024
+ */
1025
+ function createV3ProcessFunction(schema, type) {
1026
+ return (value) => {
1027
+ try {
1028
+ let processSchema = schema;
1029
+ if (type === "number") processSchema = zod.z.coerce.number();
1030
+ else if (type === "boolean") processSchema = zod.z.string().transform((val) => {
1031
+ const lower = val.toLowerCase().trim();
1032
+ if ([
1033
+ "true",
1034
+ "1",
1035
+ "yes",
1036
+ "on",
1037
+ "enabled"
1038
+ ].includes(lower)) return true;
1039
+ if ([
1040
+ "false",
1041
+ "0",
1042
+ "no",
1043
+ "off",
1044
+ "disabled"
1045
+ ].includes(lower)) return false;
1046
+ throw new Error(`Expected boolean value, received "${val}"`);
1047
+ });
1048
+ const result = processSchema.safeParse(value);
1049
+ if (result.success) return result.data;
1050
+ throw new Error(`Failed to parse value "${value}": ${result.error.issues.map((issue) => issue.message).join("; ")}`);
1051
+ } catch (error) {
1052
+ const message = error instanceof Error ? error.message : String(error);
1053
+ throw new Error(message);
1054
+ }
1055
+ };
1056
+ }
1057
+ /**
1058
+ * Convert Zod v3 schema to EnvVarSchema
1059
+ */
1060
+ function convertFromZodV3Schema(schema) {
1061
+ const peeled = peelV3Schema(schema);
1062
+ const type = resolveV3EnvVarType(peeled.schema);
1063
+ const def = getV3Def(peeled.schema);
1064
+ switch (type) {
1065
+ case "boolean": return new BooleanEnvVarSchema({
1066
+ process: createV3ProcessFunction(peeled.schema, "boolean"),
1067
+ required: peeled.required,
1068
+ default: typeof peeled.default === "boolean" ? peeled.default : void 0,
1069
+ description: peeled.description
1070
+ });
1071
+ case "number": return new NumberEnvVarSchema({
1072
+ process: createV3ProcessFunction(peeled.schema, "number"),
1073
+ required: peeled.required,
1074
+ default: typeof peeled.default === "number" ? peeled.default : void 0,
1075
+ description: peeled.description
1076
+ });
1077
+ case "enum": {
1078
+ const values = extractV3EnumValues(def) || [];
1079
+ return new EnumEnvVarSchema({
1080
+ process: createV3ProcessFunction(peeled.schema, "enum"),
1081
+ values,
1082
+ required: peeled.required,
1083
+ default: typeof peeled.default === "string" ? peeled.default : void 0,
1084
+ description: peeled.description
1085
+ });
1086
+ }
1087
+ case "string":
1088
+ default: {
1089
+ const process$1 = createV3ProcessFunction(peeled.schema, "string");
1090
+ const defaultValue = typeof peeled.default === "string" ? peeled.default : void 0;
1091
+ return new StringEnvVarSchema({
1092
+ process: process$1,
1093
+ required: peeled.required,
1094
+ default: defaultValue,
1095
+ description: peeled.description
1096
+ });
1097
+ }
1098
+ }
1099
+ }
1100
+
1101
+ //#endregion
1102
+ //#region ../converters/src/converters/zod/ZodV4Converter.ts
1103
+ /**
1104
+ * Zod v4 schema converter implementation
1105
+ */
1106
+ var ZodV4Converter = class {
1107
+ applies(schema) {
1108
+ return isZodV4Schema(schema);
1109
+ }
1110
+ convert(schema) {
1111
+ return convertFromZodV4Schema(schema);
1112
+ }
1113
+ };
1114
+ /**
1115
+ * Check if a schema is a Zod v4 schema
1116
+ */
1117
+ function isZodV4Schema(schema) {
1118
+ if (!schema || typeof schema !== "object") return false;
1119
+ return "_zod" in schema;
1120
+ }
1121
+ /**
1122
+ * Extract definition from Zod v4 schema
1123
+ */
1124
+ function getV4Def(schema) {
1125
+ const container = schema;
1126
+ if (container._zod && container._zod.def) return container._zod.def;
1127
+ return {};
1128
+ }
1129
+ /**
1130
+ * Get the type name from a Zod v4 definition
1131
+ */
1132
+ function getV4TypeName(def) {
1133
+ return def.type || "unknown";
1134
+ }
1135
+ /**
1136
+ * Check if a type is a wrapper type that should be unwrapped
1137
+ */
1138
+ function isV4WrapperType(typeName) {
1139
+ return [
1140
+ "optional",
1141
+ "default",
1142
+ "catch",
1143
+ "readonly",
1144
+ "brand",
1145
+ "prefault",
1146
+ "nullable",
1147
+ "nullish"
1148
+ ].includes(typeName);
1149
+ }
1150
+ /**
1151
+ * Get inner schema from wrapper
1152
+ */
1153
+ function getV4InnerSchema(def) {
1154
+ return def.innerType || def.schema || def.in || def.inner;
1155
+ }
1156
+ /**
1157
+ * Get default value from definition
1158
+ */
1159
+ function getV4DefaultValue(def) {
1160
+ if (def.defaultValue !== void 0) return typeof def.defaultValue === "function" ? def.defaultValue() : def.defaultValue;
1161
+ if (def.prefaultValue !== void 0) return typeof def.prefaultValue === "function" ? def.prefaultValue() : def.prefaultValue;
1162
+ }
1163
+ /**
1164
+ * Extract enum values from schema
1165
+ */
1166
+ function extractV4EnumValues(def) {
1167
+ if (Array.isArray(def.values)) return def.values.map((v) => String(v));
1168
+ if (def.entries && typeof def.entries === "object") return Object.values(def.entries).map((v) => String(v));
1169
+ }
1170
+ /**
1171
+ * Get description from schema
1172
+ */
1173
+ function getV4Description(schema, def) {
1174
+ const directDesc = schema.description;
1175
+ if (typeof directDesc === "string" && directDesc.length > 0) return directDesc;
1176
+ if (typeof def.description === "string" && def.description.length > 0) return def.description;
1177
+ const metaFn = schema.meta;
1178
+ if (typeof metaFn === "function") {
1179
+ const meta = metaFn.call(schema);
1180
+ if (meta?.description && typeof meta.description === "string") return meta.description.trim();
1181
+ }
1182
+ }
1183
+ /**
1184
+ * Resolve environment variable type from schema
1185
+ */
1186
+ function resolveV4EnvVarType(schema) {
1187
+ const def = getV4Def(schema);
1188
+ switch (getV4TypeName(def)) {
1189
+ case "string": return "string";
1190
+ case "number":
1191
+ case "int": return "number";
1192
+ case "boolean":
1193
+ case "stringbool": return "boolean";
1194
+ case "pipe":
1195
+ if (def.in && def.out) {
1196
+ const inType = resolveV4EnvVarType(def.in);
1197
+ const outType = resolveV4EnvVarType(def.out);
1198
+ if (inType === "string" && outType === "boolean") return "boolean";
1199
+ }
1200
+ return "string";
1201
+ case "enum": return "enum";
1202
+ default:
1203
+ if (def.values || def.entries) return "enum";
1204
+ return "string";
1205
+ }
1206
+ }
1207
+ function peelV4Schema(schema) {
1208
+ let current = schema;
1209
+ let required = true;
1210
+ let defaultValue = void 0;
1211
+ let description = void 0;
1212
+ for (let i = 0; i < 20; i++) {
1213
+ const def = getV4Def(current);
1214
+ const typeName = getV4TypeName(def);
1215
+ if (!description) description = getV4Description(current, def);
1216
+ if (!isV4WrapperType(typeName)) if (typeName === "pipe" && def.in && def.out) {
1217
+ const inType = resolveV4EnvVarType(def.in);
1218
+ const outType = resolveV4EnvVarType(def.out);
1219
+ if (inType === "string" && outType === "boolean") break;
1220
+ } else break;
1221
+ if (typeName === "optional" || typeName === "nullish") required = false;
1222
+ if ((typeName === "default" || typeName === "prefault") && defaultValue === void 0) defaultValue = getV4DefaultValue(def);
1223
+ const inner = getV4InnerSchema(def);
1224
+ if (!inner) break;
1225
+ current = inner;
1226
+ }
1227
+ return {
1228
+ schema: current,
1229
+ required,
1230
+ default: defaultValue,
1231
+ description
1232
+ };
1233
+ }
1234
+ /**
1235
+ * Create a process function for Zod v4 schemas
1236
+ */
1237
+ function createV4ProcessFunction(schema, type, originalSchema) {
1238
+ return (value) => {
1239
+ try {
1240
+ let processSchema = schema;
1241
+ const def = getV4Def(schema);
1242
+ const typeName = getV4TypeName(def);
1243
+ if (typeName === "stringbool" || typeName === "pipe" && def.in && def.out && resolveV4EnvVarType(def.in) === "string" && resolveV4EnvVarType(def.out) === "boolean") processSchema = originalSchema;
1244
+ else if (type === "number") processSchema = zod.z.coerce.number();
1245
+ else if (type === "boolean") processSchema = zod.z.stringbool();
1246
+ const result = zod_v4_core.safeParse(processSchema, value);
1247
+ if (result.success) return result.data;
1248
+ throw new Error(`Failed to parse value "${value}": ${result.error.issues.map((issue) => issue.message).join("; ")}`);
1249
+ } catch (error) {
1250
+ const message = error instanceof Error ? error.message : String(error);
1251
+ throw new Error(message);
1252
+ }
1253
+ };
1254
+ }
1255
+ /**
1256
+ * Convert Zod v4 schema to EnvVarSchema
1257
+ */
1258
+ function convertFromZodV4Schema(schema) {
1259
+ const peeled = peelV4Schema(schema);
1260
+ const type = resolveV4EnvVarType(peeled.schema);
1261
+ const def = getV4Def(peeled.schema);
1262
+ switch (type) {
1263
+ case "boolean": return new BooleanEnvVarSchema({
1264
+ process: createV4ProcessFunction(peeled.schema, "boolean", schema),
1265
+ required: peeled.required,
1266
+ default: typeof peeled.default === "boolean" ? peeled.default : void 0,
1267
+ description: peeled.description
1268
+ });
1269
+ case "number": return new NumberEnvVarSchema({
1270
+ process: createV4ProcessFunction(peeled.schema, "number", schema),
1271
+ required: peeled.required,
1272
+ default: typeof peeled.default === "number" ? peeled.default : void 0,
1273
+ description: peeled.description
1274
+ });
1275
+ case "enum": {
1276
+ const values = extractV4EnumValues(def) || [];
1277
+ return new EnumEnvVarSchema({
1278
+ process: createV4ProcessFunction(peeled.schema, "enum", schema),
1279
+ values,
1280
+ required: peeled.required,
1281
+ default: typeof peeled.default === "string" ? peeled.default : void 0,
1282
+ description: peeled.description
1283
+ });
1284
+ }
1285
+ case "string":
1286
+ default: {
1287
+ const process$1 = createV4ProcessFunction(peeled.schema, "string", schema);
1288
+ const defaultValue = typeof peeled.default === "string" ? peeled.default : void 0;
1289
+ return new StringEnvVarSchema({
1290
+ process: process$1,
1291
+ required: peeled.required,
1292
+ default: defaultValue,
1293
+ description: peeled.description
1294
+ });
1295
+ }
1296
+ }
1297
+ }
1298
+
1299
+ //#endregion
1300
+ //#region ../converters/src/converters/joi/JoiConverter.ts
1301
+ /**
1302
+ * Joi schema converter implementation
1303
+ */
1304
+ var JoiConverter = class {
1305
+ applies(schema) {
1306
+ return isJoiSchema(schema);
1307
+ }
1308
+ convert(schema) {
1309
+ return convertFromJoiSchema(schema);
1310
+ }
1311
+ };
1312
+ /**
1313
+ * Check if a schema is a Joi schema using the official API
1314
+ */
1315
+ function isJoiSchema(schema) {
1316
+ if (!schema || typeof schema !== "object") return false;
1317
+ const candidate = schema;
1318
+ if (!(typeof candidate.describe === "function" && typeof candidate.validate === "function")) return false;
1319
+ if (candidate.isJoi === true) return true;
1320
+ const hasAsyncVariant = typeof candidate.validateAsync === "function";
1321
+ const hasRoot = typeof candidate.$_root === "object" && candidate.$_root !== null;
1322
+ const hasFlags = typeof candidate._flags === "object" && candidate._flags !== null;
1323
+ return hasAsyncVariant || hasRoot || hasFlags;
1324
+ }
1325
+ /**
1326
+ * Get description from Joi schema using public API first, internal as fallback
1327
+ */
1328
+ function getJoiDescription(schema) {
1329
+ try {
1330
+ return schema.describe()?.flags?.description;
1331
+ } catch {
1332
+ return schema._flags?.description;
1333
+ }
1334
+ }
1335
+ /**
1336
+ * Check if schema is required using public API first, internal as fallback
1337
+ */
1338
+ function isJoiRequired(schema) {
1339
+ try {
1340
+ const presence = schema.describe()?.flags?.presence;
1341
+ if (presence === "required") return true;
1342
+ if (presence === "optional") return false;
1343
+ return presence === void 0;
1344
+ } catch {
1345
+ const flags = schema._flags;
1346
+ if (flags?.presence === "required") return true;
1347
+ if (flags?.presence === "optional") return false;
1348
+ return true;
1349
+ }
1350
+ }
1351
+ /**
1352
+ * Get default value from Joi schema using public API first, internal as fallback
1353
+ */
1354
+ function getJoiDefaultValue(schema) {
1355
+ try {
1356
+ const defaultValue = schema.describe()?.flags?.default;
1357
+ return typeof defaultValue === "function" ? defaultValue() : defaultValue;
1358
+ } catch {
1359
+ const flags = schema._flags;
1360
+ if (flags?.default !== void 0) {
1361
+ const defaultValue = flags.default;
1362
+ return typeof defaultValue === "function" ? defaultValue() : defaultValue;
1363
+ }
1364
+ return;
1365
+ }
1366
+ }
1367
+ /**
1368
+ * Get valid values for enum-like schemas using public API first, internal as fallback
1369
+ */
1370
+ function getJoiValidValues(schema) {
1371
+ const values = [];
1372
+ let isOnlySchema = false;
1373
+ try {
1374
+ const description = schema.describe();
1375
+ if (description?.allow && Array.isArray(description.allow)) values.push(...description.allow);
1376
+ isOnlySchema = description?.flags?.only === true;
1377
+ } catch {
1378
+ if (schema._valids?._values) values.push(...Array.from(schema._valids._values));
1379
+ isOnlySchema = schema._flags?.only === true;
1380
+ }
1381
+ if (isOnlySchema && values.length > 0) return values.map((v) => String(v));
1382
+ }
1383
+ /**
1384
+ * Resolve environment variable type from Joi schema using public API first, internal as fallback
1385
+ */
1386
+ function resolveJoiEnvVarType(schema) {
1387
+ let type;
1388
+ const exposedSchema = schema;
1389
+ try {
1390
+ type = schema.describe()?.type;
1391
+ } catch {
1392
+ type = exposedSchema._type || schema.type;
1393
+ }
1394
+ const validValues = getJoiValidValues(schema);
1395
+ if (validValues && validValues.length > 0) return "enum";
1396
+ switch (type) {
1397
+ case "string": return "string";
1398
+ case "number": return "number";
1399
+ case "boolean": return "boolean";
1400
+ default: return "string";
1401
+ }
1402
+ }
1403
+ /**
1404
+ * Create a process function for Joi schemas
1405
+ */
1406
+ function createJoiProcessFunction(schema, type) {
1407
+ return (value) => {
1408
+ try {
1409
+ let processValue$1 = value;
1410
+ if (type === "number") {
1411
+ const num = Number(value);
1412
+ if (Number.isNaN(num)) throw new Error(`Expected number, received "${value}"`);
1413
+ processValue$1 = num;
1414
+ } else if (type === "boolean") {
1415
+ const lower = value.toLowerCase().trim();
1416
+ if ([
1417
+ "true",
1418
+ "1",
1419
+ "yes",
1420
+ "on",
1421
+ "enabled"
1422
+ ].includes(lower)) processValue$1 = true;
1423
+ else if ([
1424
+ "false",
1425
+ "0",
1426
+ "no",
1427
+ "off",
1428
+ "disabled"
1429
+ ].includes(lower)) processValue$1 = false;
1430
+ else throw new Error(`Expected boolean value, received "${value}"`);
1431
+ }
1432
+ const result = schema.validate(processValue$1, { convert: true });
1433
+ if (result.error) {
1434
+ const message = result.error.details ? result.error.details.map((d) => d.message).join("; ") : result.error.message || String(result.error);
1435
+ throw new Error(`Validation failed: ${message}`);
1436
+ }
1437
+ return result.value;
1438
+ } catch (error) {
1439
+ const message = error instanceof Error ? error.message : String(error);
1440
+ throw new Error(message);
1441
+ }
1442
+ };
1443
+ }
1444
+ /**
1445
+ * Convert Joi schema to EnvVarSchema
1446
+ */
1447
+ function convertFromJoiSchema(schema) {
1448
+ const type = resolveJoiEnvVarType(schema);
1449
+ const required = isJoiRequired(schema);
1450
+ const defaultValue = getJoiDefaultValue(schema);
1451
+ const description = getJoiDescription(schema);
1452
+ switch (type) {
1453
+ case "boolean": return new BooleanEnvVarSchema({
1454
+ process: createJoiProcessFunction(schema, "boolean"),
1455
+ required,
1456
+ default: typeof defaultValue === "boolean" ? defaultValue : void 0,
1457
+ description
1458
+ });
1459
+ case "number": return new NumberEnvVarSchema({
1460
+ process: createJoiProcessFunction(schema, "number"),
1461
+ required,
1462
+ default: typeof defaultValue === "number" ? defaultValue : void 0,
1463
+ description
1464
+ });
1465
+ case "enum": {
1466
+ const values = getJoiValidValues(schema) || [];
1467
+ return new EnumEnvVarSchema({
1468
+ process: createJoiProcessFunction(schema, "enum"),
1469
+ values,
1470
+ required,
1471
+ default: typeof defaultValue === "string" ? defaultValue : void 0,
1472
+ description
1473
+ });
1474
+ }
1475
+ case "string":
1476
+ default: return new StringEnvVarSchema({
1477
+ process: createJoiProcessFunction(schema, "string"),
1478
+ required,
1479
+ default: typeof defaultValue === "string" ? defaultValue : void 0,
1480
+ description
1481
+ });
1482
+ }
1483
+ }
1484
+
1485
+ //#endregion
1486
+ //#region ../converters/src/converters/superstruct/SuperstructConverter.ts
1487
+ /**
1488
+ * Superstruct schema converter implementation
1489
+ */
1490
+ var SuperstructConverter = class {
1491
+ applies(schema) {
1492
+ return isSuperstructSchema(schema);
1493
+ }
1494
+ convert(schema) {
1495
+ return convertFromSuperstruct(schema);
1496
+ }
1497
+ };
1498
+ /**
1499
+ * Detect if a value looks like a Superstruct Struct instance
1500
+ */
1501
+ function isSuperstructSchema(value) {
1502
+ if (!value || typeof value !== "object") return false;
1503
+ const candidate = value;
1504
+ return typeof candidate.type === "string" && typeof candidate.validate === "function" && typeof candidate.create === "function";
1505
+ }
1506
+ /**
1507
+ * Convert a Superstruct schema to an EnvVarSchema
1508
+ */
1509
+ function convertFromSuperstruct(schema) {
1510
+ const resolvedType = resolveSuperstructEnvVarType(schema);
1511
+ const required = isStructRequired(schema);
1512
+ const description = getStructDescription(schema);
1513
+ const defaultValue = getStructDefault(schema);
1514
+ if (resolvedType === "enum") {
1515
+ const values = extractEnumValues(schema);
1516
+ if (!values || values.length === 0) return createStringEnvVarSchema(schema, required, defaultValue, description);
1517
+ const readonlyValues = values;
1518
+ return new EnumEnvVarSchema({
1519
+ process: createSuperstructProcessFunction(schema, "enum"),
1520
+ values: readonlyValues,
1521
+ required,
1522
+ default: typeof defaultValue === "string" ? defaultValue : void 0,
1523
+ description
1524
+ });
1525
+ }
1526
+ if (resolvedType === "boolean") return new BooleanEnvVarSchema({
1527
+ process: createSuperstructProcessFunction(schema, "boolean"),
1528
+ required,
1529
+ default: typeof defaultValue === "boolean" ? defaultValue : void 0,
1530
+ description
1531
+ });
1532
+ if (resolvedType === "number") return new NumberEnvVarSchema({
1533
+ process: createSuperstructProcessFunction(schema, "number"),
1534
+ required,
1535
+ default: typeof defaultValue === "number" ? defaultValue : void 0,
1536
+ description
1537
+ });
1538
+ return createStringEnvVarSchema(schema, required, defaultValue, description);
1539
+ }
1540
+ function createStringEnvVarSchema(schema, required, defaultValue, description) {
1541
+ return new StringEnvVarSchema({
1542
+ process: createSuperstructProcessFunction(schema, "string"),
1543
+ required,
1544
+ default: typeof defaultValue === "string" ? defaultValue : void 0,
1545
+ description
1546
+ });
1547
+ }
1548
+ function resolveSuperstructEnvVarType(schema) {
1549
+ switch (getStructType(schema)) {
1550
+ case "boolean": return "boolean";
1551
+ case "number":
1552
+ case "integer": return "number";
1553
+ case "enums": return "enum";
1554
+ case "literal": return typeof schema.schema === "string" ? "enum" : "string";
1555
+ default: return "string";
1556
+ }
1557
+ }
1558
+ function getStructType(schema) {
1559
+ const typeValue = schema.type;
1560
+ return typeof typeValue === "string" ? typeValue : "unknown";
1561
+ }
1562
+ function extractEnumValues(schema) {
1563
+ const typeName = getStructType(schema);
1564
+ if (typeName === "enums") {
1565
+ const structSchema = schema.schema;
1566
+ if (structSchema && typeof structSchema === "object") {
1567
+ const rawValues = Object.values(structSchema);
1568
+ if (rawValues.every((value) => typeof value === "string")) return rawValues;
1569
+ }
1570
+ }
1571
+ if (typeName === "literal") {
1572
+ const value = schema.schema;
1573
+ if (typeof value === "string") return [value];
1574
+ }
1575
+ }
1576
+ function isStructRequired(schema) {
1577
+ try {
1578
+ const [error] = schema.validate(void 0);
1579
+ return !!error;
1580
+ } catch {
1581
+ return true;
1582
+ }
1583
+ }
1584
+ function getStructDefault(schema) {
1585
+ try {
1586
+ const [error, value] = schema.validate(void 0, { coerce: true });
1587
+ if (!error && value !== void 0) return value;
1588
+ } catch {}
1589
+ }
1590
+ function getStructDescription(schema) {
1591
+ const structSchema = schema.schema;
1592
+ if (structSchema && typeof structSchema === "object" && typeof structSchema.description === "string") return structSchema.description;
1593
+ if (typeof schema.description === "string") return schema.description;
1594
+ }
1595
+ function createSuperstructProcessFunction(schema, type) {
1596
+ return (value) => {
1597
+ if (typeof value !== "string") throw new Error("Value must be a string");
1598
+ let candidate = value;
1599
+ if (type === "number") {
1600
+ const trimmed = value.trim();
1601
+ if (trimmed === "") candidate = void 0;
1602
+ else {
1603
+ const parsed = Number(trimmed);
1604
+ if (Number.isNaN(parsed) || !Number.isFinite(parsed)) throw new Error(`"${value}" is not a valid number`);
1605
+ candidate = parsed;
1606
+ }
1607
+ } else if (type === "boolean") {
1608
+ const trimmed = value.trim().toLowerCase();
1609
+ if (trimmed === "") candidate = void 0;
1610
+ else if ([
1611
+ "true",
1612
+ "1",
1613
+ "yes",
1614
+ "on",
1615
+ "enabled"
1616
+ ].includes(trimmed)) candidate = true;
1617
+ else if ([
1618
+ "false",
1619
+ "0",
1620
+ "no",
1621
+ "off",
1622
+ "disabled"
1623
+ ].includes(trimmed)) candidate = false;
1624
+ else throw new Error(`"${value}" is not a valid boolean. Use: true/false, 1/0, yes/no, on/off, or enabled/disabled`);
1625
+ } else if (value === "") candidate = void 0;
1626
+ const [error, result] = schema.validate(candidate, { coerce: true });
1627
+ if (error) throw new Error(error.message);
1628
+ return result;
1629
+ };
1630
+ }
1631
+
1632
+ //#endregion
1633
+ //#region ../converters/src/converters.ts
1634
+ /**
1635
+ * Registry of available schema converters
1636
+ */
1637
+ const converters = [
1638
+ new ZodV4Converter(),
1639
+ new ZodV3Converter(),
1640
+ new JoiConverter(),
1641
+ new SuperstructConverter()
1642
+ ];
1643
+
1644
+ //#endregion
1645
+ //#region ../models/src/resolve.ts
1646
+ /**
1647
+ * Resolve any supported schema to a EnvVarSchema.
1648
+ *
1649
+ * This is the main entry point for converting external schemas
1650
+ * (like Zod schemas) to envcredible's internal schema format.
1651
+ * If the input is already a EnvVarSchema, it returns it directly.
1652
+ *
1653
+ * @param schema - The schema to convert (e.g., Zod v3/v4 schema or EnvVarSchema)
1654
+ * @returns EnvVarSchema that can be used with envcredible
1655
+ * @throws Error if no converter can handle the schema
1656
+ */
1657
+ function resolveSchema(schema) {
1658
+ if (isEnvVarSchema(schema)) return schema;
1659
+ for (const converter of converters) if (converter.applies(schema)) return converter.convert(schema);
1660
+ throw new Error(`No converter found for schema. Supported types: Zod v3, Zod v4, Joi, Superstruct, EnvVarSchema. Received: ${typeof schema}`);
1661
+ }
1662
+ /**
1663
+ * Resolve mixed schema map (Zod schemas or EnvVarSchema) to pure EnvVarSchema map.
1664
+ *
1665
+ * This function takes a map where values can be:
1666
+ * - Zod v3 schemas
1667
+ * - Zod v4 schemas
1668
+ * - Already resolved EnvVarSchema instances
1669
+ *
1670
+ * And converts everything to EnvVarSchema instances that can be used throughout envcredible.
1671
+ *
1672
+ * @param schemas - Object mapping environment variable names to various schema types
1673
+ * @returns Record mapping env var names to EnvVarSchema instances
1674
+ */
1675
+ function resolveSchemas(schemas) {
1676
+ const resolved = {};
1677
+ for (const [key, schema] of Object.entries(schemas)) try {
1678
+ resolved[key] = resolveSchema(schema);
1679
+ } catch (error) {
1680
+ const message = error instanceof Error ? error.message : String(error);
1681
+ throw new Error(`Failed to resolve schema for environment variable "${key}": ${message}`);
1682
+ }
1683
+ return resolved;
1684
+ }
1685
+
1686
+ //#endregion
1687
+ //#region ../models/src/EnvModel.ts
1688
+ /**
1689
+ * Environment variable specification container
1690
+ * Encapsulates schemas and preprocessor configuration
1691
+ */
1692
+ var EnvModel = class {
1693
+ /**
1694
+ * Resolved environment variable schemas
1695
+ */
1696
+ schemas;
1697
+ /**
1698
+ * Preprocessing configuration for environment variable types
1699
+ */
1700
+ preprocess;
1701
+ /**
1702
+ * Create an EnvModel instance from options
1703
+ * @param options - Specification options
1704
+ */
1705
+ constructor(options) {
1706
+ this.schemas = resolveSchemas(options.schemas);
1707
+ this.preprocess = this.resolvePreprocessors(options.preprocess);
1708
+ }
1709
+ /**
1710
+ * Resolve preprocessor configuration from options
1711
+ * @param config - Preprocessor configuration (true, false, or partial object)
1712
+ * @returns Resolved preprocessors object
1713
+ */
1714
+ resolvePreprocessors(config) {
1715
+ if (config === false) return {
1716
+ string: false,
1717
+ number: false,
1718
+ boolean: false,
1719
+ enum: false
1720
+ };
1721
+ if (config === true || config === void 0) return {};
1722
+ return { ...config };
1723
+ }
1724
+ };
1725
+
1726
+ //#endregion
1727
+ //#region ../models/src/model.ts
1728
+ /**
1729
+ * Create an environment variable model
1730
+ *
1731
+ * Sugar utility for creating EnvModel instances with full type inference
1732
+ *
1733
+ * @param options - Model options
1734
+ * @returns EnvModel instance with inferred types
1735
+ *
1736
+ * @example
1737
+ * ```typescript
1738
+ * import { define, s } from "@e-n-v/models";
1739
+ *
1740
+ * export default define({
1741
+ * schemas: {
1742
+ * PORT: s.number({ default: 3000 }),
1743
+ * DATABASE_URL: s.string(),
1744
+ * DEBUG: s.boolean({ default: false })
1745
+ * },
1746
+ * preprocess: true
1747
+ * });
1748
+ * ```
1749
+ */
1750
+ function define(options) {
1751
+ return new EnvModel(options);
1752
+ }
1753
+
1754
+ //#endregion
1755
+ //#region ../prompt/src/options/defaults.ts
1756
+ var defaults_exports = /* @__PURE__ */ __export({
1757
+ ENV_PATH: () => ENV_PATH,
1758
+ SECRET_PATTERNS: () => SECRET_PATTERNS,
1759
+ TRUNCATE_LENGTH: () => TRUNCATE_LENGTH
1760
+ });
1761
+ const ENV_PATH = ".env";
1762
+ const TRUNCATE_LENGTH = 40;
1763
+ const SECRET_PATTERNS = Object.freeze([
1764
+ /password/i,
1765
+ /passphrase/i,
1766
+ /secret/i,
1767
+ /token/i,
1768
+ /api[_-]?key/i,
1769
+ /client[_-]?secret/i,
1770
+ /private[_-]?key/i,
1771
+ /(?:database|db|redis|mongo|sql|postgres|mysql)[_-]?(?:connection[_-]?)?(?:string|url)/i,
1772
+ /database(?:[_-]?url)?/i,
1773
+ /access[_-]?key/i,
1774
+ /credential/i
1775
+ ]);
1776
+
1777
+ //#endregion
1778
+ //#region ../prompt/src/visuals/Theme.ts
1779
+ var Theme = class Theme {
1780
+ static default = new Theme(picocolors.default.magenta);
1781
+ primary;
1782
+ bgPrimary;
1783
+ subtle;
1784
+ warn;
1785
+ bgWarn;
1786
+ error;
1787
+ bgError;
1788
+ constructor(main) {
1789
+ this.primary = main;
1790
+ this.bgPrimary = this.getBackgroundColor(main);
1791
+ this.subtle = picocolors.default.gray;
1792
+ this.warn = picocolors.default.yellow;
1793
+ this.bgWarn = this.getBackgroundColor(picocolors.default.yellow);
1794
+ this.error = picocolors.default.red;
1795
+ this.bgError = this.getBackgroundColor(picocolors.default.red);
1796
+ }
1797
+ /**
1798
+ * Get the background version of a color function
1799
+ */
1800
+ getBackgroundColor(colorFn) {
1801
+ if (colorFn === picocolors.default.black) return picocolors.default.bgBlack;
1802
+ if (colorFn === picocolors.default.red) return picocolors.default.bgRed;
1803
+ if (colorFn === picocolors.default.green) return picocolors.default.bgGreen;
1804
+ if (colorFn === picocolors.default.yellow) return picocolors.default.bgYellow;
1805
+ if (colorFn === picocolors.default.blue) return picocolors.default.bgBlue;
1806
+ if (colorFn === picocolors.default.magenta) return picocolors.default.bgMagenta;
1807
+ if (colorFn === picocolors.default.cyan) return picocolors.default.bgCyan;
1808
+ if (colorFn === picocolors.default.white) return picocolors.default.bgWhite;
1809
+ if (colorFn === picocolors.default.redBright) return picocolors.default.bgRedBright;
1810
+ if (colorFn === picocolors.default.greenBright) return picocolors.default.bgGreenBright;
1811
+ if (colorFn === picocolors.default.yellowBright) return picocolors.default.bgYellowBright;
1812
+ if (colorFn === picocolors.default.blueBright) return picocolors.default.bgBlueBright;
1813
+ if (colorFn === picocolors.default.magentaBright) return picocolors.default.bgMagentaBright;
1814
+ if (colorFn === picocolors.default.cyanBright) return picocolors.default.bgCyanBright;
1815
+ if (colorFn === picocolors.default.whiteBright) return picocolors.default.bgWhiteBright;
1816
+ return picocolors.default.bgBlack;
1817
+ }
1818
+ };
1819
+
1820
+ //#endregion
1821
+ //#region ../prompt/src/visuals/symbols.ts
1822
+ const S_BAR = "│";
1823
+ const S_BAR_END = "└";
1824
+ const S_BAR_START = "┌";
1825
+ const S_STEP_ACTIVE = "◆";
1826
+ const S_STEP_SUBMIT = "✔";
1827
+ const S_STEP_SKIP = "⏭";
1828
+ const S_STEP_CANCEL = "✕";
1829
+ const S_STEP_ERROR = "▲";
1830
+ const S_STEP_PREVIOUS = "⏮";
1831
+ const S_TOOL_ACTIVE = "■";
1832
+ const S_TOOL_INACTIVE = "□";
1833
+ const S_RADIO_ACTIVE = "●";
1834
+ const S_RADIO_INACTIVE = "○";
1835
+ const S_CURSOR = "█";
1836
+ const SECRET_MASK = "•";
1837
+
1838
+ //#endregion
1839
+ //#region ../prompt/src/prompts/ThemedPrompt.ts
1840
+ var ThemedPrompt = class extends __clack_core.Prompt {
1841
+ theme;
1842
+ constructor(opts, trackValue = false) {
1843
+ super(opts, trackValue);
1844
+ this.theme = opts.theme || Theme.default;
1845
+ }
1846
+ /**
1847
+ * Get the appropriate symbol based on prompt state
1848
+ */
1849
+ getSymbol() {
1850
+ switch (this.state) {
1851
+ case "initial":
1852
+ case "active": return this.theme.primary(S_STEP_ACTIVE);
1853
+ case "error": return this.theme.warn(S_STEP_ERROR);
1854
+ case "submit": return this.theme.primary(S_STEP_SUBMIT);
1855
+ case "cancel": return this.theme.error(S_STEP_CANCEL);
1856
+ default: return this.theme.primary(S_STEP_ACTIVE);
1857
+ }
1858
+ }
1859
+ /**
1860
+ * Get bar color based on error state - yellow for errors, theme primary otherwise
1861
+ */
1862
+ getBarColor(barSymbol) {
1863
+ return this.state === "error" ? this.theme.warn(barSymbol) : this.theme.primary(barSymbol);
1864
+ }
1865
+ /**
1866
+ * Get bar symbols with appropriate coloring
1867
+ */
1868
+ getBar() {
1869
+ return this.getBarColor(S_BAR);
1870
+ }
1871
+ getBarEnd() {
1872
+ return this.getBarColor(S_BAR_END);
1873
+ }
1874
+ /**
1875
+ * Color utilities for consistent theming
1876
+ */
1877
+ get colors() {
1878
+ return {
1879
+ primary: this.theme.primary,
1880
+ subtle: this.theme.subtle,
1881
+ warn: this.theme.warn,
1882
+ error: this.theme.error,
1883
+ white: picocolors.default.white,
1884
+ bold: picocolors.default.bold,
1885
+ dim: picocolors.default.dim,
1886
+ inverse: picocolors.default.inverse,
1887
+ strikethrough: picocolors.default.strikethrough
1888
+ };
1889
+ }
1890
+ };
1891
+
1892
+ //#endregion
1893
+ //#region ../prompt/src/prompts/utils/ClackPromptInternals.ts
1894
+ /** Hacks to access private members of Clack prompts */
1895
+ var ClackPromptInternals = class {
1896
+ prompt;
1897
+ constructor(prompt$1) {
1898
+ this.prompt = prompt$1;
1899
+ }
1900
+ set track(enabled) {
1901
+ this.prompt._track = enabled;
1902
+ }
1903
+ get track() {
1904
+ return this.prompt._track;
1905
+ }
1906
+ };
1907
+
1908
+ //#endregion
1909
+ //#region ../prompt/src/prompts/utils/padActiveRender.ts
1910
+ /**
1911
+ * Ensures active prompts leave a blank line beneath their output while leaving
1912
+ * submitted or cancelled renders untouched.
1913
+ */
1914
+ function padActiveRender(render) {
1915
+ return function paddedRender() {
1916
+ const result = render.call(this);
1917
+ if (typeof result !== "string") return result;
1918
+ if (this.state === "submit" || this.state === "cancel") return result;
1919
+ const normalized = result.replace(/\r\n/g, "\n");
1920
+ if (!normalized) return "\n";
1921
+ if (normalized.endsWith("\n")) return result;
1922
+ return result + "\n";
1923
+ };
1924
+ }
1925
+
1926
+ //#endregion
1927
+ //#region ../prompt/src/prompts/toolbar/Toolbar.ts
1928
+ var Toolbar = class {
1929
+ _isOpen = false;
1930
+ cursor = 0;
1931
+ previous;
1932
+ theme;
1933
+ actions;
1934
+ secret;
1935
+ constructor(config) {
1936
+ this.previous = config.previous;
1937
+ this.secret = config.secret;
1938
+ this.theme = config.theme;
1939
+ this.actions = config.actions;
1940
+ }
1941
+ get isOpen() {
1942
+ return this._isOpen;
1943
+ }
1944
+ open() {
1945
+ this._isOpen = true;
1946
+ this.cursor = 0;
1947
+ }
1948
+ close() {
1949
+ this._isOpen = false;
1950
+ this.cursor = 0;
1951
+ }
1952
+ handleKey(char, info) {
1953
+ if (!info) return false;
1954
+ if (info.name === "tab") {
1955
+ if (!this._isOpen) this.open();
1956
+ else this.close();
1957
+ return true;
1958
+ }
1959
+ if (!this._isOpen) return false;
1960
+ switch (info.name) {
1961
+ case "left":
1962
+ case "up":
1963
+ this.shiftCursor(-1);
1964
+ return true;
1965
+ case "right":
1966
+ case "down":
1967
+ this.shiftCursor(1);
1968
+ return true;
1969
+ case "return":
1970
+ case "enter":
1971
+ this.activateOption();
1972
+ return true;
1973
+ }
1974
+ if (char && char.length === 1 && !info.ctrl && !info.meta) {
1975
+ this.close();
1976
+ return false;
1977
+ }
1978
+ return false;
1979
+ }
1980
+ render() {
1981
+ if (!this._isOpen) return "";
1982
+ const options = this.getOptions();
1983
+ this.ensureCursor(options);
1984
+ if (!options.length) return this.theme.subtle("Tab to return");
1985
+ const separator = this.theme.subtle(" / ");
1986
+ return `${options.map((option, index) => {
1987
+ const isFocused = index === this.cursor;
1988
+ const label = `${isFocused ? S_TOOL_ACTIVE : S_TOOL_INACTIVE} ${option.label}`;
1989
+ return isFocused ? this.theme.primary(label) : this.theme.subtle(label);
1990
+ }).join(separator)}${separator}${this.theme.subtle("Tab to return")}`;
1991
+ }
1992
+ shiftCursor(delta) {
1993
+ const options = this.getOptions();
1994
+ if (!options.length) return;
1995
+ let nextIndex = this.cursor;
1996
+ const len = options.length;
1997
+ for (let step = 0; step < len; step++) {
1998
+ nextIndex = (nextIndex + delta + len) % len;
1999
+ this.cursor = nextIndex;
2000
+ return;
2001
+ }
2002
+ }
2003
+ activateOption() {
2004
+ const options = this.getOptions();
2005
+ this.ensureCursor(options);
2006
+ const selected = options[this.cursor];
2007
+ if (!selected) return;
2008
+ this.close();
2009
+ selected.action();
2010
+ }
2011
+ ensureCursor(options) {
2012
+ if (!options.length) {
2013
+ this.cursor = 0;
2014
+ return;
2015
+ }
2016
+ if (this.cursor >= options.length) this.cursor = 0;
2017
+ }
2018
+ getOptions() {
2019
+ const options = [{
2020
+ key: "skip",
2021
+ label: "Skip",
2022
+ action: this.actions.skip
2023
+ }];
2024
+ if (this.previous) options.push({
2025
+ key: "previous",
2026
+ label: "Previous",
2027
+ action: this.actions.previous
2028
+ });
2029
+ if (this.secret !== false) options.push({
2030
+ key: "toggleSecret",
2031
+ label: this.secret === "shown" ? "Hide" : "Show",
2032
+ action: this.actions.toggleSecret
2033
+ });
2034
+ return options;
2035
+ }
2036
+ };
2037
+
2038
+ //#endregion
2039
+ //#region ../prompt/src/prompts/state/EnvPromptModeDetails.ts
2040
+ /**
2041
+ * Creates initial mode details for a prompt
2042
+ */
2043
+ function createInitialModeDetails(options) {
2044
+ return {
2045
+ mode: options.hasOptions ? "selection" : "typing",
2046
+ intention: "commit",
2047
+ secretVisibility: options.hasSecret ? "hidden" : "not-secret",
2048
+ validation: "pending",
2049
+ cursor: 0,
2050
+ inputValue: options.initialInputValue || "",
2051
+ toolbarOpen: false,
2052
+ consumeSubmit: false
2053
+ };
2054
+ }
2055
+ /**
2056
+ * Computes derived state from the core mode details
2057
+ */
2058
+ function computeState(modeDetails) {
2059
+ return {
2060
+ canSubmit: modeDetails.intention === "commit" && modeDetails.validation !== "invalid",
2061
+ shouldTrackInput: modeDetails.mode === "typing",
2062
+ shouldDimUI: modeDetails.toolbarOpen,
2063
+ shouldConsumeSubmit: modeDetails.consumeSubmit,
2064
+ shouldSkipValidation: modeDetails.validation === "suppressed"
2065
+ };
2066
+ }
2067
+ /**
2068
+ * Creates complete state by combining mode details and computed properties
2069
+ */
2070
+ function createState(modeDetails) {
2071
+ return {
2072
+ ...modeDetails,
2073
+ ...computeState(modeDetails)
2074
+ };
2075
+ }
2076
+
2077
+ //#endregion
2078
+ //#region ../prompt/src/prompts/state/EnvPromptMode.ts
2079
+ /**
2080
+ * Encapsulates the prompt's interaction mode state and transitions.
2081
+ */
2082
+ var EnvPromptMode = class {
2083
+ _details;
2084
+ _listeners = [];
2085
+ constructor(initialModeDetails) {
2086
+ this._details = { ...initialModeDetails };
2087
+ }
2088
+ get intention() {
2089
+ return this._details.intention;
2090
+ }
2091
+ set intention(intention) {
2092
+ this.updateModeDetails({ intention });
2093
+ }
2094
+ /**
2095
+ * Complete computed state for observers.
2096
+ */
2097
+ get state() {
2098
+ return createState(this._details);
2099
+ }
2100
+ /**
2101
+ * Snapshot of the raw mode details (without computed props).
2102
+ */
2103
+ get modeDetails() {
2104
+ return { ...this._details };
2105
+ }
2106
+ subscribe(listener) {
2107
+ this._listeners.push(listener);
2108
+ return () => {
2109
+ const index = this._listeners.indexOf(listener);
2110
+ if (index >= 0) this._listeners.splice(index, 1);
2111
+ };
2112
+ }
2113
+ notifyListeners() {
2114
+ const snapshot = this.state;
2115
+ this._listeners.forEach((listener) => listener(snapshot));
2116
+ }
2117
+ updateModeDetails(updates) {
2118
+ this._details = {
2119
+ ...this._details,
2120
+ ...updates
2121
+ };
2122
+ this.notifyListeners();
2123
+ }
2124
+ enterTyping(inputValue = "") {
2125
+ if (this._details.mode === "selection") this.updateModeDetails({
2126
+ mode: "typing",
2127
+ inputValue,
2128
+ validation: "pending"
2129
+ });
2130
+ }
2131
+ exitTyping() {
2132
+ if (this._details.mode === "typing") this.updateModeDetails({
2133
+ mode: "selection",
2134
+ inputValue: "",
2135
+ validation: "pending"
2136
+ });
2137
+ }
2138
+ openToolbar() {
2139
+ this.updateModeDetails({ toolbarOpen: true });
2140
+ }
2141
+ closeToolbar() {
2142
+ this.updateModeDetails({ toolbarOpen: false });
2143
+ }
2144
+ moveCursor(direction, maxIndex) {
2145
+ if (this._details.mode === "selection" && !this._details.toolbarOpen) {
2146
+ const delta = direction === "up" ? -1 : 1;
2147
+ let cursor = this._details.cursor + delta;
2148
+ if (cursor < 0) cursor = maxIndex;
2149
+ else if (cursor > maxIndex) cursor = 0;
2150
+ this.updateModeDetails({
2151
+ cursor,
2152
+ validation: "pending"
2153
+ });
2154
+ }
2155
+ }
2156
+ setCursor(position) {
2157
+ if (this._details.mode === "selection") this.updateModeDetails({
2158
+ cursor: position,
2159
+ validation: "pending"
2160
+ });
2161
+ }
2162
+ setIntention(intention) {
2163
+ this.intention = intention;
2164
+ }
2165
+ toggleSecretVisibility() {
2166
+ if (this._details.secretVisibility !== "not-secret") {
2167
+ const next = this._details.secretVisibility === "hidden" ? "revealed" : "hidden";
2168
+ this.updateModeDetails({
2169
+ secretVisibility: next,
2170
+ validation: "suppressed",
2171
+ consumeSubmit: true
2172
+ });
2173
+ }
2174
+ }
2175
+ resetSecretVisibility() {
2176
+ if (this._details.secretVisibility === "revealed") this.updateModeDetails({ secretVisibility: "hidden" });
2177
+ }
2178
+ setValidationState(validation) {
2179
+ this.updateModeDetails({ validation });
2180
+ }
2181
+ suppressValidation() {
2182
+ this.updateModeDetails({
2183
+ validation: "suppressed",
2184
+ consumeSubmit: true
2185
+ });
2186
+ }
2187
+ restoreValidation() {
2188
+ if (this._details.validation === "suppressed") this.updateModeDetails({ validation: "pending" });
2189
+ }
2190
+ clearConsumeSubmit() {
2191
+ if (this._details.consumeSubmit) this.updateModeDetails({ consumeSubmit: false });
2192
+ }
2193
+ updateInput(value) {
2194
+ if (this._details.mode === "typing") this.updateModeDetails({
2195
+ inputValue: value,
2196
+ validation: "pending"
2197
+ });
2198
+ }
2199
+ clearInput() {
2200
+ this.updateModeDetails({
2201
+ inputValue: "",
2202
+ validation: "pending"
2203
+ });
2204
+ }
2205
+ isInInteraction(kind) {
2206
+ return this._details.mode === kind;
2207
+ }
2208
+ canTransitionToInteraction(kind) {
2209
+ switch (kind) {
2210
+ case "typing": return this._details.mode === "selection" && !this._details.toolbarOpen;
2211
+ case "selection": return this._details.mode === "typing";
2212
+ case "toolbar": return !this._details.toolbarOpen;
2213
+ default: return false;
2214
+ }
2215
+ }
2216
+ shouldPreventSubmission() {
2217
+ const snapshot = this.state;
2218
+ return !snapshot.canSubmit || snapshot.shouldConsumeSubmit;
2219
+ }
2220
+ isToolbarOpen() {
2221
+ return this._details.toolbarOpen;
2222
+ }
2223
+ isSecretRevealed() {
2224
+ return this._details.secretVisibility === "revealed";
2225
+ }
2226
+ hasSecret() {
2227
+ return this._details.secretVisibility !== "not-secret";
2228
+ }
2229
+ getCursor() {
2230
+ return this._details.cursor;
2231
+ }
2232
+ getInputValue() {
2233
+ return this._details.inputValue;
2234
+ }
2235
+ getIntention() {
2236
+ return this.intention;
2237
+ }
2238
+ };
2239
+
2240
+ //#endregion
2241
+ //#region ../prompt/src/prompts/processing/processValue.ts
2242
+ /**
2243
+ * Process a value through schema validation and return detailed results
2244
+ */
2245
+ function processValue(envKey, value, schema, preprocess) {
2246
+ try {
2247
+ if (!value || value.trim() === "") return {
2248
+ value: void 0,
2249
+ rawValue: value,
2250
+ isValid: true
2251
+ };
2252
+ const activePreprocessor = (() => {
2253
+ if (preprocess === false) return;
2254
+ if (preprocess === true) return resolvePreprocessor(schema.type, { [schema.type]: true });
2255
+ if (typeof preprocess === "function") return preprocess;
2256
+ return resolvePreprocessor(schema.type);
2257
+ })();
2258
+ const processedValue = activePreprocessor ? activePreprocessor(value) : value;
2259
+ if (schema.type === "boolean" && typeof processedValue === "boolean") return {
2260
+ value: processedValue,
2261
+ rawValue: value,
2262
+ isValid: true
2263
+ };
2264
+ if (schema.type === "number" && typeof processedValue === "number") return {
2265
+ value: processedValue,
2266
+ rawValue: value,
2267
+ isValid: true
2268
+ };
2269
+ if (typeof processedValue === "string") return {
2270
+ value: schema.process(processedValue),
2271
+ rawValue: value,
2272
+ isValid: true
2273
+ };
2274
+ return {
2275
+ value: schema.process(value),
2276
+ rawValue: value,
2277
+ isValid: true
2278
+ };
2279
+ } catch (error) {
2280
+ return {
2281
+ value: void 0,
2282
+ rawValue: value,
2283
+ isValid: false,
2284
+ error: error instanceof Error ? error.message : String(error)
2285
+ };
2286
+ }
2287
+ }
2288
+
2289
+ //#endregion
2290
+ //#region ../prompt/src/prompts/EnvPrompt.ts
2291
+ var EnvPrompt = class extends ThemedPrompt {
2292
+ /** Schema describing the environment variable. */
2293
+ schema;
2294
+ /** Flag indicating whether the variable must be provided. */
2295
+ required;
2296
+ /** Environment variable key, e.g. `NODE_ENV`. */
2297
+ key;
2298
+ /** Optional preprocessing applied before schema validation. */
2299
+ preprocess;
2300
+ /** Raw string value read from the environment. */
2301
+ rawCurrent;
2302
+ /** Result of preprocessing/validation for the raw current value. */
2303
+ currentResult;
2304
+ /** Latest committed value for this prompt, if any. */
2305
+ current;
2306
+ /** Fallback value supplied by the schema. */
2307
+ default;
2308
+ /** Maximum number of characters to display before truncation. */
2309
+ truncate;
2310
+ /** Zero-based index of this prompt in the session. */
2311
+ index;
2312
+ /** Total number of prompts in the session. */
2313
+ total;
2314
+ /** Indicates whether the value should be treated as secret. */
2315
+ secret;
2316
+ /** Internal helpers for managing clack prompt behavior. */
2317
+ internals;
2318
+ /** Toolbar instance controlling auxiliary actions. */
2319
+ toolbar;
2320
+ /** State machine managing prompt interaction modes. */
2321
+ mode;
2322
+ constructor(schema, opts) {
2323
+ const { pad = true,...promptOpts } = opts;
2324
+ const promptOptions = {
2325
+ ...promptOpts,
2326
+ default: schema.default,
2327
+ render: pad ? padActiveRender(promptOpts.render) : promptOpts.render
2328
+ };
2329
+ super(promptOptions);
2330
+ this.schema = schema;
2331
+ this.internals = new ClackPromptInternals(this);
2332
+ this.required = schema.required;
2333
+ this.internals.track = false;
2334
+ this.key = promptOptions.key;
2335
+ this.preprocess = promptOptions.preprocess;
2336
+ this.rawCurrent = promptOptions.current;
2337
+ if (this.rawCurrent !== void 0) {
2338
+ const result = processValue(this.key, this.rawCurrent, this.schema, this.preprocess ?? void 0);
2339
+ this.currentResult = result;
2340
+ this.current = result.isValid ? result.value : void 0;
2341
+ } else {
2342
+ this.currentResult = void 0;
2343
+ this.current = void 0;
2344
+ }
2345
+ this.default = schema.default;
2346
+ this.truncate = promptOptions.truncate ?? 40;
2347
+ this.index = promptOptions.index ?? 0;
2348
+ this.total = promptOptions.total ?? 1;
2349
+ const hasSecret = Boolean(promptOptions.secret);
2350
+ const hasOptions = this.rawCurrent !== void 0 || this.default !== void 0;
2351
+ this.secret = hasSecret;
2352
+ this.mode = new EnvPromptMode(createInitialModeDetails({
2353
+ hasSecret,
2354
+ hasOptions,
2355
+ initialInputValue: ""
2356
+ }));
2357
+ this.mode.subscribe((state) => {
2358
+ this.internals.track = state.shouldTrackInput;
2359
+ if (this.mode.hasSecret()) this.toolbar.secret = state.secretVisibility === "revealed" ? "shown" : "hidden";
2360
+ });
2361
+ this.toolbar = new Toolbar({
2362
+ previous: this.index > 0,
2363
+ secret: hasSecret ? this.mode.isSecretRevealed() ? "shown" : "hidden" : false,
2364
+ theme: this.theme,
2365
+ actions: {
2366
+ toggleSecret: () => this.handleToggleSecret(),
2367
+ skip: () => this.handleSkip(),
2368
+ previous: () => this.handlePrevious()
2369
+ }
2370
+ });
2371
+ this.on("finalize", () => {
2372
+ const shouldConsumeSubmit = this.mode.state.shouldConsumeSubmit;
2373
+ if (!shouldConsumeSubmit) this.mode.resetSecretVisibility();
2374
+ this.toolbar.close();
2375
+ if (shouldConsumeSubmit) {
2376
+ this.state = "active";
2377
+ this.error = "";
2378
+ this.mode.restoreValidation();
2379
+ this.mode.clearConsumeSubmit();
2380
+ this.mode.intention = "commit";
2381
+ }
2382
+ });
2383
+ }
2384
+ runSchemaValidation(value) {
2385
+ if (!value || value.trim() === "") return {
2386
+ success: true,
2387
+ value: void 0
2388
+ };
2389
+ const result = processValue(this.key, value, this.schema, this.preprocess ?? void 0);
2390
+ if (result.isValid) return {
2391
+ success: true,
2392
+ value: result.value
2393
+ };
2394
+ return {
2395
+ success: false,
2396
+ error: result.error ?? "Invalid value"
2397
+ };
2398
+ }
2399
+ setCommittedValue(value) {
2400
+ this.mode.intention = "commit";
2401
+ this.value = value;
2402
+ }
2403
+ getOutcome() {
2404
+ return this.mode.intention;
2405
+ }
2406
+ buildSkipHint(base) {
2407
+ const skipLower = "tab for options";
2408
+ const skipCapitalized = "Tab for options";
2409
+ if (base && base.trim().length > 0) return `${base} or ${skipLower}`;
2410
+ return skipCapitalized;
2411
+ }
2412
+ renderFooter(baseHint) {
2413
+ const errorFooter = this.renderFooterError();
2414
+ if (errorFooter) return errorFooter;
2415
+ const toolbarFooter = this.renderFooterToolbar();
2416
+ if (toolbarFooter) return toolbarFooter;
2417
+ return this.renderFooterHint(baseHint);
2418
+ }
2419
+ renderFooterError() {
2420
+ if (!this.error) return;
2421
+ return this.colors.warn(this.error);
2422
+ }
2423
+ renderFooterToolbar() {
2424
+ if (this.mode.hasSecret()) this.toolbar.secret = this.mode.isSecretRevealed() ? "shown" : "hidden";
2425
+ const toolbarOutput = this.toolbar.render();
2426
+ if (!toolbarOutput) return;
2427
+ return toolbarOutput;
2428
+ }
2429
+ renderFooterHint(baseHint) {
2430
+ const hint = this.buildSkipHint(baseHint);
2431
+ return this.colors.subtle(hint);
2432
+ }
2433
+ getFooterState() {
2434
+ if (this.error) return "warn";
2435
+ if (this.mode.isToolbarOpen()) return "tools";
2436
+ return "hint";
2437
+ }
2438
+ handleToolbarKey(char, info) {
2439
+ const handled = this.toolbar.handleKey(char, info);
2440
+ if (handled && info?.name === "tab") {
2441
+ if (this.toolbar.isOpen) this.mode.openToolbar();
2442
+ else this.mode.closeToolbar();
2443
+ return true;
2444
+ }
2445
+ if (handled && (info?.name === "return" || info?.name === "enter")) {
2446
+ if (this.toolbar.isOpen) this.mode.suppressValidation();
2447
+ if (!this.toolbar.isOpen && this.mode.isToolbarOpen()) this.mode.closeToolbar();
2448
+ return true;
2449
+ }
2450
+ if (handled && info?.name === "escape") {
2451
+ this.mode.closeToolbar();
2452
+ return true;
2453
+ }
2454
+ if (handled && info?.name === "backspace") {
2455
+ this.mode.closeToolbar();
2456
+ return false;
2457
+ }
2458
+ if (handled && char && char.length === 1 && !info?.ctrl && !info?.meta) {
2459
+ this.mode.closeToolbar();
2460
+ return false;
2461
+ }
2462
+ if (handled && !this.toolbar.isOpen && this.mode.isToolbarOpen()) this.mode.closeToolbar();
2463
+ return handled;
2464
+ }
2465
+ truncateValue(value) {
2466
+ if (value.length <= this.truncate) return value;
2467
+ return `${value.substring(0, this.truncate)}...`;
2468
+ }
2469
+ renderSkipped() {
2470
+ return `${this.colors.dim(this.theme.primary(S_STEP_SKIP))} ${this.colors.subtle(this.colors.bold(this.key))}`;
2471
+ }
2472
+ renderPrevious() {
2473
+ return `${this.colors.dim(this.theme.primary(S_STEP_PREVIOUS))} ${this.colors.subtle(this.colors.bold(this.key))}`;
2474
+ }
2475
+ renderOutcomeResult() {
2476
+ const intention = this.mode.intention;
2477
+ if (intention === "skip") return this.renderSkipped();
2478
+ if (intention === "previous") return this.renderPrevious();
2479
+ }
2480
+ renderCancelled() {
2481
+ return `${this.theme.error(S_STEP_CANCEL)} ${this.colors.subtle(this.colors.bold(this.key))}`;
2482
+ }
2483
+ toggleSecretReveal() {
2484
+ if (!this.mode.hasSecret()) return;
2485
+ this.mode.toggleSecretVisibility();
2486
+ if (this.mode.hasSecret()) this.toolbar.secret = this.mode.isSecretRevealed() ? "shown" : "hidden";
2487
+ }
2488
+ resetSecretReveal() {
2489
+ if (!this.mode.hasSecret()) return;
2490
+ this.mode.resetSecretVisibility();
2491
+ }
2492
+ isSecretRevealed() {
2493
+ return this.mode.isSecretRevealed();
2494
+ }
2495
+ handleToggleSecret() {
2496
+ this.toggleSecretReveal();
2497
+ }
2498
+ handleSkip() {
2499
+ this.mode.intention = "skip";
2500
+ this.value = void 0;
2501
+ this.state = "submit";
2502
+ }
2503
+ handlePrevious() {
2504
+ this.mode.intention = "previous";
2505
+ this.value = void 0;
2506
+ this.state = "submit";
2507
+ }
2508
+ consumeSkipValidation() {
2509
+ if (this.mode.state.shouldSkipValidation) {
2510
+ this.mode.restoreValidation();
2511
+ return true;
2512
+ }
2513
+ return false;
2514
+ }
2515
+ getAnnotationLabel(value) {
2516
+ const matchesCurrent = Boolean(this.currentResult?.isValid) && this.current === value;
2517
+ const matchesDefault = this.default === value;
2518
+ return this.buildAnnotation({
2519
+ isCurrent: matchesCurrent,
2520
+ isDefault: matchesDefault
2521
+ });
2522
+ }
2523
+ /**
2524
+ * Clears any active validation error so the prompt can return to the default hint state.
2525
+ */
2526
+ clearErrorState() {
2527
+ if (this.state === "error" || this.error) {
2528
+ this.state = "active";
2529
+ this.error = "";
2530
+ this.mode.restoreValidation();
2531
+ this.mode.clearConsumeSubmit();
2532
+ }
2533
+ }
2534
+ buildAnnotation(flags) {
2535
+ const labels = [];
2536
+ if (flags.isCurrent) labels.push("current");
2537
+ if (flags.isDefault) labels.push("default");
2538
+ if (flags.invalid) labels.push("invalid");
2539
+ return labels.length > 0 ? labels.join(", ") : void 0;
2540
+ }
2541
+ };
2542
+
2543
+ //#endregion
2544
+ //#region ../prompt/src/prompts/utils/selectableOptions.ts
2545
+ function buildSelectableOptions(params) {
2546
+ const invalidOptionKey = params.invalidOptionKey ?? "invalid";
2547
+ const baseOptions = params.baseOptions.map((option) => ({ ...option }));
2548
+ const currentRaw = params.currentResult?.rawValue;
2549
+ if (!(currentRaw !== void 0 && params.currentResult?.isValid === false)) return baseOptions;
2550
+ return [{
2551
+ key: invalidOptionKey,
2552
+ value: void 0,
2553
+ display: params.formatInvalidDisplay(currentRaw),
2554
+ annotation: params.buildAnnotation({
2555
+ isCurrent: true,
2556
+ invalid: true
2557
+ }) ?? void 0,
2558
+ invalid: true
2559
+ }, ...baseOptions];
2560
+ }
2561
+ function resolveInitialCursor(options, params) {
2562
+ if (!options.length) return 0;
2563
+ const equals = params.isEqual ?? ((left, right) => left === right);
2564
+ const findIndexForValue = (value) => {
2565
+ if (value === void 0) return -1;
2566
+ return options.findIndex((option) => !option.invalid && equals(option.value, value));
2567
+ };
2568
+ const currentIndex = findIndexForValue(params.currentValue);
2569
+ if (currentIndex >= 0) return currentIndex;
2570
+ const defaultIndex = findIndexForValue(params.defaultValue);
2571
+ if (defaultIndex >= 0) return defaultIndex;
2572
+ const firstValid = options.findIndex((option) => !option.invalid);
2573
+ return firstValid >= 0 ? firstValid : 0;
2574
+ }
2575
+ function getOptionAtCursor(options, cursor) {
2576
+ if (!options.length) return {
2577
+ option: void 0,
2578
+ index: 0
2579
+ };
2580
+ const index = Math.max(0, Math.min(cursor, options.length - 1));
2581
+ return {
2582
+ option: options[index],
2583
+ index
2584
+ };
2585
+ }
2586
+
2587
+ //#endregion
2588
+ //#region ../prompt/src/prompts/typed/EnvBooleanPrompt.ts
2589
+ var EnvBooleanPrompt = class extends EnvPrompt {
2590
+ cursor;
2591
+ constructor(schema, opts) {
2592
+ super(schema, {
2593
+ ...opts,
2594
+ render: function() {
2595
+ if (this.state === "submit") {
2596
+ const outcomeResult = this.renderOutcomeResult();
2597
+ if (outcomeResult) return outcomeResult;
2598
+ const valueStr = this.value ? "true" : "false";
2599
+ return `${this.getSymbol()} ${this.colors.bold(this.colors.white(this.key))}${this.colors.subtle("=")}${this.colors.white(this.truncateValue(valueStr))}`;
2600
+ }
2601
+ if (this.state === "cancel") return this.renderCancelled();
2602
+ let output = "";
2603
+ output += `${this.getSymbol()} ${this.colors.bold(this.colors.white(this.key))}`;
2604
+ if (this.schema.description) output += ` ${this.colors.subtle(this.schema.description)}`;
2605
+ output += "\n";
2606
+ const options$1 = this.buildOptions();
2607
+ const dimInputs = !this.error && this.mode.isToolbarOpen();
2608
+ options$1.forEach((option, index) => {
2609
+ const isSelected = index === this.cursor;
2610
+ const circle = dimInputs ? this.colors.dim(isSelected ? S_RADIO_ACTIVE : S_RADIO_INACTIVE) : isSelected ? this.theme.primary(S_RADIO_ACTIVE) : this.colors.dim(S_RADIO_INACTIVE);
2611
+ const formatText = (value) => {
2612
+ if (dimInputs) return this.colors.dim(value);
2613
+ if (isSelected) return this.colors.white(value);
2614
+ return this.colors.subtle(value);
2615
+ };
2616
+ let text = formatText(option.display);
2617
+ if (option.invalid) text = `\u001b[9m${text}\u001b[29m`;
2618
+ const annotation = option.annotation ? ` (${option.annotation})` : "";
2619
+ let suffix = "";
2620
+ if (annotation && isSelected) suffix = dimInputs ? this.colors.dim(annotation) : this.colors.subtle(annotation);
2621
+ output += `${this.getBar()} ${circle} ${text}${suffix}\n`;
2622
+ });
2623
+ output += `${this.getBarEnd()} ${this.renderFooter()}`;
2624
+ return output;
2625
+ },
2626
+ validate: (_value) => {
2627
+ if (this.consumeSkipValidation()) return;
2628
+ if (this.getOutcome() !== "commit") return;
2629
+ const selectedOption = this.getSelectedOption();
2630
+ if (selectedOption?.invalid) return this.currentResult?.error ?? "Current value is invalid";
2631
+ const candidateValue = selectedOption && selectedOption.value !== void 0 ? selectedOption.value : this.default ?? false;
2632
+ const validation = this.runSchemaValidation(candidateValue.toString());
2633
+ if (!validation.success) return validation.error;
2634
+ }
2635
+ });
2636
+ const options = this.buildOptions();
2637
+ this.cursor = this.getInitialCursor(options);
2638
+ this.updateValue();
2639
+ this.on("cursor", (action) => {
2640
+ this.clearErrorState();
2641
+ if (!this.error && this.mode.isToolbarOpen()) return;
2642
+ const options$1 = this.buildOptions();
2643
+ if (!options$1.length) return;
2644
+ const lastIndex = options$1.length - 1;
2645
+ switch (action) {
2646
+ case "up":
2647
+ this.cursor = this.cursor === 0 ? lastIndex : this.cursor - 1;
2648
+ break;
2649
+ case "down":
2650
+ this.cursor = this.cursor >= lastIndex ? 0 : this.cursor + 1;
2651
+ break;
2652
+ default:
2653
+ if (this.cursor > lastIndex) this.cursor = lastIndex;
2654
+ if (this.cursor < 0) this.cursor = 0;
2655
+ break;
2656
+ }
2657
+ this.updateValue();
2658
+ });
2659
+ this.on("key", (char, info) => {
2660
+ if (!info) return;
2661
+ this.clearErrorState();
2662
+ if (this.handleToolbarKey(char, info)) return;
2663
+ if (!this.error && this.mode.isToolbarOpen()) return;
2664
+ });
2665
+ }
2666
+ updateValue() {
2667
+ const selected = this.getSelectedOption();
2668
+ if (!selected || selected.invalid) {
2669
+ this.setCommittedValue(this.default ?? false);
2670
+ return;
2671
+ }
2672
+ this.setCommittedValue(selected.value ?? this.default ?? false);
2673
+ }
2674
+ buildOptions() {
2675
+ return buildSelectableOptions({
2676
+ currentResult: this.currentResult,
2677
+ formatInvalidDisplay: (raw) => this.truncateValue(raw ?? ""),
2678
+ buildAnnotation: (flags) => this.buildAnnotation(flags) ?? void 0,
2679
+ baseOptions: [{
2680
+ key: "true",
2681
+ value: true,
2682
+ display: "true",
2683
+ annotation: this.getAnnotationLabel(true) ?? void 0
2684
+ }, {
2685
+ key: "false",
2686
+ value: false,
2687
+ display: "false",
2688
+ annotation: this.getAnnotationLabel(false) ?? void 0
2689
+ }]
2690
+ });
2691
+ }
2692
+ getInitialCursor(options) {
2693
+ return resolveInitialCursor(options, {
2694
+ currentValue: this.currentResult?.isValid !== false ? this.current : void 0,
2695
+ defaultValue: this.default
2696
+ });
2697
+ }
2698
+ getSelectedOption() {
2699
+ const { option, index } = getOptionAtCursor(this.buildOptions(), this.cursor);
2700
+ if (index !== this.cursor) this.cursor = index;
2701
+ return option;
2702
+ }
2703
+ };
2704
+
2705
+ //#endregion
2706
+ //#region ../prompt/src/prompts/typed/EnvEnumPrompt.ts
2707
+ var EnvEnumPrompt = class extends EnvPrompt {
2708
+ cursor = 0;
2709
+ options;
2710
+ values;
2711
+ constructor(schema, opts) {
2712
+ super(schema, {
2713
+ ...opts,
2714
+ render: function() {
2715
+ if (this.state === "submit") {
2716
+ const outcomeResult = this.renderOutcomeResult();
2717
+ if (outcomeResult) return outcomeResult;
2718
+ return `${this.getSymbol()} ${this.colors.bold(this.colors.white(this.key))}${this.colors.subtle("=")}${this.colors.white(this.truncateValue(this.value ?? ""))}`;
2719
+ }
2720
+ if (this.state === "cancel") return this.renderCancelled();
2721
+ let output = "";
2722
+ output += `${this.getSymbol()} ${this.colors.bold(this.colors.white(this.key))}`;
2723
+ if (this.schema.description) output += ` ${this.colors.subtle(this.schema.description)}`;
2724
+ output += "\n";
2725
+ const options$1 = this.buildOptions();
2726
+ const dimInputs = !this.error && this.mode.isToolbarOpen();
2727
+ options$1.forEach((option, index) => {
2728
+ const isSelected = index === this.cursor;
2729
+ const circle = dimInputs ? this.colors.dim(isSelected ? S_RADIO_ACTIVE : S_RADIO_INACTIVE) : isSelected ? this.theme.primary(S_RADIO_ACTIVE) : this.colors.dim(S_RADIO_INACTIVE);
2730
+ const formatText = (value) => {
2731
+ if (dimInputs) return this.colors.dim(value);
2732
+ if (isSelected) return this.colors.white(value);
2733
+ return this.colors.subtle(value);
2734
+ };
2735
+ let text = formatText(option.display);
2736
+ if (option.invalid) text = `\u001b[9m${text}\u001b[29m`;
2737
+ const annotation = option.annotation ? ` (${option.annotation})` : "";
2738
+ let suffix = "";
2739
+ if (annotation && isSelected) suffix = dimInputs ? this.colors.dim(annotation) : this.colors.subtle(annotation);
2740
+ output += `${this.getBar()} ${circle} ${text}${suffix}\n`;
2741
+ });
2742
+ output += `${this.getBarEnd()} ${this.renderFooter()}`;
2743
+ return output;
2744
+ },
2745
+ validate: () => {
2746
+ if (this.consumeSkipValidation()) return;
2747
+ if (this.getOutcome() !== "commit") return;
2748
+ const selectedOption = this.getSelectedOption();
2749
+ if (!selectedOption) return;
2750
+ if (selectedOption.invalid) return this.currentResult?.error ?? "Current value is invalid";
2751
+ const candidateValue = selectedOption.value ?? this.default ?? this.values[0];
2752
+ if (candidateValue === void 0) return;
2753
+ const validation = this.runSchemaValidation(candidateValue);
2754
+ if (!validation.success) return validation.error;
2755
+ }
2756
+ });
2757
+ this.options = opts;
2758
+ this.values = [...schema.values];
2759
+ const options = this.buildOptions();
2760
+ this.cursor = this.getInitialCursor(options);
2761
+ this.updateValue();
2762
+ this.on("cursor", (action) => {
2763
+ this.clearErrorState();
2764
+ if (!this.error && this.mode.isToolbarOpen()) return;
2765
+ const options$1 = this.buildOptions();
2766
+ if (!options$1.length) return;
2767
+ const lastIndex = options$1.length - 1;
2768
+ switch (action) {
2769
+ case "up":
2770
+ this.cursor = this.cursor === 0 ? lastIndex : this.cursor - 1;
2771
+ break;
2772
+ case "down":
2773
+ this.cursor = this.cursor >= lastIndex ? 0 : this.cursor + 1;
2774
+ break;
2775
+ default:
2776
+ if (this.cursor > lastIndex) this.cursor = lastIndex;
2777
+ if (this.cursor < 0) this.cursor = 0;
2778
+ break;
2779
+ }
2780
+ this.updateValue();
2781
+ });
2782
+ this.on("key", (char, info) => {
2783
+ if (!info) return;
2784
+ this.clearErrorState();
2785
+ if (this.handleToolbarKey(char, info)) return;
2786
+ if (!this.error && this.mode.isToolbarOpen()) return;
2787
+ });
2788
+ }
2789
+ updateValue() {
2790
+ const selected = this.getSelectedOption();
2791
+ if (!selected) {
2792
+ this.setCommittedValue(this.default ?? this.values[0]);
2793
+ return;
2794
+ }
2795
+ if (selected.invalid) {
2796
+ const fallback$1 = this.default ?? this.values[0];
2797
+ this.setCommittedValue(fallback$1);
2798
+ return;
2799
+ }
2800
+ const fallback = this.default ?? this.values[0];
2801
+ this.setCommittedValue(selected.value ?? fallback);
2802
+ }
2803
+ buildOptions() {
2804
+ return buildSelectableOptions({
2805
+ currentResult: this.currentResult,
2806
+ formatInvalidDisplay: (raw) => this.truncateValue(raw ?? ""),
2807
+ buildAnnotation: (flags) => this.buildAnnotation(flags) ?? void 0,
2808
+ baseOptions: this.values.map((value) => ({
2809
+ key: value,
2810
+ value,
2811
+ display: this.truncateValue(value),
2812
+ annotation: this.getAnnotationLabel(value) ?? void 0
2813
+ }))
2814
+ });
2815
+ }
2816
+ getInitialCursor(options) {
2817
+ return resolveInitialCursor(options, {
2818
+ currentValue: this.currentResult?.isValid !== false ? this.current : void 0,
2819
+ defaultValue: this.default
2820
+ });
2821
+ }
2822
+ getSelectedOption() {
2823
+ const { option, index } = getOptionAtCursor(this.buildOptions(), this.cursor);
2824
+ if (index !== this.cursor) this.cursor = index;
2825
+ return option;
2826
+ }
2827
+ };
2828
+
2829
+ //#endregion
2830
+ //#region ../prompt/src/prompts/typed/EnvNumberPrompt.ts
2831
+ var EnvNumberPrompt = class extends EnvPrompt {
2832
+ otherInputCache = "";
2833
+ shouldStitchInput = false;
2834
+ isRestoringInput = false;
2835
+ constructor(schema, opts) {
2836
+ super(schema, {
2837
+ ...opts,
2838
+ render: function() {
2839
+ if (this.state === "submit") {
2840
+ const outcomeResult = this.renderOutcomeResult();
2841
+ if (outcomeResult) return outcomeResult;
2842
+ return `${this.getSymbol()} ${this.colors.bold(this.colors.white(this.key))}${this.colors.subtle("=")}${this.colors.white(this.formatValue(this.value))}`;
2843
+ }
2844
+ if (this.state === "cancel") return this.renderCancelled();
2845
+ let output = "";
2846
+ output += `${this.getSymbol()} ${this.colors.bold(this.colors.white(this.key))}`;
2847
+ if (this.schema.description) output += ` ${this.colors.subtle(this.schema.description)}`;
2848
+ output += "\n";
2849
+ const dimInputs = !this.error && this.mode.isToolbarOpen();
2850
+ if (!this.hasPresetOptions()) {
2851
+ if (this.mode.isInInteraction("typing")) {
2852
+ const displayText = dimInputs ? this.colors.dim(this.getInputDisplay(false)) : this.colors.white(this.getInputDisplay(true));
2853
+ output += `${this.getBar()} ${displayText}`;
2854
+ } else {
2855
+ const idleDisplay = dimInputs ? this.colors.dim(this.getInputDisplay(false)) : this.colors.white(this.getInputDisplay(true));
2856
+ output += `${this.getBar()} ${idleDisplay}`;
2857
+ }
2858
+ output += "\n";
2859
+ output += `${this.getBarEnd()} ${this.renderFooter("Enter a number")}`;
2860
+ return output;
2861
+ }
2862
+ this.buildSelectionOptions().forEach((option, index) => {
2863
+ const isSelected = index === this.mode.getCursor();
2864
+ const circle = dimInputs ? this.colors.dim(isSelected ? S_RADIO_ACTIVE : S_RADIO_INACTIVE) : isSelected ? this.theme.primary(S_RADIO_ACTIVE) : this.colors.dim(S_RADIO_INACTIVE);
2865
+ if (option.type === "other") {
2866
+ if (this.mode.isInInteraction("typing")) {
2867
+ const displayText = dimInputs ? this.colors.dim(this.getInputDisplay(false)) : this.colors.white(this.getInputDisplay(true));
2868
+ output += `${this.getBar()} ${circle} ${displayText}\n`;
2869
+ } else if (isSelected) if (dimInputs) output += `${this.getBar()} ${circle} ${this.colors.dim(option.label)}\n`;
2870
+ else output += `${this.getBar()} ${circle} ${this.colors.white(this.getInputDisplay(true))}\n`;
2871
+ else {
2872
+ const text$1 = dimInputs ? this.colors.dim(option.label) : this.colors.subtle(option.label);
2873
+ output += `${this.getBar()} ${circle} ${text$1}\n`;
2874
+ }
2875
+ return;
2876
+ }
2877
+ const formatText = (value) => {
2878
+ if (dimInputs) return this.colors.dim(value);
2879
+ if (isSelected) return this.colors.white(value);
2880
+ return this.colors.subtle(value);
2881
+ };
2882
+ let text = formatText(option.display);
2883
+ if (option.invalid) text = `\u001b[9m${text}\u001b[29m`;
2884
+ const annotation = option.annotation ? ` (${option.annotation})` : "";
2885
+ let suffix = "";
2886
+ if (annotation && isSelected) suffix = dimInputs ? this.colors.dim(annotation) : this.colors.subtle(annotation);
2887
+ output += `${this.getBar()} ${circle} ${text}${suffix}\n`;
2888
+ });
2889
+ output += `${this.getBarEnd()} ${this.renderFooter("Enter a number")}`;
2890
+ return output;
2891
+ },
2892
+ validate: (_value) => {
2893
+ if (this.consumeSkipValidation()) return;
2894
+ if (this.getOutcome() !== "commit") return;
2895
+ if (!this.hasPresetOptions()) {
2896
+ if (!this.userInput || !this.userInput.trim()) return "Please enter a number";
2897
+ const validation = this.runSchemaValidation(this.userInput);
2898
+ if (!validation.success) return validation.error;
2899
+ return;
2900
+ }
2901
+ const selectedOption = this.getSelectedOption();
2902
+ if (!this.mode.isInInteraction("typing") && selectedOption && selectedOption.type === "value" && selectedOption.key === "current" && selectedOption.invalid) return this.currentResult?.error ?? "Current value is invalid";
2903
+ const textInputIndex = this.getTextInputIndex();
2904
+ if (this.mode.getCursor() === textInputIndex && !this.mode.isInInteraction("typing")) {
2905
+ this.mode.enterTyping();
2906
+ this.mode.clearInput();
2907
+ this._setUserInput("");
2908
+ this.otherInputCache = "";
2909
+ this.updateValue();
2910
+ return "Please enter a number";
2911
+ }
2912
+ if (this.mode.getCursor() === textInputIndex && this.mode.isInInteraction("typing") && (!this.userInput || !this.userInput.trim())) return "Please enter a number";
2913
+ if (this.mode.isInInteraction("typing") && this.userInput) {
2914
+ const inputValidation = this.validateInput(this.userInput);
2915
+ if (inputValidation) return inputValidation;
2916
+ const validation = this.runSchemaValidation(this.userInput);
2917
+ if (!validation.success) return validation.error;
2918
+ }
2919
+ if (!this.mode.isInInteraction("typing")) {
2920
+ const candidate = selectedOption && selectedOption.type === "value" ? selectedOption.value : this.value;
2921
+ const validation = this.runSchemaValidation(candidate !== void 0 ? candidate.toString() : void 0);
2922
+ if (!validation.success) return validation.error;
2923
+ }
2924
+ }
2925
+ });
2926
+ if (!this.hasPresetOptions()) {
2927
+ this.mode.enterTyping();
2928
+ this.mode.clearInput();
2929
+ this._setUserInput("");
2930
+ this.otherInputCache = "";
2931
+ this.setCommittedValue(this.getDefaultValue());
2932
+ } else {
2933
+ const options = this.buildValueOptions();
2934
+ const currentValue = this.currentResult?.isValid !== false ? this.current : void 0;
2935
+ const defaultValue = this.default;
2936
+ const baseCursor = resolveInitialCursor(options, {
2937
+ currentValue,
2938
+ defaultValue
2939
+ });
2940
+ const initialCursor = options[baseCursor]?.invalid ? options.length : baseCursor;
2941
+ this.mode.setCursor(initialCursor);
2942
+ this.updateValue();
2943
+ queueMicrotask(() => {
2944
+ const refreshedOptions = this.buildValueOptions();
2945
+ const refreshedBase = resolveInitialCursor(refreshedOptions, {
2946
+ currentValue,
2947
+ defaultValue
2948
+ });
2949
+ const refreshedCursor = refreshedOptions[refreshedBase]?.invalid ? refreshedOptions.length : refreshedBase;
2950
+ this.mode.setCursor(refreshedCursor);
2951
+ this.updateValue();
2952
+ });
2953
+ }
2954
+ this.on("cursor", (action) => {
2955
+ this.clearErrorState();
2956
+ if (!this.hasPresetOptions()) return;
2957
+ if (!this.error && this.mode.isToolbarOpen()) return;
2958
+ switch (action) {
2959
+ case "up":
2960
+ const maxIndex = this.buildSelectionOptions().length - 1;
2961
+ if (this.mode.isInInteraction("typing") || this.mode.getCursor() === maxIndex) {
2962
+ this.mode.exitTyping();
2963
+ this._clearUserInput();
2964
+ this.mode.clearInput();
2965
+ this.otherInputCache = "";
2966
+ }
2967
+ this.mode.moveCursor("up", maxIndex);
2968
+ break;
2969
+ case "down":
2970
+ const maxIndexDown = this.buildSelectionOptions().length - 1;
2971
+ if (this.mode.isInInteraction("typing") || this.mode.getCursor() === maxIndexDown) {
2972
+ this.mode.exitTyping();
2973
+ this._clearUserInput();
2974
+ this.mode.clearInput();
2975
+ this.otherInputCache = "";
2976
+ }
2977
+ this.mode.moveCursor("down", maxIndexDown);
2978
+ break;
2979
+ }
2980
+ this.updateValue();
2981
+ });
2982
+ this.on("userInput", (rawInput) => {
2983
+ this.clearErrorState();
2984
+ let input = rawInput.includes(" ") ? rawInput.replace(/\t/g, "") : rawInput;
2985
+ if (this.isRestoringInput) {
2986
+ this.isRestoringInput = false;
2987
+ this.otherInputCache = input;
2988
+ return;
2989
+ }
2990
+ if (this.mode.isInInteraction("typing")) {
2991
+ let nextInput = input;
2992
+ if (this.shouldStitchInput && this.otherInputCache) if (!input || input === this.otherInputCache) nextInput = this.otherInputCache;
2993
+ else if (input.startsWith(this.otherInputCache)) {
2994
+ nextInput = input;
2995
+ this.shouldStitchInput = false;
2996
+ } else {
2997
+ nextInput = `${this.otherInputCache}${input}`;
2998
+ this.shouldStitchInput = false;
2999
+ }
3000
+ else this.shouldStitchInput = false;
3001
+ this.mode.updateInput(nextInput);
3002
+ this.userInput = nextInput;
3003
+ this.otherInputCache = nextInput;
3004
+ try {
3005
+ const parsed = this.parseInput(nextInput);
3006
+ this.setCommittedValue(parsed ?? this.getDefaultValue());
3007
+ } catch {}
3008
+ } else this.shouldStitchInput = false;
3009
+ });
3010
+ this.on("key", (char, info) => {
3011
+ if (!info) return;
3012
+ this.clearErrorState();
3013
+ if (this.handleToolbarKey(char, info)) return;
3014
+ if (!this.error && this.mode.isToolbarOpen()) return;
3015
+ if (!this.hasPresetOptions()) {
3016
+ if (this.mode.isInInteraction("typing")) try {
3017
+ const parsed = this.parseInput(this.userInput);
3018
+ this.setCommittedValue(parsed ?? this.getDefaultValue());
3019
+ } catch {}
3020
+ return;
3021
+ }
3022
+ if (char && char.length === 1 && !info.ctrl && !info.meta && !this.mode.isInInteraction("typing")) {
3023
+ const isArrowKey = [
3024
+ "up",
3025
+ "down",
3026
+ "left",
3027
+ "right"
3028
+ ].includes(info.name || "");
3029
+ const isControlKey = [
3030
+ "return",
3031
+ "enter",
3032
+ "escape",
3033
+ "tab"
3034
+ ].includes(info.name || "");
3035
+ if (!isArrowKey && !isControlKey) {
3036
+ const textInputIndex$1 = this.getTextInputIndex();
3037
+ this.mode.setCursor(textInputIndex$1);
3038
+ const existingInput = this.mode.getInputValue() || this.userInput || this.otherInputCache || "";
3039
+ this.mode.enterTyping(existingInput);
3040
+ const nextInput = `${existingInput}${char}`;
3041
+ this.otherInputCache = nextInput;
3042
+ this._setUserInput(nextInput);
3043
+ this.mode.updateInput(nextInput);
3044
+ this.syncCursorToInputEnd();
3045
+ this.updateValue();
3046
+ return;
3047
+ }
3048
+ }
3049
+ const textInputIndex = this.getTextInputIndex();
3050
+ if (this.mode.getCursor() === textInputIndex) {
3051
+ if (info.name === "escape") {
3052
+ this.mode.exitTyping();
3053
+ this._clearUserInput();
3054
+ this.mode.clearInput();
3055
+ this.otherInputCache = "";
3056
+ this.updateValue();
3057
+ return;
3058
+ }
3059
+ }
3060
+ });
3061
+ }
3062
+ getInputDisplay(includeCursor) {
3063
+ const inputValue = this.mode.getInputValue();
3064
+ if (!includeCursor) return inputValue;
3065
+ const rawCursor = this.mode.isInInteraction("typing") ? Math.max(0, this._cursor ?? inputValue.length) : 0;
3066
+ const cursorIndex = Math.min(rawCursor, inputValue.length);
3067
+ if (cursorIndex >= inputValue.length) return `${inputValue}${S_CURSOR}`;
3068
+ const before = inputValue.slice(0, cursorIndex);
3069
+ const cursorChar = inputValue.charAt(cursorIndex) || " ";
3070
+ const after = inputValue.slice(cursorIndex + 1);
3071
+ return `${before}${this.colors.inverse(cursorChar)}${after}`;
3072
+ }
3073
+ syncCursorToInputEnd() {
3074
+ const cursorHost = this;
3075
+ cursorHost._cursor = this.mode.getInputValue().length;
3076
+ }
3077
+ toggleSecretReveal() {
3078
+ const cachedInput = this.mode.getInputValue() || this.userInput || this.otherInputCache;
3079
+ super.toggleSecretReveal();
3080
+ if (!cachedInput) return;
3081
+ this.shouldStitchInput = Boolean(this.otherInputCache || cachedInput);
3082
+ const stitchedBaseline = cachedInput;
3083
+ queueMicrotask(() => {
3084
+ const restored = this.otherInputCache || stitchedBaseline;
3085
+ if (!restored) return;
3086
+ if (!this.mode.isInInteraction("typing")) this.mode.enterTyping(restored);
3087
+ this.isRestoringInput = true;
3088
+ this.internals.track = true;
3089
+ this.mode.updateInput(restored);
3090
+ this.otherInputCache = restored;
3091
+ this._setUserInput(restored, true);
3092
+ this.syncCursorToInputEnd();
3093
+ });
3094
+ }
3095
+ updateValue() {
3096
+ if (!this.hasPresetOptions()) {
3097
+ try {
3098
+ const parsed = this.parseInput(this.mode.getInputValue());
3099
+ this.setCommittedValue(parsed ?? this.getDefaultValue());
3100
+ } catch {
3101
+ this.setCommittedValue(this.getDefaultValue());
3102
+ }
3103
+ return;
3104
+ }
3105
+ if (!this.mode.isInInteraction("typing")) {
3106
+ const selected = this.buildSelectionOptions()[this.mode.getCursor()];
3107
+ if (!selected) {
3108
+ this.setCommittedValue(this.getDefaultValue());
3109
+ return;
3110
+ }
3111
+ if (selected.type === "value") {
3112
+ if (selected.invalid) {
3113
+ this.setCommittedValue(this.getDefaultValue());
3114
+ return;
3115
+ }
3116
+ this.setCommittedValue(selected.value ?? this.getDefaultValue());
3117
+ return;
3118
+ }
3119
+ this.setCommittedValue(this.getDefaultValue());
3120
+ } else try {
3121
+ const parsed = this.parseInput(this.mode.getInputValue());
3122
+ this.setCommittedValue(parsed ?? this.getDefaultValue());
3123
+ } catch {
3124
+ this.setCommittedValue(this.getDefaultValue());
3125
+ }
3126
+ }
3127
+ formatValue(value) {
3128
+ const str = value !== void 0 ? value.toString() : "";
3129
+ return this.truncateValue(str);
3130
+ }
3131
+ parseInput(input) {
3132
+ if (!input || !input.trim()) return;
3133
+ const parsed = Number(input.trim());
3134
+ if (isNaN(parsed)) return;
3135
+ return parsed;
3136
+ }
3137
+ validateInput(input) {
3138
+ if (!input || !input.trim()) return "Please enter a number";
3139
+ const parsed = Number(input.trim());
3140
+ if (isNaN(parsed)) return "Please enter a valid number";
3141
+ }
3142
+ getDefaultValue() {
3143
+ return 0;
3144
+ }
3145
+ hasPresetOptions() {
3146
+ return this.currentResult?.rawValue !== void 0 || this.default !== void 0;
3147
+ }
3148
+ buildValueOptions() {
3149
+ const hasValidCurrent = this.currentResult?.isValid !== false && this.current !== void 0;
3150
+ const baseOptions = [];
3151
+ if (hasValidCurrent && this.current !== void 0) {
3152
+ const isSameAsDefault = this.current === this.default;
3153
+ baseOptions.push({
3154
+ key: "current",
3155
+ value: this.current,
3156
+ display: this.formatValue(this.current),
3157
+ annotation: this.buildAnnotation({
3158
+ isCurrent: true,
3159
+ isDefault: isSameAsDefault
3160
+ }) ?? void 0
3161
+ });
3162
+ }
3163
+ if (this.default !== void 0 && (!hasValidCurrent || this.current !== this.default) && this.default !== void 0) {
3164
+ const isSameAsCurrent = hasValidCurrent && this.current === this.default;
3165
+ baseOptions.push({
3166
+ key: "default",
3167
+ value: this.default,
3168
+ display: this.formatValue(this.default),
3169
+ annotation: this.buildAnnotation({
3170
+ isDefault: true,
3171
+ isCurrent: isSameAsCurrent
3172
+ }) ?? void 0
3173
+ });
3174
+ }
3175
+ return buildSelectableOptions({
3176
+ currentResult: this.currentResult,
3177
+ formatInvalidDisplay: (raw) => this.formatRawValue(raw ?? ""),
3178
+ buildAnnotation: (flags) => this.buildAnnotation(flags) ?? void 0,
3179
+ baseOptions,
3180
+ invalidOptionKey: "current"
3181
+ });
3182
+ }
3183
+ buildSelectionOptions() {
3184
+ const options = this.buildValueOptions().map((option) => ({
3185
+ type: "value",
3186
+ key: option.key,
3187
+ value: option.value,
3188
+ display: option.display,
3189
+ annotation: option.annotation,
3190
+ invalid: option.invalid
3191
+ }));
3192
+ options.push({
3193
+ type: "other",
3194
+ label: "Other"
3195
+ });
3196
+ return options;
3197
+ }
3198
+ getSelectedOption() {
3199
+ if (!this.hasPresetOptions()) return;
3200
+ return this.buildSelectionOptions()[this.mode.getCursor()];
3201
+ }
3202
+ formatRawValue(raw) {
3203
+ if (!raw) return "";
3204
+ return this.truncateValue(raw);
3205
+ }
3206
+ getTextInputIndex() {
3207
+ if (!this.hasPresetOptions()) return 0;
3208
+ const options = this.buildSelectionOptions();
3209
+ const index = options.findIndex((option) => option.type === "other");
3210
+ return index === -1 ? options.length - 1 : index;
3211
+ }
3212
+ };
3213
+
3214
+ //#endregion
3215
+ //#region ../prompt/src/utils/secrets.ts
3216
+ function isSecretMatch(value, pattern) {
3217
+ if (!value) return false;
3218
+ if (typeof pattern === "string") {
3219
+ const needle = pattern.trim().toLowerCase();
3220
+ if (!needle) return false;
3221
+ return value.toLowerCase().includes(needle);
3222
+ }
3223
+ pattern.lastIndex = 0;
3224
+ const matched = pattern.test(value);
3225
+ pattern.lastIndex = 0;
3226
+ return matched;
3227
+ }
3228
+ function isSecretKey(key, description, patterns) {
3229
+ if (patterns.length === 0) return false;
3230
+ for (const pattern of patterns) if (isSecretMatch(key, pattern) || isSecretMatch(description, pattern)) return true;
3231
+ return false;
3232
+ }
3233
+ function maskSecretValue(value, maskChar = SECRET_MASK) {
3234
+ if (!value) return value;
3235
+ return value.replace(/./g, maskChar);
3236
+ }
3237
+ function resolveShouldMask(key, schema, patterns) {
3238
+ if (schema.type !== "string") return false;
3239
+ if ("secret" in schema && schema.secret !== void 0) return schema.secret;
3240
+ return isSecretKey(key, schema.description, patterns);
3241
+ }
3242
+
3243
+ //#endregion
3244
+ //#region ../prompt/src/prompts/typed/EnvStringPrompt.ts
3245
+ var EnvStringPrompt = class extends EnvPrompt {
3246
+ otherInputCache = "";
3247
+ shouldStitchInput = false;
3248
+ isRestoringInput = false;
3249
+ constructor(schema, opts) {
3250
+ super(schema, {
3251
+ ...opts,
3252
+ render: function() {
3253
+ if (this.state === "submit") {
3254
+ const outcomeResult = this.renderOutcomeResult();
3255
+ if (outcomeResult) return outcomeResult;
3256
+ const base = `${this.getSymbol()} ${this.colors.bold(this.colors.white(this.key))}`;
3257
+ if (!this.required && (this.value === void 0 || this.value === "")) return base;
3258
+ return `${base}${this.colors.subtle("=")}${this.colors.white(this.formatValue(this.value))}`;
3259
+ }
3260
+ if (this.state === "cancel") return this.renderCancelled();
3261
+ let output = "";
3262
+ output += `${this.getSymbol()} ${this.colors.bold(this.colors.white(this.key))}`;
3263
+ if (this.schema.description) output += ` ${this.colors.subtle(this.schema.description)}`;
3264
+ output += "\n";
3265
+ const dimInputs = !this.error && this.mode.isToolbarOpen();
3266
+ if (!this.hasPresetOptions()) {
3267
+ const displayText = dimInputs ? this.colors.dim(this.getInputDisplay(false)) : this.colors.white(this.getInputDisplay(true));
3268
+ output += `${this.getBar()} ${displayText}`;
3269
+ output += "\n";
3270
+ output += `${this.getBarEnd()} ${this.renderFooter(this.getEntryHint())}`;
3271
+ return output;
3272
+ }
3273
+ this.buildSelectionOptions().forEach((option, index) => {
3274
+ const isSelected = index === this.mode.getCursor();
3275
+ const circle = dimInputs ? this.colors.dim(isSelected ? S_RADIO_ACTIVE : S_RADIO_INACTIVE) : isSelected ? this.theme.primary(S_RADIO_ACTIVE) : this.colors.dim(S_RADIO_INACTIVE);
3276
+ if (option.type === "other") {
3277
+ if (this.mode.isInInteraction("typing")) {
3278
+ const displayText = dimInputs ? this.colors.dim(this.getInputDisplay(false)) : this.colors.white(this.getInputDisplay(true));
3279
+ output += `${this.getBar()} ${circle} ${displayText}\n`;
3280
+ } else if (isSelected) if (dimInputs) output += `${this.getBar()} ${circle} ${this.colors.dim(option.label)}\n`;
3281
+ else output += `${this.getBar()} ${circle} ${this.colors.white(this.getInputDisplay(true))}\n`;
3282
+ else {
3283
+ const text$1 = dimInputs ? this.colors.dim(option.label) : this.colors.subtle(option.label);
3284
+ output += `${this.getBar()} ${circle} ${text$1}\n`;
3285
+ }
3286
+ return;
3287
+ }
3288
+ const formatText = (value) => {
3289
+ if (dimInputs) return this.colors.dim(value);
3290
+ if (isSelected) return this.colors.white(value);
3291
+ return this.colors.subtle(value);
3292
+ };
3293
+ let text = formatText(option.display);
3294
+ if (option.invalid) text = `\u001b[9m${text}\u001b[29m`;
3295
+ const annotation = option.annotation ? ` (${option.annotation})` : "";
3296
+ let suffix = "";
3297
+ if (annotation && isSelected) suffix = dimInputs ? this.colors.dim(annotation) : this.colors.subtle(annotation);
3298
+ output += `${this.getBar()} ${circle} ${text}${suffix}\n`;
3299
+ });
3300
+ output += `${this.getBarEnd()} ${this.renderFooter(this.getEntryHint())}`;
3301
+ return output;
3302
+ },
3303
+ validate: (_value) => {
3304
+ if (this.consumeSkipValidation()) return;
3305
+ if (this.getOutcome() !== "commit") return;
3306
+ if (!this.hasPresetOptions()) {
3307
+ const input = this.userInput ?? "";
3308
+ if (!input.trim()) {
3309
+ if (this.required) return "Please enter a value";
3310
+ return;
3311
+ }
3312
+ const inputValidation = this.validateInput(input);
3313
+ if (inputValidation) return inputValidation;
3314
+ const validation = this.runSchemaValidation(input);
3315
+ if (!validation.success) return validation.error;
3316
+ return;
3317
+ }
3318
+ const selectedOption = this.getSelectedOption();
3319
+ if (!this.mode.isInInteraction("typing") && selectedOption && selectedOption.type === "value" && selectedOption.key === "current" && selectedOption.invalid) return this.currentResult?.error ?? "Current value is invalid";
3320
+ const textInputIndex = this.getTextInputIndex();
3321
+ if (this.mode.getCursor() === textInputIndex && !this.mode.isInInteraction("typing")) {
3322
+ this.mode.enterTyping();
3323
+ this.mode.clearInput();
3324
+ this._setUserInput("");
3325
+ this.otherInputCache = "";
3326
+ this.updateValue();
3327
+ return "Value cannot be empty";
3328
+ }
3329
+ if (this.mode.getCursor() === textInputIndex && this.mode.isInInteraction("typing") && !(this.userInput && this.userInput.trim())) {
3330
+ if (this.required) return "Please enter a value";
3331
+ return;
3332
+ }
3333
+ if (this.mode.isInInteraction("typing") && this.userInput) {
3334
+ const inputValidation = this.validateInput(this.userInput);
3335
+ if (inputValidation) return inputValidation;
3336
+ const validation = this.runSchemaValidation(this.userInput);
3337
+ if (!validation.success) return validation.error;
3338
+ }
3339
+ if (!this.mode.isInInteraction("typing")) {
3340
+ const candidate = selectedOption && selectedOption.type === "value" ? selectedOption.value : this.value;
3341
+ const validation = this.runSchemaValidation(candidate !== void 0 ? candidate : void 0);
3342
+ if (!validation.success) return validation.error;
3343
+ }
3344
+ }
3345
+ });
3346
+ if (!this.hasPresetOptions()) {
3347
+ this.mode.enterTyping();
3348
+ this.mode.clearInput();
3349
+ this._setUserInput("");
3350
+ this.otherInputCache = "";
3351
+ this.setCommittedValue(this.getDefaultValue());
3352
+ } else {
3353
+ const options = this.buildValueOptions();
3354
+ const currentValue = this.currentResult?.isValid !== false ? this.current : void 0;
3355
+ const defaultValue = this.default;
3356
+ const baseCursor = resolveInitialCursor(options, {
3357
+ currentValue,
3358
+ defaultValue
3359
+ });
3360
+ const initialCursor = options[baseCursor]?.invalid ? options.length : baseCursor;
3361
+ this.mode.setCursor(initialCursor);
3362
+ this.updateValue();
3363
+ queueMicrotask(() => {
3364
+ const refreshedOptions = this.buildValueOptions();
3365
+ const refreshedBase = resolveInitialCursor(refreshedOptions, {
3366
+ currentValue,
3367
+ defaultValue
3368
+ });
3369
+ const refreshedCursor = refreshedOptions[refreshedBase]?.invalid ? refreshedOptions.length : refreshedBase;
3370
+ this.mode.setCursor(refreshedCursor);
3371
+ this.updateValue();
3372
+ });
3373
+ }
3374
+ this.on("cursor", (action) => {
3375
+ this.clearErrorState();
3376
+ if (!this.hasPresetOptions()) return;
3377
+ if (!this.error && this.mode.isToolbarOpen()) return;
3378
+ switch (action) {
3379
+ case "up": {
3380
+ const maxIndex = this.buildSelectionOptions().length - 1;
3381
+ if (this.mode.isInInteraction("typing") || this.mode.getCursor() === maxIndex) {
3382
+ this.mode.exitTyping();
3383
+ this._clearUserInput();
3384
+ this.mode.clearInput();
3385
+ this.otherInputCache = "";
3386
+ }
3387
+ this.mode.moveCursor("up", maxIndex);
3388
+ break;
3389
+ }
3390
+ case "down": {
3391
+ const maxIndex = this.buildSelectionOptions().length - 1;
3392
+ if (this.mode.isInInteraction("typing") || this.mode.getCursor() === maxIndex) {
3393
+ this.mode.exitTyping();
3394
+ this._clearUserInput();
3395
+ this.mode.clearInput();
3396
+ this.otherInputCache = "";
3397
+ }
3398
+ this.mode.moveCursor("down", maxIndex);
3399
+ break;
3400
+ }
3401
+ }
3402
+ this.updateValue();
3403
+ });
3404
+ this.on("userInput", (rawInput) => {
3405
+ this.clearErrorState();
3406
+ let input = rawInput.includes(" ") ? rawInput.replace(/\t/g, "") : rawInput;
3407
+ if (this.isRestoringInput) {
3408
+ this.isRestoringInput = false;
3409
+ this.otherInputCache = input;
3410
+ return;
3411
+ }
3412
+ if (this.mode.isInInteraction("typing")) {
3413
+ let nextInput = input;
3414
+ if (this.shouldStitchInput && this.otherInputCache) if (!input || input === this.otherInputCache) nextInput = this.otherInputCache;
3415
+ else if (input.startsWith(this.otherInputCache)) {
3416
+ nextInput = input;
3417
+ this.shouldStitchInput = false;
3418
+ } else {
3419
+ nextInput = `${this.otherInputCache}${input}`;
3420
+ this.shouldStitchInput = false;
3421
+ }
3422
+ else this.shouldStitchInput = false;
3423
+ this.mode.updateInput(nextInput);
3424
+ this.userInput = nextInput;
3425
+ this.otherInputCache = nextInput;
3426
+ try {
3427
+ const parsed = this.parseInput(nextInput);
3428
+ this.setCommittedValue(parsed ?? this.getDefaultValue());
3429
+ } catch {}
3430
+ } else this.shouldStitchInput = false;
3431
+ });
3432
+ this.on("key", (char, info) => {
3433
+ if (!info) return;
3434
+ this.clearErrorState();
3435
+ if (this.handleToolbarKey(char, info)) return;
3436
+ if (!this.error && this.mode.isToolbarOpen()) return;
3437
+ if (!this.hasPresetOptions()) {
3438
+ if (this.mode.isInInteraction("typing")) try {
3439
+ const parsed = this.parseInput(this.userInput);
3440
+ this.setCommittedValue(parsed ?? this.getDefaultValue());
3441
+ } catch {}
3442
+ return;
3443
+ }
3444
+ if (char && char.length === 1 && !info.ctrl && !info.meta && !this.mode.isInInteraction("typing")) {
3445
+ const isArrowKey = [
3446
+ "up",
3447
+ "down",
3448
+ "left",
3449
+ "right"
3450
+ ].includes(info.name || "");
3451
+ const isControlKey = [
3452
+ "return",
3453
+ "enter",
3454
+ "escape",
3455
+ "tab"
3456
+ ].includes(info.name || "");
3457
+ if (!isArrowKey && !isControlKey) {
3458
+ const textInputIndex$1 = this.getTextInputIndex();
3459
+ this.mode.setCursor(textInputIndex$1);
3460
+ const existingInput = this.mode.getInputValue() || this.userInput || this.otherInputCache || "";
3461
+ this.mode.enterTyping(existingInput);
3462
+ const nextInput = `${existingInput}${char}`;
3463
+ this.otherInputCache = nextInput;
3464
+ this._setUserInput(nextInput);
3465
+ this.mode.updateInput(nextInput);
3466
+ this.syncCursorToInputEnd();
3467
+ this.updateValue();
3468
+ return;
3469
+ }
3470
+ }
3471
+ const textInputIndex = this.getTextInputIndex();
3472
+ if (this.mode.getCursor() === textInputIndex) {
3473
+ if (info.name === "escape") {
3474
+ this.mode.exitTyping();
3475
+ this._clearUserInput();
3476
+ this.mode.clearInput();
3477
+ this.otherInputCache = "";
3478
+ this.updateValue();
3479
+ return;
3480
+ }
3481
+ }
3482
+ });
3483
+ }
3484
+ get cursor() {
3485
+ return this.mode.getCursor();
3486
+ }
3487
+ get isTyping() {
3488
+ return this.mode.isInInteraction("typing");
3489
+ }
3490
+ updateValue() {
3491
+ if (!this.hasPresetOptions()) {
3492
+ try {
3493
+ const parsed = this.parseInput(this.mode.getInputValue());
3494
+ this.setCommittedValue(parsed ?? this.getDefaultValue());
3495
+ } catch {
3496
+ this.setCommittedValue(this.getDefaultValue());
3497
+ }
3498
+ return;
3499
+ }
3500
+ if (!this.mode.isInInteraction("typing")) {
3501
+ const selected = this.buildSelectionOptions()[this.mode.getCursor()];
3502
+ if (!selected) {
3503
+ this.setCommittedValue(this.getDefaultValue());
3504
+ return;
3505
+ }
3506
+ if (selected.type === "value") {
3507
+ if (selected.invalid) {
3508
+ this.setCommittedValue(this.getDefaultValue());
3509
+ return;
3510
+ }
3511
+ this.setCommittedValue(selected.value ?? this.getDefaultValue());
3512
+ return;
3513
+ }
3514
+ this.setCommittedValue(this.getDefaultValue());
3515
+ return;
3516
+ }
3517
+ try {
3518
+ const parsed = this.parseInput(this.mode.getInputValue());
3519
+ this.setCommittedValue(parsed ?? this.getDefaultValue());
3520
+ } catch {
3521
+ this.setCommittedValue(this.getDefaultValue());
3522
+ }
3523
+ }
3524
+ formatValue(value) {
3525
+ const hasExplicitEmpty = value === "";
3526
+ const str = value ?? "";
3527
+ let display = this.secret && str && !this.isSecretRevealed() ? this.maskValue(str) : str;
3528
+ if (!display && hasExplicitEmpty) display = "\"\"";
3529
+ return this.truncateValue(display);
3530
+ }
3531
+ parseInput(input) {
3532
+ return input || void 0;
3533
+ }
3534
+ validateInput(_input) {}
3535
+ getDefaultValue() {
3536
+ return "";
3537
+ }
3538
+ hasPresetOptions() {
3539
+ return this.currentResult?.rawValue !== void 0 || this.default !== void 0;
3540
+ }
3541
+ buildValueOptions() {
3542
+ const hasValidCurrent = this.currentResult?.isValid !== false && this.current !== void 0;
3543
+ const baseOptions = [];
3544
+ if (hasValidCurrent && this.current !== void 0) {
3545
+ const isSameAsDefault = this.current === this.default;
3546
+ baseOptions.push({
3547
+ key: "current",
3548
+ value: this.current,
3549
+ display: this.formatValue(this.current),
3550
+ annotation: this.buildAnnotation({
3551
+ isCurrent: true,
3552
+ isDefault: isSameAsDefault
3553
+ }) ?? void 0
3554
+ });
3555
+ }
3556
+ if (this.default !== void 0 && (!hasValidCurrent || this.current !== this.default) && this.default !== void 0) {
3557
+ const isSameAsCurrent = hasValidCurrent && this.current === this.default;
3558
+ baseOptions.push({
3559
+ key: "default",
3560
+ value: this.default,
3561
+ display: this.formatValue(this.default),
3562
+ annotation: this.buildAnnotation({
3563
+ isDefault: true,
3564
+ isCurrent: isSameAsCurrent
3565
+ }) ?? void 0
3566
+ });
3567
+ }
3568
+ return buildSelectableOptions({
3569
+ currentResult: this.currentResult,
3570
+ formatInvalidDisplay: (raw) => this.formatRawValue(raw ?? ""),
3571
+ buildAnnotation: (flags) => this.buildAnnotation(flags) ?? void 0,
3572
+ baseOptions,
3573
+ invalidOptionKey: "current"
3574
+ });
3575
+ }
3576
+ buildSelectionOptions() {
3577
+ const options = this.buildValueOptions().map((option) => ({
3578
+ type: "value",
3579
+ key: option.key,
3580
+ value: option.value,
3581
+ display: option.display,
3582
+ annotation: option.annotation,
3583
+ invalid: option.invalid
3584
+ }));
3585
+ options.push({
3586
+ type: "other",
3587
+ label: "Other"
3588
+ });
3589
+ return options;
3590
+ }
3591
+ getSelectedOption() {
3592
+ if (!this.hasPresetOptions()) return;
3593
+ return this.buildSelectionOptions()[this.mode.getCursor()];
3594
+ }
3595
+ formatRawValue(raw) {
3596
+ if (!raw) return "";
3597
+ const display = this.secret && !this.isSecretRevealed() ? this.maskValue(raw) : raw;
3598
+ return this.truncateValue(display);
3599
+ }
3600
+ maskValue(value) {
3601
+ return maskSecretValue(value, SECRET_MASK);
3602
+ }
3603
+ getTextInputIndex() {
3604
+ if (!this.hasPresetOptions()) return 0;
3605
+ const options = this.buildSelectionOptions();
3606
+ const index = options.findIndex((option) => option.type === "other");
3607
+ return index === -1 ? options.length - 1 : index;
3608
+ }
3609
+ getInputDisplay(includeCursor) {
3610
+ const inputValue = this.mode.getInputValue();
3611
+ const isMasked = this.secret && inputValue && !this.isSecretRevealed();
3612
+ const base = isMasked ? this.maskValue(inputValue) : inputValue;
3613
+ if (!includeCursor) return base;
3614
+ const rawCursor = this.mode.isInInteraction("typing") ? Math.max(0, this._cursor ?? inputValue.length) : 0;
3615
+ const maskLength = isMasked ? Math.max(1, SECRET_MASK.length) : 1;
3616
+ const cursorIndex = Math.min(rawCursor * maskLength, base.length);
3617
+ if (cursorIndex >= base.length) return `${base}${S_CURSOR}`;
3618
+ const segmentLength = maskLength;
3619
+ const before = base.slice(0, cursorIndex);
3620
+ const cursorSegment = base.slice(cursorIndex, cursorIndex + segmentLength) || " ";
3621
+ const after = base.slice(cursorIndex + segmentLength);
3622
+ return `${before}${this.colors.inverse(cursorSegment)}${after}`;
3623
+ }
3624
+ getEntryHint() {
3625
+ return this.secret ? "Enter a secret value" : "Enter a value";
3626
+ }
3627
+ syncCursorToInputEnd() {
3628
+ const cursorHost = this;
3629
+ cursorHost._cursor = this.mode.getInputValue().length;
3630
+ }
3631
+ toggleSecretReveal() {
3632
+ const cachedInput = this.mode.getInputValue() || this.userInput || this.otherInputCache;
3633
+ super.toggleSecretReveal();
3634
+ if (!cachedInput) return;
3635
+ this.shouldStitchInput = Boolean(this.otherInputCache || cachedInput);
3636
+ const stitchedBaseline = cachedInput;
3637
+ queueMicrotask(() => {
3638
+ const restored = this.otherInputCache || stitchedBaseline;
3639
+ if (!restored) return;
3640
+ if (!this.mode.isInInteraction("typing")) this.mode.enterTyping(restored);
3641
+ this.isRestoringInput = true;
3642
+ this.internals.track = true;
3643
+ this.mode.updateInput(restored);
3644
+ this.otherInputCache = restored;
3645
+ this._setUserInput(restored, true);
3646
+ this.syncCursorToInputEnd();
3647
+ });
3648
+ }
3649
+ };
3650
+
3651
+ //#endregion
3652
+ //#region ../prompt/src/prompts/create/createPrompt.ts
3653
+ function createPrompt({ key, schema, currentValue, theme, truncate, shouldMask, index, total, input, output, preprocessors: preprocessors$1 }) {
3654
+ const baseOptions = {
3655
+ key,
3656
+ theme,
3657
+ truncate,
3658
+ index,
3659
+ total,
3660
+ input,
3661
+ output
3662
+ };
3663
+ switch (schema.type) {
3664
+ case "boolean":
3665
+ const booleanOverride = preprocessors$1?.boolean;
3666
+ let booleanPreprocess;
3667
+ if (booleanOverride === void 0) booleanPreprocess = void 0;
3668
+ else if (booleanOverride === true) booleanPreprocess = booleanPreprocessor();
3669
+ else if (booleanOverride === false) booleanPreprocess = false;
3670
+ else if (typeof booleanOverride === "function") booleanPreprocess = booleanOverride;
3671
+ else booleanPreprocess = booleanPreprocessor(booleanOverride);
3672
+ return new EnvBooleanPrompt(schema, {
3673
+ ...baseOptions,
3674
+ current: currentValue,
3675
+ preprocess: booleanPreprocess
3676
+ });
3677
+ case "number": return new EnvNumberPrompt(schema, {
3678
+ ...baseOptions,
3679
+ current: currentValue,
3680
+ preprocess: preprocessors$1?.number
3681
+ });
3682
+ case "enum": return new EnvEnumPrompt(schema, {
3683
+ ...baseOptions,
3684
+ current: currentValue,
3685
+ preprocess: preprocessors$1?.enum
3686
+ });
3687
+ default: return new EnvStringPrompt(schema, {
3688
+ ...baseOptions,
3689
+ current: currentValue,
3690
+ secret: shouldMask,
3691
+ preprocess: preprocessors$1?.string
3692
+ });
3693
+ }
3694
+ }
3695
+
3696
+ //#endregion
3697
+ //#region ../prompt/src/utils/clearConsoleLines.ts
3698
+ function clearConsoleLines(lineCount) {
3699
+ const output = process.stdout;
3700
+ if (!output?.isTTY) return;
3701
+ try {
3702
+ for (let i = 0; i < lineCount; i++) {
3703
+ (0, node_readline.moveCursor)(output, 0, -1);
3704
+ (0, node_readline.cursorTo)(output, 0);
3705
+ (0, node_readline.clearLine)(output, 0);
3706
+ }
3707
+ (0, node_readline.cursorTo)(output, 0);
3708
+ } catch {}
3709
+ }
3710
+
3711
+ //#endregion
3712
+ //#region ../prompt/src/utils/getDisplayEnvPath.ts
3713
+ function getDisplayEnvPath(envPath, cwd = process.cwd()) {
3714
+ const relativeEnvPath = (0, node_path.relative)(cwd, envPath);
3715
+ if (relativeEnvPath === "") return ".";
3716
+ if (relativeEnvPath.startsWith(".")) return relativeEnvPath;
3717
+ return `./${relativeEnvPath}`;
3718
+ }
3719
+
3720
+ //#endregion
3721
+ //#region ../prompt/src/session/Session.ts
3722
+ var Session = class Session {
3723
+ schemas;
3724
+ newValues = {};
3725
+ promptLineHistory = [];
3726
+ channel;
3727
+ secrets;
3728
+ truncate;
3729
+ theme;
3730
+ output;
3731
+ input;
3732
+ displayEnvPath;
3733
+ envPath;
3734
+ preprocessors;
3735
+ constructor({ channel, secrets, truncate, theme, output, input, schemas, path, preprocess }) {
3736
+ this.channel = channel;
3737
+ this.secrets = secrets;
3738
+ this.truncate = truncate;
3739
+ this.theme = theme;
3740
+ this.output = output;
3741
+ this.input = input;
3742
+ this.displayEnvPath = getDisplayEnvPath(path);
3743
+ const normalizedEnvPath = path.startsWith("file://") ? (0, node_url.fileURLToPath)(path) : path;
3744
+ this.envPath = (0, node_path.resolve)(process.cwd(), normalizedEnvPath);
3745
+ this.schemas = schemas;
3746
+ this.preprocessors = preprocess;
3747
+ }
3748
+ static fromOptions(options) {
3749
+ return new Session(options);
3750
+ }
3751
+ async run() {
3752
+ this.renderSetupHeader();
3753
+ let currentValues = await this.channel.get();
3754
+ const schemaKeys = Object.keys(this.schemas);
3755
+ let index = 0;
3756
+ while (index < schemaKeys.length) {
3757
+ const key = schemaKeys[index];
3758
+ const envVarSchema = this.schemas[key];
3759
+ let addedLines = 0;
3760
+ if (index > 0) {
3761
+ this.output.write(`${picocolors.default.gray("│")} \n`);
3762
+ addedLines++;
3763
+ }
3764
+ const shouldMask = resolveShouldMask(key, envVarSchema, this.secrets);
3765
+ const storedValue = this.newValues[key] ?? currentValues[key];
3766
+ const prompt$1 = createPrompt({
3767
+ key,
3768
+ schema: envVarSchema,
3769
+ currentValue: storedValue && storedValue.trim() !== "" ? storedValue : void 0,
3770
+ theme: this.theme,
3771
+ truncate: this.truncate,
3772
+ shouldMask,
3773
+ index,
3774
+ total: schemaKeys.length,
3775
+ input: this.input,
3776
+ output: this.output,
3777
+ preprocessors: this.preprocessors
3778
+ });
3779
+ const value = await prompt$1.prompt();
3780
+ addedLines++;
3781
+ const outcome = prompt$1.getOutcome();
3782
+ if ((0, __clack_core.isCancel)(value) || typeof value === "symbol" && value?.description === "clack:cancel") {
3783
+ this.output.write(`${picocolors.default.red("│")} \n`);
3784
+ this.output.write(`${picocolors.default.red("└")} ${picocolors.default.red("Setup cancelled.")}\n\n`);
3785
+ return "cancelled";
3786
+ }
3787
+ if (outcome === "previous") {
3788
+ clearConsoleLines(addedLines);
3789
+ const previousLines = this.promptLineHistory.pop() ?? 0;
3790
+ if (previousLines > 0) clearConsoleLines(previousLines);
3791
+ index = Math.max(index - 1, 0);
3792
+ continue;
3793
+ }
3794
+ this.promptLineHistory.push(addedLines);
3795
+ if (outcome === "skip") {
3796
+ index++;
3797
+ continue;
3798
+ }
3799
+ const stringValue = String(value);
3800
+ try {
3801
+ await this.channel.set({ [key]: stringValue });
3802
+ currentValues = await this.channel.get();
3803
+ this.newValues[key] = stringValue;
3804
+ } catch (error) {
3805
+ this.output.write(`${picocolors.default.gray(S_BAR_END)} ${picocolors.default.red(`Failed to save ${key}: ${error}`)}\n\n`);
3806
+ return "error";
3807
+ }
3808
+ index++;
3809
+ }
3810
+ this.output.write(`${picocolors.default.gray(S_BAR)}\n${picocolors.default.gray(S_BAR_END)} ${this.theme.primary("Setup complete!")}\n\n`);
3811
+ return "success";
3812
+ }
3813
+ renderSetupHeader() {
3814
+ const envFileUrl = (0, node_url.pathToFileURL)(this.envPath).toString();
3815
+ const clickableEnvPath = this.toHyperlink(picocolors.default.gray(this.displayEnvPath), envFileUrl);
3816
+ const variableCount = Object.keys(this.schemas).length;
3817
+ const variableLabel = variableCount === 1 ? "1 variable" : `${variableCount} variables`;
3818
+ const headerBody = [
3819
+ this.theme.bgPrimary(picocolors.default.black(" Environment Variable Setup ")),
3820
+ `${picocolors.default.gray("│")} ${clickableEnvPath}${picocolors.default.gray(` · ${variableLabel}`)}`,
3821
+ `${picocolors.default.gray("│")} `
3822
+ ].join("\n");
3823
+ this.output.write(`\n${picocolors.default.gray(S_BAR_START)} ${headerBody}\n`);
3824
+ }
3825
+ toHyperlink(text, url) {
3826
+ const escapeCode = "\x1B";
3827
+ const oscSequence = `${escapeCode}]8;;`;
3828
+ const stringTerminator = `${escapeCode}\\`;
3829
+ return `${oscSequence}${url}${stringTerminator}${text}${oscSequence}${stringTerminator}`;
3830
+ }
3831
+ };
3832
+
3833
+ //#endregion
3834
+ //#region ../prompt/src/options/resolve.ts
3835
+ function resolveTheme(themeOption) {
3836
+ return new Theme(themeOption ?? picocolors.default.magenta);
3837
+ }
3838
+ function resolveRootDirectory(rootOption) {
3839
+ if (!rootOption) return;
3840
+ if (rootOption.startsWith("file://")) return (0, node_path.dirname)((0, node_url.fileURLToPath)(rootOption));
3841
+ return rootOption;
3842
+ }
3843
+ function resolveEnvFilePath(pathOption, rootDir) {
3844
+ if (!rootDir) return pathOption;
3845
+ return (0, node_path.resolve)(rootDir, pathOption);
3846
+ }
3847
+
3848
+ //#endregion
3849
+ //#region ../prompt/src/utils/isEnvChannel.ts
3850
+ /**
3851
+ * Type guard to check if a value is an EnvChannel instance
3852
+ */
3853
+ function isEnvChannel(value) {
3854
+ return typeof value === "object" && value !== null && "get" in value && "set" in value && typeof value.get === "function" && typeof value.set === "function";
3855
+ }
3856
+
3857
+ //#endregion
3858
+ //#region ../prompt/src/prompt.ts
3859
+ /**
3860
+ * Interactive CLI tool to generate .env files with schema validation
3861
+ */
3862
+ async function prompt(modelOrOptions, interactiveOptions) {
3863
+ let schemas;
3864
+ let preprocessConfig;
3865
+ let finalOptions;
3866
+ if (modelOrOptions instanceof EnvModel) {
3867
+ const model = modelOrOptions;
3868
+ finalOptions = interactiveOptions || {};
3869
+ schemas = model.schemas;
3870
+ preprocessConfig = model.preprocess;
3871
+ } else {
3872
+ const options = modelOrOptions;
3873
+ finalOptions = options;
3874
+ if (options.schemas) {
3875
+ schemas = resolveSchemas(options.schemas);
3876
+ preprocessConfig = options.preprocess;
3877
+ } else throw new Error("Either provide a model or schemas in options");
3878
+ }
3879
+ const rootDirectory = resolveRootDirectory(finalOptions.root);
3880
+ const path = resolveEnvFilePath(finalOptions.path ?? ENV_PATH, rootDirectory);
3881
+ const truncate = finalOptions.truncate ?? TRUNCATE_LENGTH;
3882
+ const secrets = finalOptions.secrets ?? SECRET_PATTERNS;
3883
+ const input = node_process.stdin;
3884
+ const output = node_process.stdout;
3885
+ const channel = isEnvChannel(finalOptions.channel) ? finalOptions.channel : resolveChannel(finalOptions.channel, path);
3886
+ const theme = resolveTheme(finalOptions.theme);
3887
+ await new Session({
3888
+ schemas,
3889
+ channel,
3890
+ secrets,
3891
+ truncate,
3892
+ theme,
3893
+ input,
3894
+ output,
3895
+ path,
3896
+ preprocess: preprocessConfig
3897
+ }).run();
3898
+ }
3899
+
3900
+ //#endregion
3901
+ Object.defineProperty(exports, 'BooleanEnvVarSchema', {
3902
+ enumerable: true,
3903
+ get: function () {
3904
+ return BooleanEnvVarSchema;
3905
+ }
3906
+ });
3907
+ Object.defineProperty(exports, 'DefaultEnvChannel', {
3908
+ enumerable: true,
3909
+ get: function () {
3910
+ return DefaultEnvChannel;
3911
+ }
3912
+ });
3913
+ Object.defineProperty(exports, 'DotEnvChannel', {
3914
+ enumerable: true,
3915
+ get: function () {
3916
+ return DotEnvChannel;
3917
+ }
3918
+ });
3919
+ Object.defineProperty(exports, 'DotEnvXChannel', {
3920
+ enumerable: true,
3921
+ get: function () {
3922
+ return DotEnvXChannel;
3923
+ }
3924
+ });
3925
+ Object.defineProperty(exports, 'EnumEnvVarSchema', {
3926
+ enumerable: true,
3927
+ get: function () {
3928
+ return EnumEnvVarSchema;
3929
+ }
3930
+ });
3931
+ Object.defineProperty(exports, 'EnvModel', {
3932
+ enumerable: true,
3933
+ get: function () {
3934
+ return EnvModel;
3935
+ }
3936
+ });
3937
+ Object.defineProperty(exports, 'EnvSource', {
3938
+ enumerable: true,
3939
+ get: function () {
3940
+ return EnvSource;
3941
+ }
3942
+ });
3943
+ Object.defineProperty(exports, 'EnvVarSchemaBase', {
3944
+ enumerable: true,
3945
+ get: function () {
3946
+ return EnvVarSchemaBase;
3947
+ }
3948
+ });
3949
+ Object.defineProperty(exports, 'NumberEnvVarSchema', {
3950
+ enumerable: true,
3951
+ get: function () {
3952
+ return NumberEnvVarSchema;
3953
+ }
3954
+ });
3955
+ Object.defineProperty(exports, 'ProcessEnvChannel', {
3956
+ enumerable: true,
3957
+ get: function () {
3958
+ return ProcessEnvChannel;
3959
+ }
3960
+ });
3961
+ Object.defineProperty(exports, 'StringEnvVarSchema', {
3962
+ enumerable: true,
3963
+ get: function () {
3964
+ return StringEnvVarSchema;
3965
+ }
3966
+ });
3967
+ Object.defineProperty(exports, '__export', {
3968
+ enumerable: true,
3969
+ get: function () {
3970
+ return __export;
3971
+ }
3972
+ });
3973
+ Object.defineProperty(exports, '__toESM', {
3974
+ enumerable: true,
3975
+ get: function () {
3976
+ return __toESM;
3977
+ }
3978
+ });
3979
+ Object.defineProperty(exports, 'booleanPreprocessor', {
3980
+ enumerable: true,
3981
+ get: function () {
3982
+ return booleanPreprocessor;
3983
+ }
3984
+ });
3985
+ Object.defineProperty(exports, 'booleanProcessor', {
3986
+ enumerable: true,
3987
+ get: function () {
3988
+ return booleanProcessor;
3989
+ }
3990
+ });
3991
+ Object.defineProperty(exports, 'defaults_exports', {
3992
+ enumerable: true,
3993
+ get: function () {
3994
+ return defaults_exports;
3995
+ }
3996
+ });
3997
+ Object.defineProperty(exports, 'define', {
3998
+ enumerable: true,
3999
+ get: function () {
4000
+ return define;
4001
+ }
4002
+ });
4003
+ Object.defineProperty(exports, 'enumPreprocessor', {
4004
+ enumerable: true,
4005
+ get: function () {
4006
+ return enumPreprocessor;
4007
+ }
4008
+ });
4009
+ Object.defineProperty(exports, 'enumProcessor', {
4010
+ enumerable: true,
4011
+ get: function () {
4012
+ return enumProcessor;
4013
+ }
4014
+ });
4015
+ Object.defineProperty(exports, 'get', {
4016
+ enumerable: true,
4017
+ get: function () {
4018
+ return get;
4019
+ }
4020
+ });
4021
+ Object.defineProperty(exports, 'isEnvVarSchema', {
4022
+ enumerable: true,
4023
+ get: function () {
4024
+ return isEnvVarSchema;
4025
+ }
4026
+ });
4027
+ Object.defineProperty(exports, 'numberPreprocessor', {
4028
+ enumerable: true,
4029
+ get: function () {
4030
+ return numberPreprocessor;
4031
+ }
4032
+ });
4033
+ Object.defineProperty(exports, 'numberProcessor', {
4034
+ enumerable: true,
4035
+ get: function () {
4036
+ return numberProcessor;
4037
+ }
4038
+ });
4039
+ Object.defineProperty(exports, 'preprocessors', {
4040
+ enumerable: true,
4041
+ get: function () {
4042
+ return preprocessors;
4043
+ }
4044
+ });
4045
+ Object.defineProperty(exports, 'processors', {
4046
+ enumerable: true,
4047
+ get: function () {
4048
+ return processors;
4049
+ }
4050
+ });
4051
+ Object.defineProperty(exports, 'prompt', {
4052
+ enumerable: true,
4053
+ get: function () {
4054
+ return prompt;
4055
+ }
4056
+ });
4057
+ Object.defineProperty(exports, 'resolveChannel', {
4058
+ enumerable: true,
4059
+ get: function () {
4060
+ return resolveChannel;
4061
+ }
4062
+ });
4063
+ Object.defineProperty(exports, 'resolvePreprocessor', {
4064
+ enumerable: true,
4065
+ get: function () {
4066
+ return resolvePreprocessor;
4067
+ }
4068
+ });
4069
+ Object.defineProperty(exports, 'resolveSchema', {
4070
+ enumerable: true,
4071
+ get: function () {
4072
+ return resolveSchema;
4073
+ }
4074
+ });
4075
+ Object.defineProperty(exports, 'resolveSchemas', {
4076
+ enumerable: true,
4077
+ get: function () {
4078
+ return resolveSchemas;
4079
+ }
4080
+ });
4081
+ Object.defineProperty(exports, 'set', {
4082
+ enumerable: true,
4083
+ get: function () {
4084
+ return set;
4085
+ }
4086
+ });
4087
+ Object.defineProperty(exports, 'stringPreprocessor', {
4088
+ enumerable: true,
4089
+ get: function () {
4090
+ return stringPreprocessor;
4091
+ }
4092
+ });
4093
+ Object.defineProperty(exports, 'stringProcessor', {
4094
+ enumerable: true,
4095
+ get: function () {
4096
+ return stringProcessor;
4097
+ }
4098
+ });