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