sandcovery 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1710 @@
1
+ #!/usr/bin/env node
2
+ import { B as try_, F as seconds, H as getOrUndefined, I as toMillis, J as isString, K as hasProperty, N as TaggedError, P as millis, R as isFailure, _ as decodeUnknownOption, b as fromJsonString, h as Struct, k as optional, m as String$1, n as Boolean, o as Json, p as Record, y as decodeUnknownSync, z as isSuccess } from "../Schema-DiSfJzMf.mjs";
3
+ import { n as SANDCOVERY_ORIGIN } from "../origin-CIA-1Jia.mjs";
4
+ import { A as CliFailure, C as remoteLine, E as isDigit, M as statusOf$1, N as usageFailure, O as isUpper, P as Canceled, S as remoteCell, T as consistsOf, _ as glyph, a as closest, b as theme, c as isOptionValue, d as parseLeaf, f as readOptionToken, g as ellipsis, h as clearLine, i as version, j as exitCodeOf, k as isWordCharacter, l as lastValue, o as flagOf, p as rerunArgv, r as CLI, s as isOptionToken, t as BIN, u as parseFailure, v as plainPrefix, w as remoteText, x as escapeUnprintable, y as spinnerFrame } from "../spec-DfgmzDj-.mjs";
5
+ import { n as sendTelemetry$1, t as loopbackOrigin } from "../telemetry-BYnuVdoZ.mjs";
6
+ import "../posthog-project-CdWw_ofg.mjs";
7
+ import http from "node:http";
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import { buffer } from "node:stream/consumers";
11
+ import readline from "node:readline";
12
+ import crypto from "node:crypto";
13
+ import os from "node:os";
14
+ // ../cli-core/src/layout.ts
15
+ const combining = /\p{M}/u;
16
+ const pictographic = /\p{Extended_Pictographic}/u;
17
+ const WIDE_RANGES = [
18
+ [4352, 4447],
19
+ [11904, 12350],
20
+ [12353, 13311],
21
+ [13312, 19903],
22
+ [19968, 40959],
23
+ [40960, 42191],
24
+ [44032, 55203],
25
+ [63744, 64255],
26
+ [65072, 65103],
27
+ [65280, 65376],
28
+ [65504, 65510]
29
+ ];
30
+ const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" });
31
+ const graphemeWidth = (grapheme) => {
32
+ const point = grapheme.codePointAt(0) ?? 0;
33
+ const first = String.fromCodePoint(point);
34
+ if (grapheme === "" || combining.test(first)) return 0;
35
+ return WIDE_RANGES.some(([low, high]) => point >= low && point <= high) || pictographic.test(first) ? 2 : 1;
36
+ };
37
+ const displayWidth = (text) => {
38
+ let total = 0;
39
+ for (const { segment } of segmenter.segment(text)) total += graphemeWidth(segment);
40
+ return total;
41
+ };
42
+ const padEnd = (text, width) => `${text}${" ".repeat(Math.max(0, width - displayWidth(text)))}`;
43
+ const truncate = ({ ellipsis, text, width }) => {
44
+ if (displayWidth(text) <= width) return text;
45
+ const room = Math.max(0, width - displayWidth(ellipsis));
46
+ let kept = "";
47
+ for (const { segment } of segmenter.segment(text)) {
48
+ if (displayWidth(`${kept}${segment}`) > room) break;
49
+ kept += segment;
50
+ }
51
+ return `${kept}${ellipsis}`;
52
+ };
53
+ const wrap = ({ text, width }) => {
54
+ const lines = [];
55
+ for (const paragraph of text.split("\n")) {
56
+ let line = "";
57
+ for (const word of paragraph.split(" ")) if (line === "") line = word;
58
+ else if (displayWidth(`${line} ${word}`) <= width) line = `${line} ${word}`;
59
+ else {
60
+ lines.push(line);
61
+ line = word;
62
+ }
63
+ lines.push(line);
64
+ }
65
+ return lines;
66
+ };
67
+ const indent = (lines, spaces) => lines.map((line) => line === "" ? "" : `${" ".repeat(spaces)}${line}`);
68
+ const twoColumn = ({ decorate = (text) => text, entries, indentBy, width }) => {
69
+ const column = indentBy + Math.max(0, ...entries.map((entry) => displayWidth(entry.syntax))) + 2;
70
+ const descriptionWidth = width - column;
71
+ const sideBySide = descriptionWidth >= 24;
72
+ return entries.flatMap(({ description, syntax }) => {
73
+ const lead = `${" ".repeat(indentBy)}${decorate(syntax)}`;
74
+ if (description === "") return [lead];
75
+ if (!sideBySide) return [lead, ...indent(wrap({
76
+ text: description,
77
+ width: Math.max(20, width - indentBy - 4)
78
+ }), indentBy + 4)];
79
+ const [first = "", ...rest] = wrap({
80
+ text: description,
81
+ width: descriptionWidth
82
+ });
83
+ return [`${lead}${" ".repeat(column - indentBy - displayWidth(syntax))}${first}`, ...indent(rest, column)];
84
+ });
85
+ };
86
+ // ../../node_modules/.pnpm/es-toolkit@1.53.1/node_modules/es-toolkit/dist/function/noop.mjs
87
+ /**
88
+ * A no-operation function that does nothing.
89
+ * This can be used as a placeholder or default function.
90
+ *
91
+ * @example
92
+ * noop(); // Does nothing
93
+ *
94
+ * @returns This function does not return anything.
95
+ */
96
+ function noop() {}
97
+ // ../../node_modules/.pnpm/es-toolkit@1.53.1/node_modules/es-toolkit/dist/math/sum.mjs
98
+ /**
99
+ * Calculates the sum of an array of numbers.
100
+ *
101
+ * This function takes an array of numbers and returns the sum of all the elements in the array.
102
+ *
103
+ * @param nums - An array of numbers to be summed.
104
+ * @returns The sum of all the numbers in the array.
105
+ *
106
+ * @example
107
+ * const numbers = [1, 2, 3, 4, 5];
108
+ * const result = sum(numbers);
109
+ * // result will be 15
110
+ */
111
+ function sum(nums) {
112
+ let result = 0;
113
+ for (let i = 0; i < nums.length; i++) result += nums[i];
114
+ return result;
115
+ }
116
+ // ../../node_modules/.pnpm/es-toolkit@1.53.1/node_modules/es-toolkit/dist/object/omitBy.mjs
117
+ /**
118
+ * Creates a new object composed of the properties that do not satisfy the predicate function.
119
+ *
120
+ * This function takes an object and a predicate function, and returns a new object that
121
+ * includes only the properties for which the predicate function returns false.
122
+ *
123
+ * @template T - The type of object.
124
+ * @param obj - The object to omit properties from.
125
+ * @param shouldOmit - A predicate function that determines
126
+ * whether a property should be omitted. It takes the property's key and value as arguments and returns `true`
127
+ * if the property should be omitted, and `false` otherwise. Numeric keys are passed as strings.
128
+ * @returns A new object with the properties that do not satisfy the predicate function.
129
+ *
130
+ * @example
131
+ * const obj = { a: 1, b: 'omit', c: 3 };
132
+ * const shouldOmit = (value) => typeof value === 'string';
133
+ * const result = omitBy(obj, shouldOmit);
134
+ * // result will be { a: 1, c: 3 }
135
+ */
136
+ function omitBy(obj, shouldOmit) {
137
+ const result = {};
138
+ const keys = Object.keys(obj);
139
+ for (let i = 0; i < keys.length; i++) {
140
+ const key = keys[i];
141
+ const objectKey = key;
142
+ const value = obj[objectKey];
143
+ if (!shouldOmit(value, key)) result[objectKey] = value;
144
+ }
145
+ return result;
146
+ }
147
+ // ../cli-core/src/output.ts
148
+ const decodeJsonRecord = decodeUnknownSync(fromJsonString(Record(String$1, Json)));
149
+ const jsonRecord = ({ value }) => decodeJsonRecord(JSON.stringify(value));
150
+ const SHELL_SAFE_PUNCTUATION = /* @__PURE__ */ new Set([
151
+ "%",
152
+ "+",
153
+ ",",
154
+ "-",
155
+ ".",
156
+ "/",
157
+ ":",
158
+ "=",
159
+ "@"
160
+ ]);
161
+ const DOUBLE_QUOTE_SPECIALS = [
162
+ "!",
163
+ "\"",
164
+ "$",
165
+ "\\",
166
+ "`"
167
+ ];
168
+ const isShellSafe = (word) => consistsOf(word, (character) => isWordCharacter(character) || SHELL_SAFE_PUNCTUATION.has(character));
169
+ const isPlaceholder = (word) => {
170
+ const bare = word.endsWith("...") ? word.slice(0, -3) : word;
171
+ const name = bare.slice(1, -1);
172
+ return bare.startsWith("<") && bare.endsWith(">") && isUpper(name.charAt(0)) && consistsOf(name, (character) => isUpper(character) || isDigit(character) || character === "_");
173
+ };
174
+ const shellWord = (word) => {
175
+ if (isShellSafe(word) || isPlaceholder(word)) return word;
176
+ if (DOUBLE_QUOTE_SPECIALS.some((special) => word.includes(special))) return `'${word.replaceAll("'", () => `'"'"'`)}'`;
177
+ return `"${word}"`;
178
+ };
179
+ const shellCommand = (argv) => argv.map(shellWord).join(" ");
180
+ const definedOnly = (value) => omitBy(value, (field) => field === void 0);
181
+ const nextEntry = ({ bin, next: { argv, when } }) => {
182
+ const entry = {
183
+ argv: [bin, ...argv],
184
+ command: shellCommand([bin, ...argv])
185
+ };
186
+ if (when !== void 0) entry.when = when;
187
+ return entry;
188
+ };
189
+ const nextEntries = ({ bin, steps }) => {
190
+ const entries = steps.flatMap((step) => "argv" in step ? [nextEntry({
191
+ bin,
192
+ next: step
193
+ })] : []);
194
+ return entries.length === 0 ? void 0 : entries;
195
+ };
196
+ const hasPlaceholder = (argv) => argv.some((word) => word.includes("<"));
197
+ const cellText = (cell) => isString(cell) ? cell : cell.text;
198
+ const cellPlain = (cell) => isString(cell) ? cell : cell.plain;
199
+ const COLUMN_GAP = 3;
200
+ const TABLE_INDENT = 2;
201
+ const MIN_OPTIONAL_WIDTH = 8;
202
+ const LIST_LIMIT = 5;
203
+ const MIN_WRAP$1 = 20;
204
+ const styledCommand = ({ argv, style }) => hasPlaceholder(argv) ? shellCommand(argv) : theme.command(style, shellCommand(argv));
205
+ const rowLines = (rows, style) => rows.flatMap(({ label, prose, value }) => {
206
+ const text = prose === true ? remoteText(value).replaceAll("\r", "") : remoteLine(value);
207
+ const lead = ` ${padEnd(label, 16)}`;
208
+ const room = style.width - 18;
209
+ if (prose === true && room >= MIN_WRAP$1) {
210
+ const [first = "", ...rest] = wrap({
211
+ text,
212
+ width: room
213
+ });
214
+ return [`${lead}${first}`, ...indent(rest, 18)];
215
+ }
216
+ if (displayWidth(label) >= 16 || displayWidth(text) > room) return [` ${label}`, ` ${text}`];
217
+ return [`${lead}${text}`];
218
+ });
219
+ const plainRowLines = (rows) => rows.map(({ label, value }) => `${label}\t${remoteCell({
220
+ separated: true,
221
+ text: value
222
+ })}`);
223
+ const listLines = (items) => {
224
+ const shown = items.slice(0, LIST_LIMIT).map((item) => ` ${remoteLine(item)}`);
225
+ const rest = items.length - LIST_LIMIT;
226
+ return rest <= 0 ? shown : [...shown, ` and ${String(rest)} more`];
227
+ };
228
+ const tableWidth = (widths) => TABLE_INDENT + sum(widths) + COLUMN_GAP * (widths.length - 1);
229
+ const fittedWidths = ({ natural, table, width }) => {
230
+ const fixed = sum(table.columns.map((column, index) => column.optional === true ? 0 : natural[index] ?? 0));
231
+ const optional = table.columns.filter((column) => column.optional === true).length;
232
+ const room = width - TABLE_INDENT - fixed - COLUMN_GAP * (table.columns.length - 1);
233
+ const share = optional === 0 ? 0 : Math.floor(room / optional);
234
+ return table.columns.map((column, index) => column.optional === true ? Math.min(natural[index] ?? 0, Math.max(share, MIN_OPTIONAL_WIDTH, displayWidth(column.header))) : natural[index] ?? 0);
235
+ };
236
+ const recoveryLines = ({ bin, recovery, style }) => recovery.flatMap(({ instruction, next, url }, index) => {
237
+ const lowered = `${instruction.charAt(0).toLowerCase()}${instruction.slice(1)}`;
238
+ const label = index === 0 ? instruction : `Or ${lowered}`;
239
+ if (next !== void 0) return [` ${label}:`, ` ${styledCommand({
240
+ argv: [bin, ...next.argv],
241
+ style
242
+ })}`];
243
+ if (url !== void 0) return [` ${label}:`, ` ${url}`];
244
+ return [` ${label}`];
245
+ });
246
+ const headlineLines = ({ lead, style, text }) => {
247
+ const [first = "", ...rest] = wrap({
248
+ text: remoteLine(text),
249
+ width: Math.max(MIN_WRAP$1, style.width - 2)
250
+ });
251
+ return [`${lead} ${first}`, ...indent(rest, 2)];
252
+ };
253
+ const stepLines = ({ bin, steps, style }) => steps.flatMap((step) => [` ${step.benefit}:`, ` ${"argv" in step ? styledCommand({
254
+ argv: [bin, ...step.argv],
255
+ style
256
+ }) : step.url}`]);
257
+ const errorDocument = ({ bin, failure, warnings }) => {
258
+ const next = (failure.recovery ?? []).flatMap((recovery) => recovery.next === void 0 ? [] : [nextEntry({
259
+ bin,
260
+ next: recovery.next
261
+ })]);
262
+ const issues = failure.issues ?? [];
263
+ const data = definedOnly({
264
+ ...failure.data,
265
+ issues: issues.length === 0 ? void 0 : issues.map(({ field, message }) => ({
266
+ field,
267
+ message,
268
+ reason: failure.reason
269
+ })),
270
+ remoteMessage: failure.remoteMessage === void 0 ? void 0 : remoteText(failure.remoteMessage)
271
+ });
272
+ const document = {
273
+ message: failure.message,
274
+ reason: failure.reason,
275
+ status: statusOf$1(failure)
276
+ };
277
+ if (Object.keys(data).length > 0) document.data = data;
278
+ if (next.length > 0) document.next = next;
279
+ if (failure.requestId !== void 0) document.requestId = failure.requestId;
280
+ if (failure.retryAfter !== void 0) document.retryAfter = failure.retryAfter;
281
+ if (failure.retryable !== void 0) document.retryable = failure.retryable;
282
+ if (failure.userActionRequired === true) document.userActionRequired = true;
283
+ if (warnings.length > 0) document.warnings = warnings;
284
+ return document;
285
+ };
286
+ var Output = class {
287
+ warnings = [];
288
+ bin;
289
+ err;
290
+ guidance;
291
+ mode;
292
+ out;
293
+ spinner = null;
294
+ stderrUsed = false;
295
+ constructor({ bin, err, guidance, mode, out }) {
296
+ this.bin = bin;
297
+ this.err = err;
298
+ this.guidance = guidance;
299
+ this.mode = mode;
300
+ this.out = out;
301
+ }
302
+ get human() {
303
+ return this.mode.format === "human";
304
+ }
305
+ get errStyle() {
306
+ return this.mode.stderr;
307
+ }
308
+ get stdoutTerminal() {
309
+ return this.mode.stdout.tty;
310
+ }
311
+ writeErr(lines) {
312
+ this.stopSpinner();
313
+ for (const line of lines) this.err.write(`${line}\n`);
314
+ this.stderrUsed = true;
315
+ }
316
+ writeOut(lines) {
317
+ this.stopSpinner();
318
+ for (const line of lines) this.out.write(`${line}\n`);
319
+ }
320
+ block(lines) {
321
+ if (!this.human || lines.length === 0) return;
322
+ this.writeErr(this.stderrUsed ? ["", ...lines] : lines);
323
+ }
324
+ context(rows) {
325
+ this.block(rowLines(rows, this.errStyle));
326
+ }
327
+ note(lines) {
328
+ const width = Math.max(MIN_WRAP$1, this.errStyle.width - 2);
329
+ this.block(lines.flatMap((line) => indent(wrap({
330
+ text: remoteLine(line),
331
+ width
332
+ }), 2)));
333
+ }
334
+ receipt({ outcome, rows = [], target }) {
335
+ const style = this.errStyle;
336
+ const shown = remoteLine(target);
337
+ const label = theme.outcome(style, padEnd(outcome, 16));
338
+ const headline = style.rich ? `${glyph(style, "success")} ${label}${shown}` : `${outcome} ${shown}`;
339
+ this.block([headline, ...rowLines(rows, style)]);
340
+ }
341
+ warn(reason, message) {
342
+ if (this.warnings.some((warning) => warning.message === message)) return;
343
+ this.warnings.push({
344
+ message,
345
+ reason
346
+ });
347
+ if (!this.human) return;
348
+ const style = this.errStyle;
349
+ const lead = style.rich ? glyph(style, "warning") : plainPrefix(style, "warning");
350
+ this.writeErr(headlineLines({
351
+ lead,
352
+ style,
353
+ text: message
354
+ }));
355
+ }
356
+ next(steps) {
357
+ const style = this.errStyle;
358
+ const shown = steps.filter((step) => step.optional !== true || this.guidance);
359
+ const lines = stepLines({
360
+ bin: this.bin,
361
+ steps: shown,
362
+ style
363
+ });
364
+ this.block(shown.length > 1 ? [" Next steps:", ...lines] : lines);
365
+ }
366
+ progress(phase) {
367
+ if (!this.human) return { done: noop };
368
+ if (!this.errStyle.rich || !this.mode.interactive) {
369
+ this.writeErr([` ${phase}`]);
370
+ return { done: noop };
371
+ }
372
+ this.stopSpinner();
373
+ const spinner = {
374
+ phase,
375
+ tick: 0,
376
+ timer: setInterval(() => {
377
+ this.renderSpinner(spinner);
378
+ }, 80)
379
+ };
380
+ this.spinner = spinner;
381
+ this.renderSpinner(spinner);
382
+ this.stderrUsed = true;
383
+ return { done: () => {
384
+ if (this.spinner === spinner) this.stopSpinner();
385
+ } };
386
+ }
387
+ renderSpinner(spinner) {
388
+ this.err.write(`${clearLine}${spinnerFrame(spinner.tick)} ${spinner.phase}`);
389
+ spinner.tick += 1;
390
+ }
391
+ stopSpinner() {
392
+ if (this.spinner === null) return;
393
+ clearInterval(this.spinner.timer);
394
+ this.spinner = null;
395
+ this.err.write(clearLine);
396
+ }
397
+ details(rows) {
398
+ if (this.human) this.writeOut(this.stdoutTerminal ? rowLines(rows, this.mode.stdout) : plainRowLines(rows));
399
+ }
400
+ table({ empty, table }) {
401
+ if (!this.human) return;
402
+ const header = table.columns.map((column) => column.header);
403
+ if (table.rows.length === 0) {
404
+ if (!this.stdoutTerminal) this.writeOut([header.join(" ")]);
405
+ this.block([` ${empty}`]);
406
+ return;
407
+ }
408
+ if (!this.stdoutTerminal) {
409
+ this.writeOut([header.join(" "), ...table.rows.map((row) => row.map((cell) => remoteCell({
410
+ separated: true,
411
+ text: cellPlain(cell)
412
+ })).join(" "))]);
413
+ return;
414
+ }
415
+ this.writeOut(this.alignedTable(table));
416
+ }
417
+ alignedTable(table) {
418
+ const style = this.mode.stdout;
419
+ const cells = table.rows.map((row) => row.map((cell) => remoteCell({
420
+ separated: false,
421
+ text: cellText(cell)
422
+ })));
423
+ const natural = table.columns.map((column, index) => Math.max(displayWidth(column.header), ...cells.map((row) => displayWidth(row[index] ?? ""))));
424
+ const widths = tableWidth(natural) > style.width ? fittedWidths({
425
+ natural,
426
+ table,
427
+ width: style.width
428
+ }) : natural;
429
+ if (tableWidth(widths) > style.width) return cells.flatMap((row, index) => [...index === 0 ? [] : [""], ...rowLines(table.columns.map((column, position) => ({
430
+ label: column.header,
431
+ value: row[position] ?? ""
432
+ })), style)]);
433
+ const line = (row) => {
434
+ const shown = row.map((cell, index) => {
435
+ const width = widths[index] ?? 0;
436
+ const cut = truncate({
437
+ ellipsis: ellipsis(style),
438
+ text: cell,
439
+ width
440
+ });
441
+ return index === row.length - 1 ? cut : padEnd(cut, width);
442
+ });
443
+ return `${" ".repeat(TABLE_INDENT)}${shown.join(" ".repeat(COLUMN_GAP))}`.trimEnd();
444
+ };
445
+ return [line(table.columns.map((column) => column.header)), ...cells.map(line)];
446
+ }
447
+ identifier(id) {
448
+ if (this.human && !(this.mode.interactive && this.stdoutTerminal)) this.writeOut([id]);
449
+ }
450
+ mask(secret) {
451
+ if (this.mode.githubActions) {
452
+ this.stopSpinner();
453
+ this.err.write(`::add-mask::${secret}\n`);
454
+ }
455
+ }
456
+ secret(secret) {
457
+ if (this.human) this.writeOut([secret]);
458
+ }
459
+ bytes(text) {
460
+ if (this.human) {
461
+ this.stopSpinner();
462
+ this.out.write(this.stdoutTerminal ? escapeUnprintable(text) : text);
463
+ }
464
+ }
465
+ values(lines) {
466
+ if (this.human) this.writeOut(lines.map((line) => remoteLine(line)));
467
+ }
468
+ document(document) {
469
+ this.stopSpinner();
470
+ const full = this.warnings.length === 0 ? document : {
471
+ ...document,
472
+ warnings: this.warnings
473
+ };
474
+ const text = this.stdoutTerminal ? JSON.stringify(full, null, 2) : JSON.stringify(full);
475
+ this.out.write(`${text}\n`);
476
+ }
477
+ failure(failure) {
478
+ this.stopSpinner();
479
+ if (!this.human) {
480
+ this.err.write(`${JSON.stringify(errorDocument({
481
+ bin: this.bin,
482
+ failure,
483
+ warnings: this.warnings
484
+ }))}\n`);
485
+ return;
486
+ }
487
+ const style = this.errStyle;
488
+ const lead = style.rich ? glyph(style, "error") : plainPrefix(style, "error");
489
+ const issues = failure.issues ?? [];
490
+ const width = Math.max(MIN_WRAP$1, style.width - 2);
491
+ const recovery = recoveryLines({
492
+ bin: this.bin,
493
+ recovery: failure.recovery ?? [],
494
+ style
495
+ });
496
+ this.block([
497
+ ...headlineLines({
498
+ lead,
499
+ style,
500
+ text: failure.message
501
+ }),
502
+ ...(failure.notes ?? []).flatMap((note) => indent(wrap({
503
+ text: remoteLine(note),
504
+ width
505
+ }), 2)),
506
+ ...issues.length > 1 ? listLines(issues.map(({ message }) => message)) : [],
507
+ ...rowLines(failure.detail ?? [], style),
508
+ ...rowLines(failure.context ?? [], style),
509
+ ...rowLines(failure.ids ?? [], style),
510
+ ...recovery.length === 0 ? [] : ["", ...recovery]
511
+ ]);
512
+ }
513
+ canceled({ lines, next = [], remote }) {
514
+ this.stopSpinner();
515
+ if (this.human) {
516
+ this.block(lines);
517
+ this.next(next);
518
+ return;
519
+ }
520
+ const document = {
521
+ data: { remote },
522
+ message: lines[0] ?? "Canceled.",
523
+ reason: "canceled",
524
+ status: "error"
525
+ };
526
+ document.next = nextEntries({
527
+ bin: this.bin,
528
+ steps: next
529
+ });
530
+ if (this.warnings.length > 0) document.warnings = this.warnings;
531
+ this.err.write(`${JSON.stringify(document)}\n`);
532
+ }
533
+ };
534
+ // ../cli-core/src/route.ts
535
+ const HELP = "help";
536
+ const WORDS = "words";
537
+ const optionsFor = (options, surface) => options.filter((option) => option.surfaces === void 0 || option.surfaces.includes(surface));
538
+ const childrenOf = (node, surface) => node.children.filter((child) => child.surfaces === void 0 || child.surfaces.includes(surface));
539
+ const matches = (node, token) => node.name === token || (node.shortcuts ?? []).includes(token);
540
+ const subtreeOptions = (node) => node.kind === "leaf" ? node.options : [...node.options ?? [], ...node.children.flatMap(subtreeOptions)];
541
+ const knownOptions = ({ cli, node, surface }) => [...optionsFor(cli.globals, surface), ...subtreeOptions(node)];
542
+ const isHelpCommand = (path) => path.length === 1 && path[0] === HELP;
543
+ const takeOption = (walk, argv, token) => {
544
+ const read = readOptionToken({
545
+ options: knownOptions(walk),
546
+ token
547
+ });
548
+ walk.tokens.push(token);
549
+ walk.index += 1;
550
+ if (read.option === void 0) {
551
+ walk.unknownOption ??= token;
552
+ return;
553
+ }
554
+ const next = argv[walk.index];
555
+ if (read.option.kind === "value" && read.explicit === null && next !== void 0 && isOptionValue(next)) {
556
+ walk.tokens.push(next);
557
+ walk.index += 1;
558
+ }
559
+ };
560
+ const takeWord = (walk, token) => {
561
+ const { node } = walk;
562
+ walk.index += 1;
563
+ if (node.kind === "leaf" || walk.words) {
564
+ walk.tokens.push(token);
565
+ return;
566
+ }
567
+ const children = childrenOf(node, walk.surface);
568
+ const child = children.find((candidate) => matches(candidate, token));
569
+ if (child !== void 0) {
570
+ walk.node = child;
571
+ walk.path = [...walk.path, child.name];
572
+ return;
573
+ }
574
+ if (isHelpCommand(walk.path)) {
575
+ walk.words = true;
576
+ walk.tokens.push(token);
577
+ return;
578
+ }
579
+ walk.unknownCommand ??= {
580
+ kind: "command",
581
+ path: walk.path,
582
+ segment: token,
583
+ suggestion: closest({
584
+ candidates: children.map((candidate) => candidate.name),
585
+ token
586
+ })
587
+ };
588
+ };
589
+ const optionFailure = (walk) => {
590
+ if (walk.unknownOption === null) return null;
591
+ const read = readOptionToken({
592
+ options: knownOptions(walk),
593
+ token: walk.unknownOption
594
+ });
595
+ return {
596
+ kind: "option",
597
+ path: walk.path,
598
+ segment: read.spelled,
599
+ suggestion: read.suggestion
600
+ };
601
+ };
602
+ const route = ({ argv, cli, surface }) => {
603
+ const walk = {
604
+ cli,
605
+ index: 0,
606
+ node: cli.root,
607
+ path: [],
608
+ surface,
609
+ tokens: [],
610
+ unknownCommand: null,
611
+ unknownOption: null,
612
+ words: false
613
+ };
614
+ while (walk.index < argv.length) {
615
+ const token = argv[walk.index] ?? "";
616
+ if (token === "--") {
617
+ walk.tokens.push(...argv.slice(walk.index));
618
+ break;
619
+ }
620
+ if (isOptionToken(token)) takeOption(walk, argv, token);
621
+ else takeWord(walk, token);
622
+ }
623
+ return {
624
+ node: walk.node,
625
+ path: walk.path,
626
+ tokens: walk.tokens,
627
+ unknownCommand: walk.unknownCommand,
628
+ unknownOption: optionFailure(walk)
629
+ };
630
+ };
631
+ const routeFailure = ({ bin, failure }) => {
632
+ const suggestion = failure.suggestion === void 0 ? "" : ` Did you mean ${failure.suggestion}?`;
633
+ const message = `Unknown ${failure.kind} ${failure.segment} for ${[bin, ...failure.path].join(" ")}.${suggestion}`;
634
+ const issues = [{
635
+ field: failure.segment,
636
+ message
637
+ }];
638
+ return failure.kind === "command" ? new CliFailure({
639
+ issues,
640
+ message,
641
+ reason: "unknown_command",
642
+ recovery: [{
643
+ instruction: "See all commands",
644
+ next: { argv: [...failure.path, "--help"] }
645
+ }]
646
+ }) : usageFailure({
647
+ help: failure.path,
648
+ issues,
649
+ message,
650
+ reason: "unknown_option"
651
+ });
652
+ };
653
+ const helpTarget = ({ cli, surface, words }) => {
654
+ const { node, path, unknownCommand } = route({
655
+ argv: words,
656
+ cli,
657
+ surface
658
+ });
659
+ return unknownCommand === null ? {
660
+ node,
661
+ path
662
+ } : routeFailure({
663
+ bin: cli.bin,
664
+ failure: unknownCommand
665
+ });
666
+ };
667
+ const refusalOf = ({ help, unknownCommand, unknownOption }) => {
668
+ if (unknownCommand !== null) return unknownOption ?? unknownCommand;
669
+ return help ? null : unknownOption;
670
+ };
671
+ const readCommandLine = ({ argv, cli, surface }) => {
672
+ const routed = route({
673
+ argv,
674
+ cli,
675
+ surface
676
+ });
677
+ const { node, tokens } = routed;
678
+ const { input, issues } = parseLeaf({
679
+ arguments: [{
680
+ name: WORDS,
681
+ optional: true,
682
+ variadic: true
683
+ }],
684
+ command: [cli.bin, ...routed.path].join(" "),
685
+ options: knownOptions({
686
+ cli,
687
+ node: cli.root,
688
+ surface
689
+ }),
690
+ tokens
691
+ });
692
+ const line = {
693
+ options: input.options,
694
+ path: routed.path,
695
+ unknownCommand: routed.unknownCommand !== null,
696
+ used: input.used
697
+ };
698
+ const help = flagOf(input.options, "help") === true;
699
+ const refused = refusalOf({
700
+ ...routed,
701
+ help
702
+ });
703
+ if (refused !== null) return {
704
+ ...line,
705
+ failure: routeFailure({
706
+ bin: cli.bin,
707
+ failure: refused
708
+ }),
709
+ kind: "refused"
710
+ };
711
+ if (isHelpCommand(routed.path)) return issues.length === 0 ? {
712
+ ...line,
713
+ kind: "helpCommand",
714
+ words: input.arguments[WORDS] ?? []
715
+ } : {
716
+ ...line,
717
+ failure: parseFailure({
718
+ bin: cli.bin,
719
+ issues,
720
+ path: routed.path
721
+ }),
722
+ kind: "refused"
723
+ };
724
+ if (help) return {
725
+ ...line,
726
+ kind: "help",
727
+ node
728
+ };
729
+ if (flagOf(input.options, "version") === true) return {
730
+ ...line,
731
+ kind: "version"
732
+ };
733
+ if (node.kind === "leaf") return {
734
+ ...line,
735
+ kind: "leaf",
736
+ leaf: node,
737
+ tokens
738
+ };
739
+ const child = childrenOf(node, surface).find((candidate) => candidate.name === node.defaultChild);
740
+ return child?.kind === "leaf" ? {
741
+ ...line,
742
+ kind: "leaf",
743
+ leaf: child,
744
+ path: [...routed.path, child.name],
745
+ tokens
746
+ } : {
747
+ ...line,
748
+ kind: "help",
749
+ node
750
+ };
751
+ };
752
+ // ../cli-core/src/help.ts
753
+ const COMMANDS = "Commands";
754
+ const MIN_WRAP = 20;
755
+ const SEARCH_LIMIT = 10;
756
+ const PATH_WEIGHT = 3;
757
+ const SUMMARY_WEIGHT = 2;
758
+ const isNameCharacter = (character) => isWordCharacter(character) || character === "-";
759
+ const optionNameEnd = (syntax) => {
760
+ const start = syntax.startsWith("-") && isWordCharacter(syntax.charAt(1)) && syntax.startsWith(", ", 2) ? 4 : 0;
761
+ if (!syntax.startsWith("--", start)) return 0;
762
+ const rest = syntax.slice(start + 2).split("");
763
+ const stop = rest.findIndex((character) => !isNameCharacter(character));
764
+ const length = stop === -1 ? rest.length : stop;
765
+ return length === 0 ? 0 : start + 2 + length;
766
+ };
767
+ const decorateOptionName = (style, syntax) => {
768
+ const end = optionNameEnd(syntax);
769
+ return end === 0 ? syntax : `${theme.name(style, syntax.slice(0, end))}${syntax.slice(end)}`;
770
+ };
771
+ const argumentSyntax = (argument) => {
772
+ const name = argument.optional === true ? `[${argument.name}]` : `<${argument.name}>`;
773
+ return argument.variadic === true ? `${name}...` : name;
774
+ };
775
+ const optionSyntax = (option) => {
776
+ const hint = option.hint === void 0 ? "" : ` ${option.hint}`;
777
+ const long = `--${option.name}${hint}`;
778
+ return option.short === void 0 ? long : `-${option.short}, ${long}`;
779
+ };
780
+ const optionDescription = (option) => {
781
+ const parts = [option.summary];
782
+ if (option.values !== void 0) parts.push(`(one of: ${option.values.join(", ")})`);
783
+ if (option.defaultText !== void 0) parts.push(`(default: ${option.defaultText})`);
784
+ return parts.join(" ");
785
+ };
786
+ const usageText = ({ bin, node, path }) => {
787
+ const head = [bin, ...path].join(" ");
788
+ if (node.kind === "group") return `${head} <command> [options]`;
789
+ return [
790
+ head,
791
+ ...node.options.flatMap((option) => option.required === true ? [`--${option.name} ${option.hint ?? "<VALUE>"}`] : []),
792
+ ...node.arguments.map(argumentSyntax),
793
+ "[options]"
794
+ ].join(" ");
795
+ };
796
+ const section = (style, title, lines) => lines.length === 0 ? [] : [
797
+ "",
798
+ theme.heading(style, `${title}:`),
799
+ ...lines
800
+ ];
801
+ const optionLines = ({ options, style, surface }) => twoColumn({
802
+ decorate: (syntax) => decorateOptionName(style, syntax),
803
+ entries: optionsFor(options, surface).toSorted((left, right) => left.name.localeCompare(right.name)).map((option) => ({
804
+ description: optionDescription(option),
805
+ syntax: optionSyntax(option)
806
+ })),
807
+ indentBy: 2,
808
+ width: style.width
809
+ });
810
+ const commandLines = ({ entries, style }) => twoColumn({
811
+ decorate: (syntax) => theme.name(style, syntax),
812
+ entries,
813
+ indentBy: 2,
814
+ width: style.width
815
+ });
816
+ const taskSections = ({ cli, style, surface }) => cli.tasks.flatMap(({ paths, title }) => section(style, title, commandLines({
817
+ entries: paths.flatMap((path) => {
818
+ const found = helpTarget({
819
+ cli,
820
+ surface,
821
+ words: path
822
+ });
823
+ return found instanceof CliFailure ? [] : [{
824
+ description: found.node.summary,
825
+ syntax: path.join(" ")
826
+ }];
827
+ }),
828
+ style
829
+ })));
830
+ const childSections = ({ node, style, surface }) => [...section(style, COMMANDS, commandLines({
831
+ entries: childrenOf(node, surface).map((child) => ({
832
+ description: node.defaultChild === child.name ? `${child.summary} (default)` : child.summary,
833
+ syntax: [child.name, ...child.shortcuts ?? []].join(", ")
834
+ })),
835
+ style
836
+ })), ...section(style, "Options", optionLines({
837
+ options: node.options ?? [],
838
+ style,
839
+ surface
840
+ }))];
841
+ const groupSections = ({ cli, isRoot, node, style, surface }) => isRoot ? taskSections({
842
+ cli,
843
+ style,
844
+ surface
845
+ }) : childSections({
846
+ node,
847
+ style,
848
+ surface
849
+ });
850
+ const leafSections = ({ node, style, surface }) => [...section(style, "Arguments", twoColumn({
851
+ entries: node.arguments.map((argument) => ({
852
+ description: argument.summary,
853
+ syntax: argumentSyntax(argument)
854
+ })),
855
+ indentBy: 2,
856
+ width: style.width
857
+ })), ...section(style, "Options", optionLines({
858
+ options: node.options,
859
+ style,
860
+ surface
861
+ }))];
862
+ const exampleLines = ({ bin, node, style }) => node.kind === "leaf" ? section(style, "Examples", node.examples.flatMap(({ argv, summary }, index) => [
863
+ ...index === 0 ? [] : [""],
864
+ ` ${summary}`,
865
+ ` ${styledCommand({
866
+ argv: [bin, ...argv],
867
+ style
868
+ })}`
869
+ ])) : [];
870
+ const renderHelp = ({ cli, node, path, style, surface }) => {
871
+ const isRoot = path.length === 0;
872
+ const head = [cli.bin, ...path].join(" ");
873
+ const usage = usageText({
874
+ bin: cli.bin,
875
+ node,
876
+ path
877
+ });
878
+ const width = Math.max(MIN_WRAP, style.width - 2);
879
+ return `${[
880
+ `${theme.name(style, head)}${usage.slice(head.length)}`,
881
+ theme.optional(style, node.summary),
882
+ ...node.kind === "leaf" ? leafSections({
883
+ node,
884
+ style,
885
+ surface
886
+ }) : groupSections({
887
+ cli,
888
+ isRoot,
889
+ node,
890
+ style,
891
+ surface
892
+ }),
893
+ ...isRoot ? section(style, "Global Options", optionLines({
894
+ options: cli.globals,
895
+ style,
896
+ surface
897
+ })) : ["", `${theme.heading(style, "Global Options:")} See \`${cli.bin} --help\``],
898
+ ...exampleLines({
899
+ bin: cli.bin,
900
+ node,
901
+ style
902
+ }),
903
+ ...section(style, "Notes", (node.notes ?? []).flatMap((note) => indent(wrap({
904
+ text: note,
905
+ width
906
+ }), 2))),
907
+ ...cli.learnMore === void 0 ? [] : ["", `Learn more: ${cli.learnMore}`]
908
+ ].join("\n")}\n`;
909
+ };
910
+ const optionDocument = (option) => ({
911
+ default: option.defaultText ?? null,
912
+ name: option.name,
913
+ repeatable: option.repeat === "append",
914
+ short: option.short ?? null,
915
+ type: option.kind === "flag" ? "boolean" : "string",
916
+ values: option.values ?? null,
917
+ valueHint: option.hint ?? null
918
+ });
919
+ const argumentDocument = (argument) => ({
920
+ name: argument.name,
921
+ required: argument.optional !== true,
922
+ summary: argument.summary
923
+ });
924
+ const exampleDocuments = ({ bin, node }) => node.kind === "leaf" ? node.examples.map(({ argv, summary }) => ({
925
+ argv: [bin, ...argv],
926
+ command: shellCommand([bin, ...argv]),
927
+ summary
928
+ })) : [];
929
+ const subcommandDocument = ({ child, group }) => ({
930
+ default: group.defaultChild === child.name,
931
+ summary: child.summary
932
+ });
933
+ const allCommands = ({ path = [], root, surface }) => childrenOf(root, surface).flatMap((child) => {
934
+ const childPath = [...path, child.name];
935
+ return child.kind === "group" ? [{
936
+ node: child,
937
+ path: childPath
938
+ }, ...allCommands({
939
+ path: childPath,
940
+ root: child,
941
+ surface
942
+ })] : [{
943
+ node: child,
944
+ path: childPath
945
+ }];
946
+ });
947
+ const scoreOf = ({ node, path, words }) => {
948
+ const named = path.join(" ");
949
+ const summary = node.summary.toLowerCase();
950
+ const examples = node.kind === "leaf" ? node.examples.flatMap((example) => [example.summary, example.argv.join(" ")]).join(" ").toLowerCase() : "";
951
+ return words.reduce((score, word) => score + (named.includes(word) ? PATH_WEIGHT : 0) + (summary.includes(word) ? SUMMARY_WEIGHT : 0) + (examples.includes(word) ? 1 : 0), 0);
952
+ };
953
+ const searchCommands = ({ query, root, surface }) => {
954
+ const words = query.toLowerCase().split("").map((character) => character === "," || character.trim() === "" ? " " : character).join("").split(" ").filter((word) => word !== "");
955
+ return allCommands({
956
+ root,
957
+ surface
958
+ }).flatMap((entry) => {
959
+ const score = scoreOf({
960
+ ...entry,
961
+ words
962
+ });
963
+ return score > 0 ? [{
964
+ entry,
965
+ score
966
+ }] : [];
967
+ }).toSorted((left, right) => right.score - left.score || left.entry.path.join(" ").localeCompare(right.entry.path.join(" "))).slice(0, SEARCH_LIMIT).map(({ entry }) => entry);
968
+ };
969
+ const listCommands = ({ bin, empty, found, io }) => {
970
+ io.table({
971
+ empty,
972
+ table: {
973
+ columns: [{ header: "Command" }, { header: "Summary" }],
974
+ rows: found.map(({ node, path }) => [[bin, ...path].join(" "), node.summary])
975
+ }
976
+ });
977
+ if (found.length === 0) io.next([{
978
+ argv: ["--help"],
979
+ benefit: "See all commands"
980
+ }]);
981
+ };
982
+ // ../cli-core/src/mode.ts
983
+ const DEFAULT_WIDTH = 80;
984
+ const terminalOf = (stream) => ({
985
+ columns: stream.columns,
986
+ tty: stream.isTTY === true
987
+ });
988
+ const falsy = /* @__PURE__ */ new Set([
989
+ "",
990
+ "0",
991
+ "false"
992
+ ]);
993
+ const enabledVariable = (value) => value !== void 0 && !falsy.has(value.trim().toLowerCase());
994
+ const nonempty = (value) => value !== void 0 && value !== "";
995
+ const colorPreference = ({ env, noColor }) => {
996
+ if (noColor || nonempty(env.NO_COLOR)) return false;
997
+ const forced = env.FORCE_COLOR;
998
+ if (forced === void 0) return;
999
+ return forced !== "0" && forced.toLowerCase() !== "false";
1000
+ };
1001
+ const streamStyle = ({ accessible, color, env, terminal }) => {
1002
+ const rich = terminal.tty && env.TERM !== "dumb" && !accessible;
1003
+ return {
1004
+ color: color ?? rich,
1005
+ rich,
1006
+ tty: terminal.tty,
1007
+ width: terminal.columns !== void 0 && terminal.columns > 0 ? terminal.columns : DEFAULT_WIDTH
1008
+ };
1009
+ };
1010
+ const interactionAllowed = (input, ci) => {
1011
+ if (!(input.stdin.tty && input.stderr.tty && !input.payloadStdin) || input.json || ci || input.nonInteractive === true) return false;
1012
+ return input.agent === void 0 || input.nonInteractive === false;
1013
+ };
1014
+ const resolveMode = (input) => {
1015
+ const { accessible } = input;
1016
+ const ci = enabledVariable(input.env.CI);
1017
+ const color = colorPreference(input);
1018
+ return {
1019
+ accessible,
1020
+ agent: input.agent,
1021
+ ci,
1022
+ format: input.json ? "json" : "human",
1023
+ githubActions: input.env.GITHUB_ACTIONS === "true",
1024
+ interactive: interactionAllowed(input, ci),
1025
+ stderr: streamStyle({
1026
+ accessible,
1027
+ color,
1028
+ env: input.env,
1029
+ terminal: input.stderr
1030
+ }),
1031
+ stdout: streamStyle({
1032
+ accessible,
1033
+ color,
1034
+ env: input.env,
1035
+ terminal: input.stdout
1036
+ })
1037
+ };
1038
+ };
1039
+ const AGENT_VARIABLES = [
1040
+ "AGENT",
1041
+ "AI_AGENT",
1042
+ "AUGMENT_AGENT",
1043
+ "CLAUDECODE",
1044
+ "CLAUDE_CODE",
1045
+ "CODEX_SANDBOX",
1046
+ "CURSOR_AGENT",
1047
+ "GEMINI_CLI",
1048
+ "OPENCODE"
1049
+ ];
1050
+ const productVariable = ({ bin, name }) => `${bin.toUpperCase()}_${name}`;
1051
+ const guidanceOn = ({ bin, env = process.env }) => !enabledVariable(env[productVariable({
1052
+ bin,
1053
+ name: "GUIDANCE_DISABLED"
1054
+ })]);
1055
+ const accessibleOn = ({ bin, env = process.env }) => enabledVariable(env[productVariable({
1056
+ bin,
1057
+ name: "ACCESSIBLE"
1058
+ })]);
1059
+ const modeOf = ({ bin, env = process.env, io, json, noColor, nonInteractive, payloadStdin }) => resolveMode({
1060
+ accessible: accessibleOn({
1061
+ bin,
1062
+ env
1063
+ }),
1064
+ agent: AGENT_VARIABLES.find((name) => enabledVariable(env[name])),
1065
+ env,
1066
+ json,
1067
+ noColor,
1068
+ nonInteractive: nonInteractive ?? null,
1069
+ payloadStdin,
1070
+ stderr: terminalOf(io.stderr),
1071
+ stdin: terminalOf(io.stdin),
1072
+ stdout: terminalOf(io.stdout)
1073
+ });
1074
+ // ../cli-core/src/prompt.ts
1075
+ const ask = async (question) => {
1076
+ const { promise, reject, resolve } = Promise.withResolvers();
1077
+ const prompt = readline.createInterface({
1078
+ input: process.stdin,
1079
+ output: process.stderr,
1080
+ terminal: true
1081
+ });
1082
+ let answered = false;
1083
+ prompt.on("SIGINT", () => {
1084
+ prompt.close();
1085
+ });
1086
+ prompt.on("close", () => {
1087
+ if (!answered) {
1088
+ process.stderr.write("\n");
1089
+ reject(new Canceled({
1090
+ remote: "none",
1091
+ signal: "SIGINT"
1092
+ }));
1093
+ }
1094
+ });
1095
+ prompt.question(`? ${question} `, (answer) => {
1096
+ answered = true;
1097
+ prompt.close();
1098
+ resolve(answer);
1099
+ });
1100
+ return await promise;
1101
+ };
1102
+ const terminalPrompter = {
1103
+ confirm: async (question) => {
1104
+ const answer = await ask(`${question} (y/N)`);
1105
+ return ["y", "yes"].includes(answer.trim().toLowerCase());
1106
+ },
1107
+ text: async (question) => await ask(question)
1108
+ };
1109
+ millis(50);
1110
+ toMillis(seconds(90));
1111
+ seconds(20);
1112
+ TaggedError("LockHeld");
1113
+ const configDirectory = ({ bin, cwd, override }) => override === void 0 ? path.join(os.homedir(), ".config", bin) : path.resolve(cwd ?? process.cwd(), override);
1114
+ const writePrivateFile = ({ file, text }) => {
1115
+ const directory = path.dirname(file);
1116
+ fs.mkdirSync(directory, {
1117
+ mode: 448,
1118
+ recursive: true
1119
+ });
1120
+ const pending = path.join(directory, `.${path.basename(file)}.${crypto.randomBytes(8).toString("hex")}.tmp`);
1121
+ fs.writeFileSync(pending, text, {
1122
+ flag: "wx",
1123
+ mode: 384
1124
+ });
1125
+ fs.renameSync(pending, file);
1126
+ };
1127
+ // ../cli-core/src/telemetry-settings.ts
1128
+ const telemetrySettingsSchema = Struct({
1129
+ disclosed: optional(Boolean),
1130
+ enabled: optional(Boolean)
1131
+ });
1132
+ const settingsSchema = Struct({ telemetry: optional(telemetrySettingsSchema) });
1133
+ const decodeSettings = decodeUnknownOption(fromJsonString(settingsSchema));
1134
+ const readSettings = (file) => {
1135
+ const read = try_(() => fs.readFileSync(file, "utf-8"));
1136
+ if (isSuccess(read)) return getOrUndefined(decodeSettings(read.success));
1137
+ return hasProperty(read.failure, "code") && read.failure.code === "ENOENT" ? {} : void 0;
1138
+ };
1139
+ const disabledVariable = (bin) => productVariable({
1140
+ bin,
1141
+ name: "TELEMETRY_DISABLED"
1142
+ });
1143
+ const telemetryStatus = ({ bin, env = process.env, file }) => {
1144
+ const settings = readSettings(file);
1145
+ const disclosed = settings?.telemetry?.disclosed === true;
1146
+ if (enabledVariable(env[disabledVariable(bin)])) return {
1147
+ disclosed,
1148
+ enabled: false,
1149
+ readable: settings !== void 0,
1150
+ source: "environment"
1151
+ };
1152
+ if (settings === void 0) return {
1153
+ disclosed,
1154
+ enabled: false,
1155
+ readable: false,
1156
+ source: "settings"
1157
+ };
1158
+ const enabled = settings.telemetry?.enabled;
1159
+ return enabled === void 0 ? {
1160
+ disclosed,
1161
+ enabled: true,
1162
+ readable: true,
1163
+ source: "default"
1164
+ } : {
1165
+ disclosed,
1166
+ enabled,
1167
+ readable: true,
1168
+ source: "settings"
1169
+ };
1170
+ };
1171
+ const writeTelemetry = ({ file, telemetry }) => {
1172
+ const settings = readSettings(file) ?? {};
1173
+ writePrivateFile({
1174
+ file,
1175
+ text: `${JSON.stringify({
1176
+ ...settings,
1177
+ telemetry: {
1178
+ ...settings.telemetry,
1179
+ ...telemetry
1180
+ }
1181
+ }, null, 2)}\n`
1182
+ });
1183
+ };
1184
+ const statusText = ({ bin, file, status }) => {
1185
+ if (status.source === "environment") return `Off, since ${disabledVariable(bin)} is set.`;
1186
+ if (!status.readable) return `Off, since ${file} can't be read.`;
1187
+ return status.enabled ? "On." : "Off.";
1188
+ };
1189
+ const telemetryCommand = ({ action, bin, env = process.env, file, io }) => {
1190
+ const report = (status, outcome) => {
1191
+ io.receipt({
1192
+ outcome: "Telemetry",
1193
+ target: statusText({
1194
+ bin,
1195
+ file,
1196
+ status
1197
+ })
1198
+ });
1199
+ return {
1200
+ outcome,
1201
+ telemetry: {
1202
+ enabled: status.enabled,
1203
+ source: status.source
1204
+ }
1205
+ };
1206
+ };
1207
+ const before = telemetryStatus({
1208
+ bin,
1209
+ env,
1210
+ file
1211
+ });
1212
+ if (action === "status") return report(before);
1213
+ if (!before.readable) return new CliFailure({
1214
+ message: `${file}: the CLI settings can't be read.`,
1215
+ notes: ["Fix the file or move it away, then run the command again."],
1216
+ reason: "invalid_config"
1217
+ });
1218
+ const enabled = action === "enable";
1219
+ if (before.source === "settings" && before.enabled === enabled) return report(before, "unchanged");
1220
+ writeTelemetry({
1221
+ file,
1222
+ telemetry: {
1223
+ disclosed: true,
1224
+ enabled
1225
+ }
1226
+ });
1227
+ return report(telemetryStatus({
1228
+ bin,
1229
+ env,
1230
+ file
1231
+ }), enabled ? "enabled" : "disabled");
1232
+ };
1233
+ // src/cli/local.ts
1234
+ const helpSearch = (context) => {
1235
+ const query = (context.arguments.query ?? []).join(" ");
1236
+ const found = searchCommands({
1237
+ query,
1238
+ root: CLI.root,
1239
+ surface: "cli"
1240
+ });
1241
+ listCommands({
1242
+ bin: CLI.bin,
1243
+ empty: `No commands match "${query}".`,
1244
+ found,
1245
+ io: context.io
1246
+ });
1247
+ return { document: { commands: found.map(({ node, path }) => ({
1248
+ argv: [CLI.bin, ...path],
1249
+ path: path.join(" "),
1250
+ summary: node.summary
1251
+ })) } };
1252
+ };
1253
+ const telemetry = (action) => ({ io, settingsFile }) => {
1254
+ const document = telemetryCommand({
1255
+ action,
1256
+ bin: CLI.bin,
1257
+ file: settingsFile,
1258
+ io
1259
+ });
1260
+ if (document instanceof CliFailure) throw document;
1261
+ return { document };
1262
+ };
1263
+ const LOCAL_COMMANDS = /* @__PURE__ */ new Map([
1264
+ ["cli telemetry disable", telemetry("disable")],
1265
+ ["cli telemetry enable", telemetry("enable")],
1266
+ ["cli telemetry status", telemetry("status")],
1267
+ ["help search", helpSearch]
1268
+ ]);
1269
+ // src/cli/settings.ts
1270
+ const settingsFileOf = (directory) => path.join(configDirectory({
1271
+ bin: BIN,
1272
+ override: directory
1273
+ }), "settings.json");
1274
+ // src/cli/telemetry.ts
1275
+ const DISCLOSURE = "The Sandcovery CLI sends anonymous usage data: command paths, option names, failure reasons, and exit codes, never values or remote data.";
1276
+ const DISCLOSURE_STEP = {
1277
+ argv: [
1278
+ "cli",
1279
+ "telemetry",
1280
+ "disable"
1281
+ ],
1282
+ benefit: "Turn it off"
1283
+ };
1284
+ const telemetryHost = (origin) => loopbackOrigin(process.env.__SANDCOVERY_POSTHOG_HOST) ?? (origin === "https://www.sandcovery.com" ? "https://us.i.posthog.com" : void 0);
1285
+ const sendTelemetry = ({ event, host }) => {
1286
+ sendTelemetry$1({
1287
+ bin: BIN,
1288
+ event: {
1289
+ ...event,
1290
+ version
1291
+ },
1292
+ host
1293
+ });
1294
+ };
1295
+ // src/cli/main.ts
1296
+ const CANCELED_EXIT = 130;
1297
+ const SUCCESS = { exitCode: 0 };
1298
+ const UNREADABLE = /* @__PURE__ */ new Map([
1299
+ ["EACCES", "isn't readable"],
1300
+ ["EISDIR", "is a directory"],
1301
+ ["ENOENT", "doesn't exist"]
1302
+ ]);
1303
+ const globalsOf = (options) => ({
1304
+ debug: flagOf(options, "debug") === true,
1305
+ globalConfig: lastValue(options, "global-config"),
1306
+ json: flagOf(options, "json") === true,
1307
+ noColor: flagOf(options, "no-color") === true,
1308
+ nonInteractive: flagOf(options, "non-interactive"),
1309
+ token: lastValue(options, "token")
1310
+ });
1311
+ const commandOf = ({ leaf, path: commandPath, tokens }) => {
1312
+ const { input, issues } = parseLeaf({
1313
+ arguments: leaf.arguments,
1314
+ command: [CLI.bin, ...commandPath].join(" "),
1315
+ options: [...CLI.globals, ...leaf.options],
1316
+ tokens
1317
+ });
1318
+ if (issues.length > 0) return {
1319
+ failure: parseFailure({
1320
+ bin: CLI.bin,
1321
+ issues,
1322
+ path: commandPath
1323
+ }),
1324
+ kind: "failure"
1325
+ };
1326
+ const empty = Object.entries(input.options).find(([, value]) => value.kind === "value" && value.values.some((text) => text.trim() === ""));
1327
+ if (empty !== void 0) {
1328
+ const field = `--${empty[0]}`;
1329
+ const message = `Can't use an empty ${field}.`;
1330
+ return {
1331
+ failure: usageFailure({
1332
+ help: commandPath,
1333
+ issues: [{
1334
+ field,
1335
+ message
1336
+ }],
1337
+ message
1338
+ }),
1339
+ kind: "failure"
1340
+ };
1341
+ }
1342
+ return {
1343
+ input,
1344
+ kind: "command",
1345
+ path: commandPath
1346
+ };
1347
+ };
1348
+ const invocationOf = (line) => {
1349
+ switch (line.kind) {
1350
+ case "refused": return {
1351
+ failure: line.failure,
1352
+ kind: "failure"
1353
+ };
1354
+ case "helpCommand": return {
1355
+ all: flagOf(line.options, "all") === true,
1356
+ kind: "help",
1357
+ path: line.words
1358
+ };
1359
+ case "help": return {
1360
+ all: false,
1361
+ kind: "help",
1362
+ path: line.path
1363
+ };
1364
+ case "version": return { kind: "version" };
1365
+ case "leaf": return commandOf(line);
1366
+ default: return commandOf(line);
1367
+ }
1368
+ };
1369
+ const failed = ({ failure, session }) => {
1370
+ session.out.failure(failure);
1371
+ return {
1372
+ exitCode: exitCodeOf(failure.reason),
1373
+ reason: failure.reason
1374
+ };
1375
+ };
1376
+ const succeeded = ({ finished, session }) => {
1377
+ if (session.mode.format === "json") session.out.document(jsonRecord({ value: finished.document }));
1378
+ else if (finished.next !== void 0 && finished.next.length > 0) session.out.next(finished.next);
1379
+ return { exitCode: finished.exitCode ?? 0 };
1380
+ };
1381
+ const canceled = ({ progress, session }) => {
1382
+ const unknown = progress.sent && progress.mutation;
1383
+ const lines = unknown ? ["Stopped waiting. Can't confirm whether the request finished."] : [progress.sent ? "Canceled." : "Canceled. Nothing was changed."];
1384
+ session.out.canceled({
1385
+ lines,
1386
+ next: unknown && progress.inspect !== null ? [{
1387
+ argv: progress.inspect,
1388
+ benefit: "Check what happened"
1389
+ }] : [],
1390
+ remote: unknown ? "unknown" : "none"
1391
+ });
1392
+ return {
1393
+ exitCode: Number.isInteger(session.signal.reason) ? Number(session.signal.reason) : CANCELED_EXIT,
1394
+ reason: "canceled"
1395
+ };
1396
+ };
1397
+ const internalFailure = (commandPath) => new CliFailure({
1398
+ message: `Unexpected error in sandcovery ${commandPath.join(" ")}. This is a bug in the Sandcovery CLI.`,
1399
+ reason: "internal_error",
1400
+ recovery: [{
1401
+ instruction: "See the details",
1402
+ next: { argv: [...commandPath, "--debug"] }
1403
+ }, {
1404
+ instruction: "Report it to the Sandcovery team",
1405
+ url: "mailto:team@sandcovery.com"
1406
+ }]
1407
+ });
1408
+ const debugLine = (session) => (line) => {
1409
+ if (session.globals.debug) session.io.stderr.write(`debug: ${line}\n`);
1410
+ };
1411
+ const readSource = async (source) => {
1412
+ if (source === "-") return new Uint8Array(await buffer(process.stdin));
1413
+ const read = try_(() => fs.readFileSync(path.resolve(source)));
1414
+ if (isSuccess(read)) return new Uint8Array(read.success);
1415
+ const { failure } = read;
1416
+ const reason = UNREADABLE.get(hasProperty(failure, "code") && isString(failure.code) ? failure.code : "");
1417
+ if (reason === void 0) throw failure;
1418
+ throw new CliFailure({
1419
+ message: `Can't read ${source}. The file ${reason}.`,
1420
+ reason: "invalid_arguments"
1421
+ });
1422
+ };
1423
+ const runCommand = async ({ invocation, session }) => {
1424
+ const progress = {
1425
+ inspect: null,
1426
+ mutation: false,
1427
+ sent: false
1428
+ };
1429
+ const { input } = invocation;
1430
+ const context = {
1431
+ arguments: input.arguments,
1432
+ debug: debugLine(session),
1433
+ io: session.out,
1434
+ mode: session.mode,
1435
+ now: /* @__PURE__ */ new Date(),
1436
+ options: input.options,
1437
+ path: invocation.path,
1438
+ progress,
1439
+ prompter: session.mode.interactive ? terminalPrompter : void 0,
1440
+ read: readSource,
1441
+ rerun: rerunArgv({
1442
+ arguments: input.arguments,
1443
+ options: input.options,
1444
+ path: invocation.path
1445
+ }),
1446
+ settingsFile: session.settingsFile,
1447
+ signal: session.signal,
1448
+ streams: {
1449
+ stderr: session.io.stderr,
1450
+ stdout: session.io.stdout
1451
+ },
1452
+ token: session.globals.token
1453
+ };
1454
+ const key = invocation.path.join(" ");
1455
+ const settle = async () => {
1456
+ try {
1457
+ const local = LOCAL_COMMANDS.get(key);
1458
+ if (local !== void 0) return local(context);
1459
+ const { HANDLERS } = await import("../handlers-rkx0CsMY.mjs");
1460
+ const handler = HANDLERS.get(key);
1461
+ if (handler === void 0) throw internalFailure(invocation.path);
1462
+ return await handler(context);
1463
+ } catch (error) {
1464
+ if (error instanceof Canceled || error instanceof CliFailure || session.signal.aborted) throw error;
1465
+ context.debug(error instanceof Error ? error.stack ?? error.message : String(error));
1466
+ throw internalFailure(invocation.path);
1467
+ }
1468
+ };
1469
+ try {
1470
+ return succeeded({
1471
+ finished: await settle(),
1472
+ session
1473
+ });
1474
+ } catch (error) {
1475
+ if (error instanceof Canceled || session.signal.aborted) return canceled({
1476
+ progress,
1477
+ session
1478
+ });
1479
+ if (error instanceof CliFailure) return failed({
1480
+ failure: error,
1481
+ session
1482
+ });
1483
+ throw error;
1484
+ }
1485
+ };
1486
+ const optionDocumentOf = (option) => ({
1487
+ ...optionDocument(option),
1488
+ deprecated: null,
1489
+ summary: option.summary
1490
+ });
1491
+ const commandDocument = ({ node, path: nodePath }) => ({
1492
+ arguments: node.kind === "group" ? [] : node.arguments.map(argumentDocument),
1493
+ examples: exampleDocuments({
1494
+ bin: CLI.bin,
1495
+ node
1496
+ }),
1497
+ lifecycle: null,
1498
+ options: node.kind === "group" ? [] : node.options.map(optionDocumentOf),
1499
+ path: nodePath.join(" "),
1500
+ resultSchema: node.kind === "group" || node.result.length === 0 ? null : { fields: node.result.map(({ name, secret, type }) => ({
1501
+ name,
1502
+ secret: secret ?? false,
1503
+ type
1504
+ })) },
1505
+ subcommands: node.kind === "group" ? node.children.map((child) => ({
1506
+ ...subcommandDocument({
1507
+ child,
1508
+ group: node
1509
+ }),
1510
+ path: [...nodePath, child.name].join(" ")
1511
+ })) : [],
1512
+ summary: node.summary
1513
+ });
1514
+ const showHelp = ({ all, path: words, session }) => {
1515
+ const json = session.mode.format === "json";
1516
+ if (all) {
1517
+ const commands = allCommands({
1518
+ root: CLI.root,
1519
+ surface: "cli"
1520
+ });
1521
+ if (json) session.out.document(jsonRecord({ value: { commands: [{
1522
+ node: CLI.root,
1523
+ path: []
1524
+ }, ...commands].map(commandDocument) } }));
1525
+ else listCommands({
1526
+ bin: CLI.bin,
1527
+ empty: "",
1528
+ found: commands,
1529
+ io: session.out
1530
+ });
1531
+ return SUCCESS;
1532
+ }
1533
+ const target = helpTarget({
1534
+ cli: CLI,
1535
+ surface: "cli",
1536
+ words
1537
+ });
1538
+ if (target instanceof CliFailure) return failed({
1539
+ failure: target,
1540
+ session
1541
+ });
1542
+ if (json) session.out.document(jsonRecord({ value: target.path.length === 0 ? {
1543
+ ...commandDocument(target),
1544
+ globalOptions: CLI.globals.map(optionDocumentOf)
1545
+ } : commandDocument(target) }));
1546
+ else session.io.stdout.write(renderHelp({
1547
+ cli: CLI,
1548
+ ...target,
1549
+ style: session.mode.stdout,
1550
+ surface: "cli"
1551
+ }));
1552
+ return SUCCESS;
1553
+ };
1554
+ const dispatch = async (session) => {
1555
+ const { invocation } = session;
1556
+ switch (invocation.kind) {
1557
+ case "failure": return failed({
1558
+ failure: invocation.failure,
1559
+ session
1560
+ });
1561
+ case "help": return showHelp({
1562
+ all: invocation.all,
1563
+ path: invocation.path,
1564
+ session
1565
+ });
1566
+ case "version":
1567
+ if (session.mode.format === "json") session.out.document({ version });
1568
+ else session.io.stdout.write(`${version}\n`);
1569
+ return SUCCESS;
1570
+ case "command": return await runCommand({
1571
+ invocation,
1572
+ session
1573
+ });
1574
+ default: return await runCommand({
1575
+ invocation,
1576
+ session
1577
+ });
1578
+ }
1579
+ };
1580
+ const discloses = (session) => session.mode.format !== "json" && session.invocation.kind !== "help" && session.invocation.kind !== "version" && !session.telemetryPath.startsWith("cli telemetry");
1581
+ const disclose = (session) => {
1582
+ if (session.mode.interactive) {
1583
+ session.out.note([DISCLOSURE]);
1584
+ session.out.next([DISCLOSURE_STEP]);
1585
+ } else session.io.stderr.write(`${DISCLOSURE} Turn it off with ${shellCommand([CLI.bin, ...DISCLOSURE_STEP.argv])} or SANDCOVERY_TELEMETRY_DISABLED=1.\n`);
1586
+ const saved = try_(() => {
1587
+ writeTelemetry({
1588
+ file: session.settingsFile,
1589
+ telemetry: { disclosed: true }
1590
+ });
1591
+ });
1592
+ if (isFailure(saved)) session.out.note([`Couldn't save to ${session.settingsFile} that telemetry was disclosed.`]);
1593
+ };
1594
+ const statusOf = (session) => telemetryStatus({
1595
+ bin: CLI.bin,
1596
+ file: session.settingsFile
1597
+ });
1598
+ const telemetryAllowed = ({ host, session }) => {
1599
+ if (host === void 0) return false;
1600
+ const status = statusOf(session);
1601
+ if (!status.enabled) return false;
1602
+ if (status.disclosed) return true;
1603
+ if (!discloses(session)) return false;
1604
+ disclose(session);
1605
+ return true;
1606
+ };
1607
+ const originFor = (options) => {
1608
+ const chosen = [lastValue(options, "base-url"), process.env.SANDCOVERY_BASE_URL].find((value) => value !== void 0 && value.trim() !== "");
1609
+ return chosen === void 0 ? SANDCOVERY_ORIGIN : URL.parse(chosen.trim())?.origin ?? chosen;
1610
+ };
1611
+ const run = async ({ argv, io, signal }) => {
1612
+ const line = readCommandLine({
1613
+ argv,
1614
+ cli: CLI,
1615
+ surface: "cli"
1616
+ });
1617
+ const globals = globalsOf(line.options);
1618
+ const invocation = invocationOf(line);
1619
+ const options = invocation.kind === "command" ? invocation.input.options : line.options;
1620
+ const mode = modeOf({
1621
+ bin: CLI.bin,
1622
+ io,
1623
+ json: globals.json,
1624
+ noColor: globals.noColor,
1625
+ nonInteractive: globals.nonInteractive,
1626
+ payloadStdin: lastValue(options, "from") === "-"
1627
+ });
1628
+ const session = {
1629
+ globals,
1630
+ invocation,
1631
+ io,
1632
+ mode,
1633
+ out: new Output({
1634
+ bin: CLI.bin,
1635
+ err: io.stderr,
1636
+ guidance: guidanceOn({ bin: CLI.bin }),
1637
+ mode,
1638
+ out: io.stdout
1639
+ }),
1640
+ settingsFile: settingsFileOf(globals.globalConfig),
1641
+ signal,
1642
+ telemetryPath: [...line.path, ...line.unknownCommand ? ["<path>"] : []].join(" ")
1643
+ };
1644
+ if (globals.debug) io.stderr.write(`debug: sandcovery ${version}, node ${process.version}, ${process.platform}, interactive ${String(mode.interactive)}, agent ${String(mode.agent !== void 0)}, ci ${String(mode.ci)}\n`);
1645
+ const host = telemetryHost(originFor(options));
1646
+ const send = telemetryAllowed({
1647
+ host,
1648
+ session
1649
+ });
1650
+ const outcome = await dispatch(session);
1651
+ if (send && host !== void 0 && statusOf(session).enabled) sendTelemetry({
1652
+ event: {
1653
+ command: session.telemetryPath,
1654
+ exitCode: outcome.exitCode,
1655
+ options: line.used,
1656
+ reason: outcome.reason
1657
+ },
1658
+ host
1659
+ });
1660
+ return outcome.exitCode;
1661
+ };
1662
+ // src/cli/index.ts
1663
+ const SIGNAL_EXITS = [
1664
+ ["SIGHUP", 129],
1665
+ ["SIGINT", 130],
1666
+ ["SIGTERM", 143]
1667
+ ];
1668
+ const quietOnBrokenPipe = (stream) => {
1669
+ stream.on("error", (error) => {
1670
+ if (error.code === "EPIPE") process.exit(process.exitCode ?? 0);
1671
+ throw error;
1672
+ });
1673
+ };
1674
+ const applyProxyFromEnv = () => {
1675
+ if ([
1676
+ process.env.HTTPS_PROXY,
1677
+ process.env.https_proxy,
1678
+ process.env.HTTP_PROXY,
1679
+ process.env.http_proxy
1680
+ ].some((value) => value !== void 0 && value !== "") && Object.hasOwn(http, "setGlobalProxyFromEnv")) http.setGlobalProxyFromEnv();
1681
+ };
1682
+ const event = process.env.__SANDCOVERY_TELEMETRY_EVENT;
1683
+ applyProxyFromEnv();
1684
+ if (event === void 0) {
1685
+ quietOnBrokenPipe(process.stdout);
1686
+ quietOnBrokenPipe(process.stderr);
1687
+ const controller = new AbortController();
1688
+ for (const [signal, code] of SIGNAL_EXITS) process.on(signal, () => {
1689
+ if (controller.signal.aborted) process.exit(code);
1690
+ controller.abort(code);
1691
+ });
1692
+ process.exitCode = await run({
1693
+ argv: process.argv.slice(2),
1694
+ io: {
1695
+ stderr: process.stderr,
1696
+ stdin: process.stdin,
1697
+ stdout: process.stdout
1698
+ },
1699
+ signal: controller.signal
1700
+ });
1701
+ } else {
1702
+ const [{ deliverTelemetry }, project] = await Promise.all([import("../telemetry-delivery-zinKRHRc.mjs"), import("../posthog-project-BpOd2VxW.mjs")]);
1703
+ await deliverTelemetry({
1704
+ host: process.env.__SANDCOVERY_POSTHOG_HOST,
1705
+ productionHost: project.POSTHOG_INGEST_HOST,
1706
+ text: event,
1707
+ token: project.POSTHOG_PROJECT_TOKEN
1708
+ });
1709
+ }
1710
+ export {};