@antasphere/slideless 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/LICENSE +21 -0
  2. package/dist/bin.js +4875 -0
  3. package/package.json +40 -0
package/dist/bin.js ADDED
@@ -0,0 +1,4875 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
10
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
11
+ }) : x)(function(x) {
12
+ if (typeof require !== "undefined") return require.apply(this, arguments);
13
+ throw Error('Dynamic require of "' + x + '" is not supported');
14
+ });
15
+ var __commonJS = (cb, mod) => function __require2() {
16
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27
+ // If the importer is in node compatibility mode or this is not an ESM
28
+ // file that has been converted to a CommonJS file using a Babel-
29
+ // compatible transform (i.e. "__esModule" has not been set), then set
30
+ // "default" to the CommonJS "module.exports" for node compatibility.
31
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
32
+ mod
33
+ ));
34
+
35
+ // ../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/error.js
36
+ var require_error = __commonJS({
37
+ "../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/error.js"(exports) {
38
+ var CommanderError2 = class extends Error {
39
+ /**
40
+ * Constructs the CommanderError class
41
+ * @param {number} exitCode suggested exit code which could be used with process.exit
42
+ * @param {string} code an id string representing the error
43
+ * @param {string} message human-readable description of the error
44
+ */
45
+ constructor(exitCode, code, message) {
46
+ super(message);
47
+ Error.captureStackTrace(this, this.constructor);
48
+ this.name = this.constructor.name;
49
+ this.code = code;
50
+ this.exitCode = exitCode;
51
+ this.nestedError = void 0;
52
+ }
53
+ };
54
+ var InvalidArgumentError2 = class extends CommanderError2 {
55
+ /**
56
+ * Constructs the InvalidArgumentError class
57
+ * @param {string} [message] explanation of why argument is invalid
58
+ */
59
+ constructor(message) {
60
+ super(1, "commander.invalidArgument", message);
61
+ Error.captureStackTrace(this, this.constructor);
62
+ this.name = this.constructor.name;
63
+ }
64
+ };
65
+ exports.CommanderError = CommanderError2;
66
+ exports.InvalidArgumentError = InvalidArgumentError2;
67
+ }
68
+ });
69
+
70
+ // ../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/argument.js
71
+ var require_argument = __commonJS({
72
+ "../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/argument.js"(exports) {
73
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
74
+ var Argument2 = class {
75
+ /**
76
+ * Initialize a new command argument with the given name and description.
77
+ * The default is that the argument is required, and you can explicitly
78
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
79
+ *
80
+ * @param {string} name
81
+ * @param {string} [description]
82
+ */
83
+ constructor(name, description) {
84
+ this.description = description || "";
85
+ this.variadic = false;
86
+ this.parseArg = void 0;
87
+ this.defaultValue = void 0;
88
+ this.defaultValueDescription = void 0;
89
+ this.argChoices = void 0;
90
+ switch (name[0]) {
91
+ case "<":
92
+ this.required = true;
93
+ this._name = name.slice(1, -1);
94
+ break;
95
+ case "[":
96
+ this.required = false;
97
+ this._name = name.slice(1, -1);
98
+ break;
99
+ default:
100
+ this.required = true;
101
+ this._name = name;
102
+ break;
103
+ }
104
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
105
+ this.variadic = true;
106
+ this._name = this._name.slice(0, -3);
107
+ }
108
+ }
109
+ /**
110
+ * Return argument name.
111
+ *
112
+ * @return {string}
113
+ */
114
+ name() {
115
+ return this._name;
116
+ }
117
+ /**
118
+ * @package
119
+ */
120
+ _concatValue(value, previous) {
121
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
122
+ return [value];
123
+ }
124
+ return previous.concat(value);
125
+ }
126
+ /**
127
+ * Set the default value, and optionally supply the description to be displayed in the help.
128
+ *
129
+ * @param {*} value
130
+ * @param {string} [description]
131
+ * @return {Argument}
132
+ */
133
+ default(value, description) {
134
+ this.defaultValue = value;
135
+ this.defaultValueDescription = description;
136
+ return this;
137
+ }
138
+ /**
139
+ * Set the custom handler for processing CLI command arguments into argument values.
140
+ *
141
+ * @param {Function} [fn]
142
+ * @return {Argument}
143
+ */
144
+ argParser(fn) {
145
+ this.parseArg = fn;
146
+ return this;
147
+ }
148
+ /**
149
+ * Only allow argument value to be one of choices.
150
+ *
151
+ * @param {string[]} values
152
+ * @return {Argument}
153
+ */
154
+ choices(values) {
155
+ this.argChoices = values.slice();
156
+ this.parseArg = (arg, previous) => {
157
+ if (!this.argChoices.includes(arg)) {
158
+ throw new InvalidArgumentError2(
159
+ `Allowed choices are ${this.argChoices.join(", ")}.`
160
+ );
161
+ }
162
+ if (this.variadic) {
163
+ return this._concatValue(arg, previous);
164
+ }
165
+ return arg;
166
+ };
167
+ return this;
168
+ }
169
+ /**
170
+ * Make argument required.
171
+ *
172
+ * @returns {Argument}
173
+ */
174
+ argRequired() {
175
+ this.required = true;
176
+ return this;
177
+ }
178
+ /**
179
+ * Make argument optional.
180
+ *
181
+ * @returns {Argument}
182
+ */
183
+ argOptional() {
184
+ this.required = false;
185
+ return this;
186
+ }
187
+ };
188
+ function humanReadableArgName(arg) {
189
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
190
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
191
+ }
192
+ exports.Argument = Argument2;
193
+ exports.humanReadableArgName = humanReadableArgName;
194
+ }
195
+ });
196
+
197
+ // ../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/help.js
198
+ var require_help = __commonJS({
199
+ "../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/help.js"(exports) {
200
+ var { humanReadableArgName } = require_argument();
201
+ var Help2 = class {
202
+ constructor() {
203
+ this.helpWidth = void 0;
204
+ this.sortSubcommands = false;
205
+ this.sortOptions = false;
206
+ this.showGlobalOptions = false;
207
+ }
208
+ /**
209
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
210
+ *
211
+ * @param {Command} cmd
212
+ * @returns {Command[]}
213
+ */
214
+ visibleCommands(cmd) {
215
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
216
+ const helpCommand = cmd._getHelpCommand();
217
+ if (helpCommand && !helpCommand._hidden) {
218
+ visibleCommands.push(helpCommand);
219
+ }
220
+ if (this.sortSubcommands) {
221
+ visibleCommands.sort((a, b) => {
222
+ return a.name().localeCompare(b.name());
223
+ });
224
+ }
225
+ return visibleCommands;
226
+ }
227
+ /**
228
+ * Compare options for sort.
229
+ *
230
+ * @param {Option} a
231
+ * @param {Option} b
232
+ * @returns {number}
233
+ */
234
+ compareOptions(a, b) {
235
+ const getSortKey = (option) => {
236
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
237
+ };
238
+ return getSortKey(a).localeCompare(getSortKey(b));
239
+ }
240
+ /**
241
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
242
+ *
243
+ * @param {Command} cmd
244
+ * @returns {Option[]}
245
+ */
246
+ visibleOptions(cmd) {
247
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
248
+ const helpOption = cmd._getHelpOption();
249
+ if (helpOption && !helpOption.hidden) {
250
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
251
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
252
+ if (!removeShort && !removeLong) {
253
+ visibleOptions.push(helpOption);
254
+ } else if (helpOption.long && !removeLong) {
255
+ visibleOptions.push(
256
+ cmd.createOption(helpOption.long, helpOption.description)
257
+ );
258
+ } else if (helpOption.short && !removeShort) {
259
+ visibleOptions.push(
260
+ cmd.createOption(helpOption.short, helpOption.description)
261
+ );
262
+ }
263
+ }
264
+ if (this.sortOptions) {
265
+ visibleOptions.sort(this.compareOptions);
266
+ }
267
+ return visibleOptions;
268
+ }
269
+ /**
270
+ * Get an array of the visible global options. (Not including help.)
271
+ *
272
+ * @param {Command} cmd
273
+ * @returns {Option[]}
274
+ */
275
+ visibleGlobalOptions(cmd) {
276
+ if (!this.showGlobalOptions) return [];
277
+ const globalOptions = [];
278
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
279
+ const visibleOptions = ancestorCmd.options.filter(
280
+ (option) => !option.hidden
281
+ );
282
+ globalOptions.push(...visibleOptions);
283
+ }
284
+ if (this.sortOptions) {
285
+ globalOptions.sort(this.compareOptions);
286
+ }
287
+ return globalOptions;
288
+ }
289
+ /**
290
+ * Get an array of the arguments if any have a description.
291
+ *
292
+ * @param {Command} cmd
293
+ * @returns {Argument[]}
294
+ */
295
+ visibleArguments(cmd) {
296
+ if (cmd._argsDescription) {
297
+ cmd.registeredArguments.forEach((argument) => {
298
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
299
+ });
300
+ }
301
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
302
+ return cmd.registeredArguments;
303
+ }
304
+ return [];
305
+ }
306
+ /**
307
+ * Get the command term to show in the list of subcommands.
308
+ *
309
+ * @param {Command} cmd
310
+ * @returns {string}
311
+ */
312
+ subcommandTerm(cmd) {
313
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
314
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
315
+ (args ? " " + args : "");
316
+ }
317
+ /**
318
+ * Get the option term to show in the list of options.
319
+ *
320
+ * @param {Option} option
321
+ * @returns {string}
322
+ */
323
+ optionTerm(option) {
324
+ return option.flags;
325
+ }
326
+ /**
327
+ * Get the argument term to show in the list of arguments.
328
+ *
329
+ * @param {Argument} argument
330
+ * @returns {string}
331
+ */
332
+ argumentTerm(argument) {
333
+ return argument.name();
334
+ }
335
+ /**
336
+ * Get the longest command term length.
337
+ *
338
+ * @param {Command} cmd
339
+ * @param {Help} helper
340
+ * @returns {number}
341
+ */
342
+ longestSubcommandTermLength(cmd, helper) {
343
+ return helper.visibleCommands(cmd).reduce((max, command) => {
344
+ return Math.max(max, helper.subcommandTerm(command).length);
345
+ }, 0);
346
+ }
347
+ /**
348
+ * Get the longest option term length.
349
+ *
350
+ * @param {Command} cmd
351
+ * @param {Help} helper
352
+ * @returns {number}
353
+ */
354
+ longestOptionTermLength(cmd, helper) {
355
+ return helper.visibleOptions(cmd).reduce((max, option) => {
356
+ return Math.max(max, helper.optionTerm(option).length);
357
+ }, 0);
358
+ }
359
+ /**
360
+ * Get the longest global option term length.
361
+ *
362
+ * @param {Command} cmd
363
+ * @param {Help} helper
364
+ * @returns {number}
365
+ */
366
+ longestGlobalOptionTermLength(cmd, helper) {
367
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
368
+ return Math.max(max, helper.optionTerm(option).length);
369
+ }, 0);
370
+ }
371
+ /**
372
+ * Get the longest argument term length.
373
+ *
374
+ * @param {Command} cmd
375
+ * @param {Help} helper
376
+ * @returns {number}
377
+ */
378
+ longestArgumentTermLength(cmd, helper) {
379
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
380
+ return Math.max(max, helper.argumentTerm(argument).length);
381
+ }, 0);
382
+ }
383
+ /**
384
+ * Get the command usage to be displayed at the top of the built-in help.
385
+ *
386
+ * @param {Command} cmd
387
+ * @returns {string}
388
+ */
389
+ commandUsage(cmd) {
390
+ let cmdName = cmd._name;
391
+ if (cmd._aliases[0]) {
392
+ cmdName = cmdName + "|" + cmd._aliases[0];
393
+ }
394
+ let ancestorCmdNames = "";
395
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
396
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
397
+ }
398
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
399
+ }
400
+ /**
401
+ * Get the description for the command.
402
+ *
403
+ * @param {Command} cmd
404
+ * @returns {string}
405
+ */
406
+ commandDescription(cmd) {
407
+ return cmd.description();
408
+ }
409
+ /**
410
+ * Get the subcommand summary to show in the list of subcommands.
411
+ * (Fallback to description for backwards compatibility.)
412
+ *
413
+ * @param {Command} cmd
414
+ * @returns {string}
415
+ */
416
+ subcommandDescription(cmd) {
417
+ return cmd.summary() || cmd.description();
418
+ }
419
+ /**
420
+ * Get the option description to show in the list of options.
421
+ *
422
+ * @param {Option} option
423
+ * @return {string}
424
+ */
425
+ optionDescription(option) {
426
+ const extraInfo = [];
427
+ if (option.argChoices) {
428
+ extraInfo.push(
429
+ // use stringify to match the display of the default value
430
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
431
+ );
432
+ }
433
+ if (option.defaultValue !== void 0) {
434
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
435
+ if (showDefault) {
436
+ extraInfo.push(
437
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
438
+ );
439
+ }
440
+ }
441
+ if (option.presetArg !== void 0 && option.optional) {
442
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
443
+ }
444
+ if (option.envVar !== void 0) {
445
+ extraInfo.push(`env: ${option.envVar}`);
446
+ }
447
+ if (extraInfo.length > 0) {
448
+ return `${option.description} (${extraInfo.join(", ")})`;
449
+ }
450
+ return option.description;
451
+ }
452
+ /**
453
+ * Get the argument description to show in the list of arguments.
454
+ *
455
+ * @param {Argument} argument
456
+ * @return {string}
457
+ */
458
+ argumentDescription(argument) {
459
+ const extraInfo = [];
460
+ if (argument.argChoices) {
461
+ extraInfo.push(
462
+ // use stringify to match the display of the default value
463
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
464
+ );
465
+ }
466
+ if (argument.defaultValue !== void 0) {
467
+ extraInfo.push(
468
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
469
+ );
470
+ }
471
+ if (extraInfo.length > 0) {
472
+ const extraDescripton = `(${extraInfo.join(", ")})`;
473
+ if (argument.description) {
474
+ return `${argument.description} ${extraDescripton}`;
475
+ }
476
+ return extraDescripton;
477
+ }
478
+ return argument.description;
479
+ }
480
+ /**
481
+ * Generate the built-in help text.
482
+ *
483
+ * @param {Command} cmd
484
+ * @param {Help} helper
485
+ * @returns {string}
486
+ */
487
+ formatHelp(cmd, helper) {
488
+ const termWidth = helper.padWidth(cmd, helper);
489
+ const helpWidth = helper.helpWidth || 80;
490
+ const itemIndentWidth = 2;
491
+ const itemSeparatorWidth = 2;
492
+ function formatItem(term, description) {
493
+ if (description) {
494
+ const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
495
+ return helper.wrap(
496
+ fullText,
497
+ helpWidth - itemIndentWidth,
498
+ termWidth + itemSeparatorWidth
499
+ );
500
+ }
501
+ return term;
502
+ }
503
+ function formatList(textArray) {
504
+ return textArray.join("\n").replace(/^/gm, " ".repeat(itemIndentWidth));
505
+ }
506
+ let output = [`Usage: ${helper.commandUsage(cmd)}`, ""];
507
+ const commandDescription = helper.commandDescription(cmd);
508
+ if (commandDescription.length > 0) {
509
+ output = output.concat([
510
+ helper.wrap(commandDescription, helpWidth, 0),
511
+ ""
512
+ ]);
513
+ }
514
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
515
+ return formatItem(
516
+ helper.argumentTerm(argument),
517
+ helper.argumentDescription(argument)
518
+ );
519
+ });
520
+ if (argumentList.length > 0) {
521
+ output = output.concat(["Arguments:", formatList(argumentList), ""]);
522
+ }
523
+ const optionList = helper.visibleOptions(cmd).map((option) => {
524
+ return formatItem(
525
+ helper.optionTerm(option),
526
+ helper.optionDescription(option)
527
+ );
528
+ });
529
+ if (optionList.length > 0) {
530
+ output = output.concat(["Options:", formatList(optionList), ""]);
531
+ }
532
+ if (this.showGlobalOptions) {
533
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
534
+ return formatItem(
535
+ helper.optionTerm(option),
536
+ helper.optionDescription(option)
537
+ );
538
+ });
539
+ if (globalOptionList.length > 0) {
540
+ output = output.concat([
541
+ "Global Options:",
542
+ formatList(globalOptionList),
543
+ ""
544
+ ]);
545
+ }
546
+ }
547
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
548
+ return formatItem(
549
+ helper.subcommandTerm(cmd2),
550
+ helper.subcommandDescription(cmd2)
551
+ );
552
+ });
553
+ if (commandList.length > 0) {
554
+ output = output.concat(["Commands:", formatList(commandList), ""]);
555
+ }
556
+ return output.join("\n");
557
+ }
558
+ /**
559
+ * Calculate the pad width from the maximum term length.
560
+ *
561
+ * @param {Command} cmd
562
+ * @param {Help} helper
563
+ * @returns {number}
564
+ */
565
+ padWidth(cmd, helper) {
566
+ return Math.max(
567
+ helper.longestOptionTermLength(cmd, helper),
568
+ helper.longestGlobalOptionTermLength(cmd, helper),
569
+ helper.longestSubcommandTermLength(cmd, helper),
570
+ helper.longestArgumentTermLength(cmd, helper)
571
+ );
572
+ }
573
+ /**
574
+ * Wrap the given string to width characters per line, with lines after the first indented.
575
+ * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
576
+ *
577
+ * @param {string} str
578
+ * @param {number} width
579
+ * @param {number} indent
580
+ * @param {number} [minColumnWidth=40]
581
+ * @return {string}
582
+ *
583
+ */
584
+ wrap(str, width, indent, minColumnWidth = 40) {
585
+ const indents = " \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF";
586
+ const manualIndent = new RegExp(`[\\n][${indents}]+`);
587
+ if (str.match(manualIndent)) return str;
588
+ const columnWidth = width - indent;
589
+ if (columnWidth < minColumnWidth) return str;
590
+ const leadingStr = str.slice(0, indent);
591
+ const columnText = str.slice(indent).replace("\r\n", "\n");
592
+ const indentString = " ".repeat(indent);
593
+ const zeroWidthSpace = "\u200B";
594
+ const breaks = `\\s${zeroWidthSpace}`;
595
+ const regex = new RegExp(
596
+ `
597
+ |.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,
598
+ "g"
599
+ );
600
+ const lines = columnText.match(regex) || [];
601
+ return leadingStr + lines.map((line, i) => {
602
+ if (line === "\n") return "";
603
+ return (i > 0 ? indentString : "") + line.trimEnd();
604
+ }).join("\n");
605
+ }
606
+ };
607
+ exports.Help = Help2;
608
+ }
609
+ });
610
+
611
+ // ../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/option.js
612
+ var require_option = __commonJS({
613
+ "../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/option.js"(exports) {
614
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
615
+ var Option2 = class {
616
+ /**
617
+ * Initialize a new `Option` with the given `flags` and `description`.
618
+ *
619
+ * @param {string} flags
620
+ * @param {string} [description]
621
+ */
622
+ constructor(flags, description) {
623
+ this.flags = flags;
624
+ this.description = description || "";
625
+ this.required = flags.includes("<");
626
+ this.optional = flags.includes("[");
627
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
628
+ this.mandatory = false;
629
+ const optionFlags = splitOptionFlags(flags);
630
+ this.short = optionFlags.shortFlag;
631
+ this.long = optionFlags.longFlag;
632
+ this.negate = false;
633
+ if (this.long) {
634
+ this.negate = this.long.startsWith("--no-");
635
+ }
636
+ this.defaultValue = void 0;
637
+ this.defaultValueDescription = void 0;
638
+ this.presetArg = void 0;
639
+ this.envVar = void 0;
640
+ this.parseArg = void 0;
641
+ this.hidden = false;
642
+ this.argChoices = void 0;
643
+ this.conflictsWith = [];
644
+ this.implied = void 0;
645
+ }
646
+ /**
647
+ * Set the default value, and optionally supply the description to be displayed in the help.
648
+ *
649
+ * @param {*} value
650
+ * @param {string} [description]
651
+ * @return {Option}
652
+ */
653
+ default(value, description) {
654
+ this.defaultValue = value;
655
+ this.defaultValueDescription = description;
656
+ return this;
657
+ }
658
+ /**
659
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
660
+ * The custom processing (parseArg) is called.
661
+ *
662
+ * @example
663
+ * new Option('--color').default('GREYSCALE').preset('RGB');
664
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
665
+ *
666
+ * @param {*} arg
667
+ * @return {Option}
668
+ */
669
+ preset(arg) {
670
+ this.presetArg = arg;
671
+ return this;
672
+ }
673
+ /**
674
+ * Add option name(s) that conflict with this option.
675
+ * An error will be displayed if conflicting options are found during parsing.
676
+ *
677
+ * @example
678
+ * new Option('--rgb').conflicts('cmyk');
679
+ * new Option('--js').conflicts(['ts', 'jsx']);
680
+ *
681
+ * @param {(string | string[])} names
682
+ * @return {Option}
683
+ */
684
+ conflicts(names) {
685
+ this.conflictsWith = this.conflictsWith.concat(names);
686
+ return this;
687
+ }
688
+ /**
689
+ * Specify implied option values for when this option is set and the implied options are not.
690
+ *
691
+ * The custom processing (parseArg) is not called on the implied values.
692
+ *
693
+ * @example
694
+ * program
695
+ * .addOption(new Option('--log', 'write logging information to file'))
696
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
697
+ *
698
+ * @param {object} impliedOptionValues
699
+ * @return {Option}
700
+ */
701
+ implies(impliedOptionValues) {
702
+ let newImplied = impliedOptionValues;
703
+ if (typeof impliedOptionValues === "string") {
704
+ newImplied = { [impliedOptionValues]: true };
705
+ }
706
+ this.implied = Object.assign(this.implied || {}, newImplied);
707
+ return this;
708
+ }
709
+ /**
710
+ * Set environment variable to check for option value.
711
+ *
712
+ * An environment variable is only used if when processed the current option value is
713
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
714
+ *
715
+ * @param {string} name
716
+ * @return {Option}
717
+ */
718
+ env(name) {
719
+ this.envVar = name;
720
+ return this;
721
+ }
722
+ /**
723
+ * Set the custom handler for processing CLI option arguments into option values.
724
+ *
725
+ * @param {Function} [fn]
726
+ * @return {Option}
727
+ */
728
+ argParser(fn) {
729
+ this.parseArg = fn;
730
+ return this;
731
+ }
732
+ /**
733
+ * Whether the option is mandatory and must have a value after parsing.
734
+ *
735
+ * @param {boolean} [mandatory=true]
736
+ * @return {Option}
737
+ */
738
+ makeOptionMandatory(mandatory = true) {
739
+ this.mandatory = !!mandatory;
740
+ return this;
741
+ }
742
+ /**
743
+ * Hide option in help.
744
+ *
745
+ * @param {boolean} [hide=true]
746
+ * @return {Option}
747
+ */
748
+ hideHelp(hide = true) {
749
+ this.hidden = !!hide;
750
+ return this;
751
+ }
752
+ /**
753
+ * @package
754
+ */
755
+ _concatValue(value, previous) {
756
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
757
+ return [value];
758
+ }
759
+ return previous.concat(value);
760
+ }
761
+ /**
762
+ * Only allow option value to be one of choices.
763
+ *
764
+ * @param {string[]} values
765
+ * @return {Option}
766
+ */
767
+ choices(values) {
768
+ this.argChoices = values.slice();
769
+ this.parseArg = (arg, previous) => {
770
+ if (!this.argChoices.includes(arg)) {
771
+ throw new InvalidArgumentError2(
772
+ `Allowed choices are ${this.argChoices.join(", ")}.`
773
+ );
774
+ }
775
+ if (this.variadic) {
776
+ return this._concatValue(arg, previous);
777
+ }
778
+ return arg;
779
+ };
780
+ return this;
781
+ }
782
+ /**
783
+ * Return option name.
784
+ *
785
+ * @return {string}
786
+ */
787
+ name() {
788
+ if (this.long) {
789
+ return this.long.replace(/^--/, "");
790
+ }
791
+ return this.short.replace(/^-/, "");
792
+ }
793
+ /**
794
+ * Return option name, in a camelcase format that can be used
795
+ * as a object attribute key.
796
+ *
797
+ * @return {string}
798
+ */
799
+ attributeName() {
800
+ return camelcase(this.name().replace(/^no-/, ""));
801
+ }
802
+ /**
803
+ * Check if `arg` matches the short or long flag.
804
+ *
805
+ * @param {string} arg
806
+ * @return {boolean}
807
+ * @package
808
+ */
809
+ is(arg) {
810
+ return this.short === arg || this.long === arg;
811
+ }
812
+ /**
813
+ * Return whether a boolean option.
814
+ *
815
+ * Options are one of boolean, negated, required argument, or optional argument.
816
+ *
817
+ * @return {boolean}
818
+ * @package
819
+ */
820
+ isBoolean() {
821
+ return !this.required && !this.optional && !this.negate;
822
+ }
823
+ };
824
+ var DualOptions = class {
825
+ /**
826
+ * @param {Option[]} options
827
+ */
828
+ constructor(options) {
829
+ this.positiveOptions = /* @__PURE__ */ new Map();
830
+ this.negativeOptions = /* @__PURE__ */ new Map();
831
+ this.dualOptions = /* @__PURE__ */ new Set();
832
+ options.forEach((option) => {
833
+ if (option.negate) {
834
+ this.negativeOptions.set(option.attributeName(), option);
835
+ } else {
836
+ this.positiveOptions.set(option.attributeName(), option);
837
+ }
838
+ });
839
+ this.negativeOptions.forEach((value, key) => {
840
+ if (this.positiveOptions.has(key)) {
841
+ this.dualOptions.add(key);
842
+ }
843
+ });
844
+ }
845
+ /**
846
+ * Did the value come from the option, and not from possible matching dual option?
847
+ *
848
+ * @param {*} value
849
+ * @param {Option} option
850
+ * @returns {boolean}
851
+ */
852
+ valueFromOption(value, option) {
853
+ const optionKey = option.attributeName();
854
+ if (!this.dualOptions.has(optionKey)) return true;
855
+ const preset = this.negativeOptions.get(optionKey).presetArg;
856
+ const negativeValue = preset !== void 0 ? preset : false;
857
+ return option.negate === (negativeValue === value);
858
+ }
859
+ };
860
+ function camelcase(str) {
861
+ return str.split("-").reduce((str2, word) => {
862
+ return str2 + word[0].toUpperCase() + word.slice(1);
863
+ });
864
+ }
865
+ function splitOptionFlags(flags) {
866
+ let shortFlag;
867
+ let longFlag;
868
+ const flagParts = flags.split(/[ |,]+/);
869
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))
870
+ shortFlag = flagParts.shift();
871
+ longFlag = flagParts.shift();
872
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
873
+ shortFlag = longFlag;
874
+ longFlag = void 0;
875
+ }
876
+ return { shortFlag, longFlag };
877
+ }
878
+ exports.Option = Option2;
879
+ exports.DualOptions = DualOptions;
880
+ }
881
+ });
882
+
883
+ // ../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/suggestSimilar.js
884
+ var require_suggestSimilar = __commonJS({
885
+ "../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/suggestSimilar.js"(exports) {
886
+ var maxDistance = 3;
887
+ function editDistance(a, b) {
888
+ if (Math.abs(a.length - b.length) > maxDistance)
889
+ return Math.max(a.length, b.length);
890
+ const d = [];
891
+ for (let i = 0; i <= a.length; i++) {
892
+ d[i] = [i];
893
+ }
894
+ for (let j = 0; j <= b.length; j++) {
895
+ d[0][j] = j;
896
+ }
897
+ for (let j = 1; j <= b.length; j++) {
898
+ for (let i = 1; i <= a.length; i++) {
899
+ let cost = 1;
900
+ if (a[i - 1] === b[j - 1]) {
901
+ cost = 0;
902
+ } else {
903
+ cost = 1;
904
+ }
905
+ d[i][j] = Math.min(
906
+ d[i - 1][j] + 1,
907
+ // deletion
908
+ d[i][j - 1] + 1,
909
+ // insertion
910
+ d[i - 1][j - 1] + cost
911
+ // substitution
912
+ );
913
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
914
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
915
+ }
916
+ }
917
+ }
918
+ return d[a.length][b.length];
919
+ }
920
+ function suggestSimilar(word, candidates) {
921
+ if (!candidates || candidates.length === 0) return "";
922
+ candidates = Array.from(new Set(candidates));
923
+ const searchingOptions = word.startsWith("--");
924
+ if (searchingOptions) {
925
+ word = word.slice(2);
926
+ candidates = candidates.map((candidate) => candidate.slice(2));
927
+ }
928
+ let similar = [];
929
+ let bestDistance = maxDistance;
930
+ const minSimilarity = 0.4;
931
+ candidates.forEach((candidate) => {
932
+ if (candidate.length <= 1) return;
933
+ const distance = editDistance(word, candidate);
934
+ const length = Math.max(word.length, candidate.length);
935
+ const similarity = (length - distance) / length;
936
+ if (similarity > minSimilarity) {
937
+ if (distance < bestDistance) {
938
+ bestDistance = distance;
939
+ similar = [candidate];
940
+ } else if (distance === bestDistance) {
941
+ similar.push(candidate);
942
+ }
943
+ }
944
+ });
945
+ similar.sort((a, b) => a.localeCompare(b));
946
+ if (searchingOptions) {
947
+ similar = similar.map((candidate) => `--${candidate}`);
948
+ }
949
+ if (similar.length > 1) {
950
+ return `
951
+ (Did you mean one of ${similar.join(", ")}?)`;
952
+ }
953
+ if (similar.length === 1) {
954
+ return `
955
+ (Did you mean ${similar[0]}?)`;
956
+ }
957
+ return "";
958
+ }
959
+ exports.suggestSimilar = suggestSimilar;
960
+ }
961
+ });
962
+
963
+ // ../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/command.js
964
+ var require_command = __commonJS({
965
+ "../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/lib/command.js"(exports) {
966
+ var EventEmitter = __require("node:events").EventEmitter;
967
+ var childProcess = __require("node:child_process");
968
+ var path = __require("node:path");
969
+ var fs = __require("node:fs");
970
+ var process2 = __require("node:process");
971
+ var { Argument: Argument2, humanReadableArgName } = require_argument();
972
+ var { CommanderError: CommanderError2 } = require_error();
973
+ var { Help: Help2 } = require_help();
974
+ var { Option: Option2, DualOptions } = require_option();
975
+ var { suggestSimilar } = require_suggestSimilar();
976
+ var Command2 = class _Command extends EventEmitter {
977
+ /**
978
+ * Initialize a new `Command`.
979
+ *
980
+ * @param {string} [name]
981
+ */
982
+ constructor(name) {
983
+ super();
984
+ this.commands = [];
985
+ this.options = [];
986
+ this.parent = null;
987
+ this._allowUnknownOption = false;
988
+ this._allowExcessArguments = true;
989
+ this.registeredArguments = [];
990
+ this._args = this.registeredArguments;
991
+ this.args = [];
992
+ this.rawArgs = [];
993
+ this.processedArgs = [];
994
+ this._scriptPath = null;
995
+ this._name = name || "";
996
+ this._optionValues = {};
997
+ this._optionValueSources = {};
998
+ this._storeOptionsAsProperties = false;
999
+ this._actionHandler = null;
1000
+ this._executableHandler = false;
1001
+ this._executableFile = null;
1002
+ this._executableDir = null;
1003
+ this._defaultCommandName = null;
1004
+ this._exitCallback = null;
1005
+ this._aliases = [];
1006
+ this._combineFlagAndOptionalValue = true;
1007
+ this._description = "";
1008
+ this._summary = "";
1009
+ this._argsDescription = void 0;
1010
+ this._enablePositionalOptions = false;
1011
+ this._passThroughOptions = false;
1012
+ this._lifeCycleHooks = {};
1013
+ this._showHelpAfterError = false;
1014
+ this._showSuggestionAfterError = true;
1015
+ this._outputConfiguration = {
1016
+ writeOut: (str) => process2.stdout.write(str),
1017
+ writeErr: (str) => process2.stderr.write(str),
1018
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
1019
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
1020
+ outputError: (str, write) => write(str)
1021
+ };
1022
+ this._hidden = false;
1023
+ this._helpOption = void 0;
1024
+ this._addImplicitHelpCommand = void 0;
1025
+ this._helpCommand = void 0;
1026
+ this._helpConfiguration = {};
1027
+ }
1028
+ /**
1029
+ * Copy settings that are useful to have in common across root command and subcommands.
1030
+ *
1031
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1032
+ *
1033
+ * @param {Command} sourceCommand
1034
+ * @return {Command} `this` command for chaining
1035
+ */
1036
+ copyInheritedSettings(sourceCommand) {
1037
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1038
+ this._helpOption = sourceCommand._helpOption;
1039
+ this._helpCommand = sourceCommand._helpCommand;
1040
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1041
+ this._exitCallback = sourceCommand._exitCallback;
1042
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1043
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1044
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1045
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1046
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1047
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1048
+ return this;
1049
+ }
1050
+ /**
1051
+ * @returns {Command[]}
1052
+ * @private
1053
+ */
1054
+ _getCommandAndAncestors() {
1055
+ const result = [];
1056
+ for (let command = this; command; command = command.parent) {
1057
+ result.push(command);
1058
+ }
1059
+ return result;
1060
+ }
1061
+ /**
1062
+ * Define a command.
1063
+ *
1064
+ * There are two styles of command: pay attention to where to put the description.
1065
+ *
1066
+ * @example
1067
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1068
+ * program
1069
+ * .command('clone <source> [destination]')
1070
+ * .description('clone a repository into a newly created directory')
1071
+ * .action((source, destination) => {
1072
+ * console.log('clone command called');
1073
+ * });
1074
+ *
1075
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1076
+ * program
1077
+ * .command('start <service>', 'start named service')
1078
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1079
+ *
1080
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1081
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1082
+ * @param {object} [execOpts] - configuration options (for executable)
1083
+ * @return {Command} returns new command for action handler, or `this` for executable command
1084
+ */
1085
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1086
+ let desc = actionOptsOrExecDesc;
1087
+ let opts = execOpts;
1088
+ if (typeof desc === "object" && desc !== null) {
1089
+ opts = desc;
1090
+ desc = null;
1091
+ }
1092
+ opts = opts || {};
1093
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1094
+ const cmd = this.createCommand(name);
1095
+ if (desc) {
1096
+ cmd.description(desc);
1097
+ cmd._executableHandler = true;
1098
+ }
1099
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1100
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1101
+ cmd._executableFile = opts.executableFile || null;
1102
+ if (args) cmd.arguments(args);
1103
+ this._registerCommand(cmd);
1104
+ cmd.parent = this;
1105
+ cmd.copyInheritedSettings(this);
1106
+ if (desc) return this;
1107
+ return cmd;
1108
+ }
1109
+ /**
1110
+ * Factory routine to create a new unattached command.
1111
+ *
1112
+ * See .command() for creating an attached subcommand, which uses this routine to
1113
+ * create the command. You can override createCommand to customise subcommands.
1114
+ *
1115
+ * @param {string} [name]
1116
+ * @return {Command} new command
1117
+ */
1118
+ createCommand(name) {
1119
+ return new _Command(name);
1120
+ }
1121
+ /**
1122
+ * You can customise the help with a subclass of Help by overriding createHelp,
1123
+ * or by overriding Help properties using configureHelp().
1124
+ *
1125
+ * @return {Help}
1126
+ */
1127
+ createHelp() {
1128
+ return Object.assign(new Help2(), this.configureHelp());
1129
+ }
1130
+ /**
1131
+ * You can customise the help by overriding Help properties using configureHelp(),
1132
+ * or with a subclass of Help by overriding createHelp().
1133
+ *
1134
+ * @param {object} [configuration] - configuration options
1135
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1136
+ */
1137
+ configureHelp(configuration) {
1138
+ if (configuration === void 0) return this._helpConfiguration;
1139
+ this._helpConfiguration = configuration;
1140
+ return this;
1141
+ }
1142
+ /**
1143
+ * The default output goes to stdout and stderr. You can customise this for special
1144
+ * applications. You can also customise the display of errors by overriding outputError.
1145
+ *
1146
+ * The configuration properties are all functions:
1147
+ *
1148
+ * // functions to change where being written, stdout and stderr
1149
+ * writeOut(str)
1150
+ * writeErr(str)
1151
+ * // matching functions to specify width for wrapping help
1152
+ * getOutHelpWidth()
1153
+ * getErrHelpWidth()
1154
+ * // functions based on what is being written out
1155
+ * outputError(str, write) // used for displaying errors, and not used for displaying help
1156
+ *
1157
+ * @param {object} [configuration] - configuration options
1158
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1159
+ */
1160
+ configureOutput(configuration) {
1161
+ if (configuration === void 0) return this._outputConfiguration;
1162
+ Object.assign(this._outputConfiguration, configuration);
1163
+ return this;
1164
+ }
1165
+ /**
1166
+ * Display the help or a custom message after an error occurs.
1167
+ *
1168
+ * @param {(boolean|string)} [displayHelp]
1169
+ * @return {Command} `this` command for chaining
1170
+ */
1171
+ showHelpAfterError(displayHelp = true) {
1172
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1173
+ this._showHelpAfterError = displayHelp;
1174
+ return this;
1175
+ }
1176
+ /**
1177
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1178
+ *
1179
+ * @param {boolean} [displaySuggestion]
1180
+ * @return {Command} `this` command for chaining
1181
+ */
1182
+ showSuggestionAfterError(displaySuggestion = true) {
1183
+ this._showSuggestionAfterError = !!displaySuggestion;
1184
+ return this;
1185
+ }
1186
+ /**
1187
+ * Add a prepared subcommand.
1188
+ *
1189
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1190
+ *
1191
+ * @param {Command} cmd - new subcommand
1192
+ * @param {object} [opts] - configuration options
1193
+ * @return {Command} `this` command for chaining
1194
+ */
1195
+ addCommand(cmd, opts) {
1196
+ if (!cmd._name) {
1197
+ throw new Error(`Command passed to .addCommand() must have a name
1198
+ - specify the name in Command constructor or using .name()`);
1199
+ }
1200
+ opts = opts || {};
1201
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1202
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1203
+ this._registerCommand(cmd);
1204
+ cmd.parent = this;
1205
+ cmd._checkForBrokenPassThrough();
1206
+ return this;
1207
+ }
1208
+ /**
1209
+ * Factory routine to create a new unattached argument.
1210
+ *
1211
+ * See .argument() for creating an attached argument, which uses this routine to
1212
+ * create the argument. You can override createArgument to return a custom argument.
1213
+ *
1214
+ * @param {string} name
1215
+ * @param {string} [description]
1216
+ * @return {Argument} new argument
1217
+ */
1218
+ createArgument(name, description) {
1219
+ return new Argument2(name, description);
1220
+ }
1221
+ /**
1222
+ * Define argument syntax for command.
1223
+ *
1224
+ * The default is that the argument is required, and you can explicitly
1225
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1226
+ *
1227
+ * @example
1228
+ * program.argument('<input-file>');
1229
+ * program.argument('[output-file]');
1230
+ *
1231
+ * @param {string} name
1232
+ * @param {string} [description]
1233
+ * @param {(Function|*)} [fn] - custom argument processing function
1234
+ * @param {*} [defaultValue]
1235
+ * @return {Command} `this` command for chaining
1236
+ */
1237
+ argument(name, description, fn, defaultValue) {
1238
+ const argument = this.createArgument(name, description);
1239
+ if (typeof fn === "function") {
1240
+ argument.default(defaultValue).argParser(fn);
1241
+ } else {
1242
+ argument.default(fn);
1243
+ }
1244
+ this.addArgument(argument);
1245
+ return this;
1246
+ }
1247
+ /**
1248
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1249
+ *
1250
+ * See also .argument().
1251
+ *
1252
+ * @example
1253
+ * program.arguments('<cmd> [env]');
1254
+ *
1255
+ * @param {string} names
1256
+ * @return {Command} `this` command for chaining
1257
+ */
1258
+ arguments(names) {
1259
+ names.trim().split(/ +/).forEach((detail) => {
1260
+ this.argument(detail);
1261
+ });
1262
+ return this;
1263
+ }
1264
+ /**
1265
+ * Define argument syntax for command, adding a prepared argument.
1266
+ *
1267
+ * @param {Argument} argument
1268
+ * @return {Command} `this` command for chaining
1269
+ */
1270
+ addArgument(argument) {
1271
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1272
+ if (previousArgument && previousArgument.variadic) {
1273
+ throw new Error(
1274
+ `only the last argument can be variadic '${previousArgument.name()}'`
1275
+ );
1276
+ }
1277
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1278
+ throw new Error(
1279
+ `a default value for a required argument is never used: '${argument.name()}'`
1280
+ );
1281
+ }
1282
+ this.registeredArguments.push(argument);
1283
+ return this;
1284
+ }
1285
+ /**
1286
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1287
+ *
1288
+ * @example
1289
+ * program.helpCommand('help [cmd]');
1290
+ * program.helpCommand('help [cmd]', 'show help');
1291
+ * program.helpCommand(false); // suppress default help command
1292
+ * program.helpCommand(true); // add help command even if no subcommands
1293
+ *
1294
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1295
+ * @param {string} [description] - custom description
1296
+ * @return {Command} `this` command for chaining
1297
+ */
1298
+ helpCommand(enableOrNameAndArgs, description) {
1299
+ if (typeof enableOrNameAndArgs === "boolean") {
1300
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1301
+ return this;
1302
+ }
1303
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
1304
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
1305
+ const helpDescription = description ?? "display help for command";
1306
+ const helpCommand = this.createCommand(helpName);
1307
+ helpCommand.helpOption(false);
1308
+ if (helpArgs) helpCommand.arguments(helpArgs);
1309
+ if (helpDescription) helpCommand.description(helpDescription);
1310
+ this._addImplicitHelpCommand = true;
1311
+ this._helpCommand = helpCommand;
1312
+ return this;
1313
+ }
1314
+ /**
1315
+ * Add prepared custom help command.
1316
+ *
1317
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1318
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1319
+ * @return {Command} `this` command for chaining
1320
+ */
1321
+ addHelpCommand(helpCommand, deprecatedDescription) {
1322
+ if (typeof helpCommand !== "object") {
1323
+ this.helpCommand(helpCommand, deprecatedDescription);
1324
+ return this;
1325
+ }
1326
+ this._addImplicitHelpCommand = true;
1327
+ this._helpCommand = helpCommand;
1328
+ return this;
1329
+ }
1330
+ /**
1331
+ * Lazy create help command.
1332
+ *
1333
+ * @return {(Command|null)}
1334
+ * @package
1335
+ */
1336
+ _getHelpCommand() {
1337
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1338
+ if (hasImplicitHelpCommand) {
1339
+ if (this._helpCommand === void 0) {
1340
+ this.helpCommand(void 0, void 0);
1341
+ }
1342
+ return this._helpCommand;
1343
+ }
1344
+ return null;
1345
+ }
1346
+ /**
1347
+ * Add hook for life cycle event.
1348
+ *
1349
+ * @param {string} event
1350
+ * @param {Function} listener
1351
+ * @return {Command} `this` command for chaining
1352
+ */
1353
+ hook(event, listener) {
1354
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1355
+ if (!allowedValues.includes(event)) {
1356
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1357
+ Expecting one of '${allowedValues.join("', '")}'`);
1358
+ }
1359
+ if (this._lifeCycleHooks[event]) {
1360
+ this._lifeCycleHooks[event].push(listener);
1361
+ } else {
1362
+ this._lifeCycleHooks[event] = [listener];
1363
+ }
1364
+ return this;
1365
+ }
1366
+ /**
1367
+ * Register callback to use as replacement for calling process.exit.
1368
+ *
1369
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1370
+ * @return {Command} `this` command for chaining
1371
+ */
1372
+ exitOverride(fn) {
1373
+ if (fn) {
1374
+ this._exitCallback = fn;
1375
+ } else {
1376
+ this._exitCallback = (err) => {
1377
+ if (err.code !== "commander.executeSubCommandAsync") {
1378
+ throw err;
1379
+ } else {
1380
+ }
1381
+ };
1382
+ }
1383
+ return this;
1384
+ }
1385
+ /**
1386
+ * Call process.exit, and _exitCallback if defined.
1387
+ *
1388
+ * @param {number} exitCode exit code for using with process.exit
1389
+ * @param {string} code an id string representing the error
1390
+ * @param {string} message human-readable description of the error
1391
+ * @return never
1392
+ * @private
1393
+ */
1394
+ _exit(exitCode, code, message) {
1395
+ if (this._exitCallback) {
1396
+ this._exitCallback(new CommanderError2(exitCode, code, message));
1397
+ }
1398
+ process2.exit(exitCode);
1399
+ }
1400
+ /**
1401
+ * Register callback `fn` for the command.
1402
+ *
1403
+ * @example
1404
+ * program
1405
+ * .command('serve')
1406
+ * .description('start service')
1407
+ * .action(function() {
1408
+ * // do work here
1409
+ * });
1410
+ *
1411
+ * @param {Function} fn
1412
+ * @return {Command} `this` command for chaining
1413
+ */
1414
+ action(fn) {
1415
+ const listener = (args) => {
1416
+ const expectedArgsCount = this.registeredArguments.length;
1417
+ const actionArgs = args.slice(0, expectedArgsCount);
1418
+ if (this._storeOptionsAsProperties) {
1419
+ actionArgs[expectedArgsCount] = this;
1420
+ } else {
1421
+ actionArgs[expectedArgsCount] = this.opts();
1422
+ }
1423
+ actionArgs.push(this);
1424
+ return fn.apply(this, actionArgs);
1425
+ };
1426
+ this._actionHandler = listener;
1427
+ return this;
1428
+ }
1429
+ /**
1430
+ * Factory routine to create a new unattached option.
1431
+ *
1432
+ * See .option() for creating an attached option, which uses this routine to
1433
+ * create the option. You can override createOption to return a custom option.
1434
+ *
1435
+ * @param {string} flags
1436
+ * @param {string} [description]
1437
+ * @return {Option} new option
1438
+ */
1439
+ createOption(flags, description) {
1440
+ return new Option2(flags, description);
1441
+ }
1442
+ /**
1443
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1444
+ *
1445
+ * @param {(Option | Argument)} target
1446
+ * @param {string} value
1447
+ * @param {*} previous
1448
+ * @param {string} invalidArgumentMessage
1449
+ * @private
1450
+ */
1451
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1452
+ try {
1453
+ return target.parseArg(value, previous);
1454
+ } catch (err) {
1455
+ if (err.code === "commander.invalidArgument") {
1456
+ const message = `${invalidArgumentMessage} ${err.message}`;
1457
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1458
+ }
1459
+ throw err;
1460
+ }
1461
+ }
1462
+ /**
1463
+ * Check for option flag conflicts.
1464
+ * Register option if no conflicts found, or throw on conflict.
1465
+ *
1466
+ * @param {Option} option
1467
+ * @private
1468
+ */
1469
+ _registerOption(option) {
1470
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1471
+ if (matchingOption) {
1472
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1473
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1474
+ - already used by option '${matchingOption.flags}'`);
1475
+ }
1476
+ this.options.push(option);
1477
+ }
1478
+ /**
1479
+ * Check for command name and alias conflicts with existing commands.
1480
+ * Register command if no conflicts found, or throw on conflict.
1481
+ *
1482
+ * @param {Command} command
1483
+ * @private
1484
+ */
1485
+ _registerCommand(command) {
1486
+ const knownBy = (cmd) => {
1487
+ return [cmd.name()].concat(cmd.aliases());
1488
+ };
1489
+ const alreadyUsed = knownBy(command).find(
1490
+ (name) => this._findCommand(name)
1491
+ );
1492
+ if (alreadyUsed) {
1493
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1494
+ const newCmd = knownBy(command).join("|");
1495
+ throw new Error(
1496
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1497
+ );
1498
+ }
1499
+ this.commands.push(command);
1500
+ }
1501
+ /**
1502
+ * Add an option.
1503
+ *
1504
+ * @param {Option} option
1505
+ * @return {Command} `this` command for chaining
1506
+ */
1507
+ addOption(option) {
1508
+ this._registerOption(option);
1509
+ const oname = option.name();
1510
+ const name = option.attributeName();
1511
+ if (option.negate) {
1512
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1513
+ if (!this._findOption(positiveLongFlag)) {
1514
+ this.setOptionValueWithSource(
1515
+ name,
1516
+ option.defaultValue === void 0 ? true : option.defaultValue,
1517
+ "default"
1518
+ );
1519
+ }
1520
+ } else if (option.defaultValue !== void 0) {
1521
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1522
+ }
1523
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1524
+ if (val == null && option.presetArg !== void 0) {
1525
+ val = option.presetArg;
1526
+ }
1527
+ const oldValue = this.getOptionValue(name);
1528
+ if (val !== null && option.parseArg) {
1529
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1530
+ } else if (val !== null && option.variadic) {
1531
+ val = option._concatValue(val, oldValue);
1532
+ }
1533
+ if (val == null) {
1534
+ if (option.negate) {
1535
+ val = false;
1536
+ } else if (option.isBoolean() || option.optional) {
1537
+ val = true;
1538
+ } else {
1539
+ val = "";
1540
+ }
1541
+ }
1542
+ this.setOptionValueWithSource(name, val, valueSource);
1543
+ };
1544
+ this.on("option:" + oname, (val) => {
1545
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1546
+ handleOptionValue(val, invalidValueMessage, "cli");
1547
+ });
1548
+ if (option.envVar) {
1549
+ this.on("optionEnv:" + oname, (val) => {
1550
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1551
+ handleOptionValue(val, invalidValueMessage, "env");
1552
+ });
1553
+ }
1554
+ return this;
1555
+ }
1556
+ /**
1557
+ * Internal implementation shared by .option() and .requiredOption()
1558
+ *
1559
+ * @return {Command} `this` command for chaining
1560
+ * @private
1561
+ */
1562
+ _optionEx(config, flags, description, fn, defaultValue) {
1563
+ if (typeof flags === "object" && flags instanceof Option2) {
1564
+ throw new Error(
1565
+ "To add an Option object use addOption() instead of option() or requiredOption()"
1566
+ );
1567
+ }
1568
+ const option = this.createOption(flags, description);
1569
+ option.makeOptionMandatory(!!config.mandatory);
1570
+ if (typeof fn === "function") {
1571
+ option.default(defaultValue).argParser(fn);
1572
+ } else if (fn instanceof RegExp) {
1573
+ const regex = fn;
1574
+ fn = (val, def) => {
1575
+ const m = regex.exec(val);
1576
+ return m ? m[0] : def;
1577
+ };
1578
+ option.default(defaultValue).argParser(fn);
1579
+ } else {
1580
+ option.default(fn);
1581
+ }
1582
+ return this.addOption(option);
1583
+ }
1584
+ /**
1585
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1586
+ *
1587
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1588
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1589
+ *
1590
+ * See the README for more details, and see also addOption() and requiredOption().
1591
+ *
1592
+ * @example
1593
+ * program
1594
+ * .option('-p, --pepper', 'add pepper')
1595
+ * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1596
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1597
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1598
+ *
1599
+ * @param {string} flags
1600
+ * @param {string} [description]
1601
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1602
+ * @param {*} [defaultValue]
1603
+ * @return {Command} `this` command for chaining
1604
+ */
1605
+ option(flags, description, parseArg, defaultValue) {
1606
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1607
+ }
1608
+ /**
1609
+ * Add a required option which must have a value after parsing. This usually means
1610
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1611
+ *
1612
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1613
+ *
1614
+ * @param {string} flags
1615
+ * @param {string} [description]
1616
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1617
+ * @param {*} [defaultValue]
1618
+ * @return {Command} `this` command for chaining
1619
+ */
1620
+ requiredOption(flags, description, parseArg, defaultValue) {
1621
+ return this._optionEx(
1622
+ { mandatory: true },
1623
+ flags,
1624
+ description,
1625
+ parseArg,
1626
+ defaultValue
1627
+ );
1628
+ }
1629
+ /**
1630
+ * Alter parsing of short flags with optional values.
1631
+ *
1632
+ * @example
1633
+ * // for `.option('-f,--flag [value]'):
1634
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1635
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1636
+ *
1637
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1638
+ * @return {Command} `this` command for chaining
1639
+ */
1640
+ combineFlagAndOptionalValue(combine = true) {
1641
+ this._combineFlagAndOptionalValue = !!combine;
1642
+ return this;
1643
+ }
1644
+ /**
1645
+ * Allow unknown options on the command line.
1646
+ *
1647
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1648
+ * @return {Command} `this` command for chaining
1649
+ */
1650
+ allowUnknownOption(allowUnknown = true) {
1651
+ this._allowUnknownOption = !!allowUnknown;
1652
+ return this;
1653
+ }
1654
+ /**
1655
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1656
+ *
1657
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1658
+ * @return {Command} `this` command for chaining
1659
+ */
1660
+ allowExcessArguments(allowExcess = true) {
1661
+ this._allowExcessArguments = !!allowExcess;
1662
+ return this;
1663
+ }
1664
+ /**
1665
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1666
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1667
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1668
+ *
1669
+ * @param {boolean} [positional]
1670
+ * @return {Command} `this` command for chaining
1671
+ */
1672
+ enablePositionalOptions(positional = true) {
1673
+ this._enablePositionalOptions = !!positional;
1674
+ return this;
1675
+ }
1676
+ /**
1677
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1678
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1679
+ * positional options to have been enabled on the program (parent commands).
1680
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1681
+ *
1682
+ * @param {boolean} [passThrough] for unknown options.
1683
+ * @return {Command} `this` command for chaining
1684
+ */
1685
+ passThroughOptions(passThrough = true) {
1686
+ this._passThroughOptions = !!passThrough;
1687
+ this._checkForBrokenPassThrough();
1688
+ return this;
1689
+ }
1690
+ /**
1691
+ * @private
1692
+ */
1693
+ _checkForBrokenPassThrough() {
1694
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1695
+ throw new Error(
1696
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
1697
+ );
1698
+ }
1699
+ }
1700
+ /**
1701
+ * Whether to store option values as properties on command object,
1702
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1703
+ *
1704
+ * @param {boolean} [storeAsProperties=true]
1705
+ * @return {Command} `this` command for chaining
1706
+ */
1707
+ storeOptionsAsProperties(storeAsProperties = true) {
1708
+ if (this.options.length) {
1709
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1710
+ }
1711
+ if (Object.keys(this._optionValues).length) {
1712
+ throw new Error(
1713
+ "call .storeOptionsAsProperties() before setting option values"
1714
+ );
1715
+ }
1716
+ this._storeOptionsAsProperties = !!storeAsProperties;
1717
+ return this;
1718
+ }
1719
+ /**
1720
+ * Retrieve option value.
1721
+ *
1722
+ * @param {string} key
1723
+ * @return {object} value
1724
+ */
1725
+ getOptionValue(key) {
1726
+ if (this._storeOptionsAsProperties) {
1727
+ return this[key];
1728
+ }
1729
+ return this._optionValues[key];
1730
+ }
1731
+ /**
1732
+ * Store option value.
1733
+ *
1734
+ * @param {string} key
1735
+ * @param {object} value
1736
+ * @return {Command} `this` command for chaining
1737
+ */
1738
+ setOptionValue(key, value) {
1739
+ return this.setOptionValueWithSource(key, value, void 0);
1740
+ }
1741
+ /**
1742
+ * Store option value and where the value came from.
1743
+ *
1744
+ * @param {string} key
1745
+ * @param {object} value
1746
+ * @param {string} source - expected values are default/config/env/cli/implied
1747
+ * @return {Command} `this` command for chaining
1748
+ */
1749
+ setOptionValueWithSource(key, value, source) {
1750
+ if (this._storeOptionsAsProperties) {
1751
+ this[key] = value;
1752
+ } else {
1753
+ this._optionValues[key] = value;
1754
+ }
1755
+ this._optionValueSources[key] = source;
1756
+ return this;
1757
+ }
1758
+ /**
1759
+ * Get source of option value.
1760
+ * Expected values are default | config | env | cli | implied
1761
+ *
1762
+ * @param {string} key
1763
+ * @return {string}
1764
+ */
1765
+ getOptionValueSource(key) {
1766
+ return this._optionValueSources[key];
1767
+ }
1768
+ /**
1769
+ * Get source of option value. See also .optsWithGlobals().
1770
+ * Expected values are default | config | env | cli | implied
1771
+ *
1772
+ * @param {string} key
1773
+ * @return {string}
1774
+ */
1775
+ getOptionValueSourceWithGlobals(key) {
1776
+ let source;
1777
+ this._getCommandAndAncestors().forEach((cmd) => {
1778
+ if (cmd.getOptionValueSource(key) !== void 0) {
1779
+ source = cmd.getOptionValueSource(key);
1780
+ }
1781
+ });
1782
+ return source;
1783
+ }
1784
+ /**
1785
+ * Get user arguments from implied or explicit arguments.
1786
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1787
+ *
1788
+ * @private
1789
+ */
1790
+ _prepareUserArgs(argv, parseOptions) {
1791
+ if (argv !== void 0 && !Array.isArray(argv)) {
1792
+ throw new Error("first parameter to parse must be array or undefined");
1793
+ }
1794
+ parseOptions = parseOptions || {};
1795
+ if (argv === void 0 && parseOptions.from === void 0) {
1796
+ if (process2.versions?.electron) {
1797
+ parseOptions.from = "electron";
1798
+ }
1799
+ const execArgv = process2.execArgv ?? [];
1800
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1801
+ parseOptions.from = "eval";
1802
+ }
1803
+ }
1804
+ if (argv === void 0) {
1805
+ argv = process2.argv;
1806
+ }
1807
+ this.rawArgs = argv.slice();
1808
+ let userArgs;
1809
+ switch (parseOptions.from) {
1810
+ case void 0:
1811
+ case "node":
1812
+ this._scriptPath = argv[1];
1813
+ userArgs = argv.slice(2);
1814
+ break;
1815
+ case "electron":
1816
+ if (process2.defaultApp) {
1817
+ this._scriptPath = argv[1];
1818
+ userArgs = argv.slice(2);
1819
+ } else {
1820
+ userArgs = argv.slice(1);
1821
+ }
1822
+ break;
1823
+ case "user":
1824
+ userArgs = argv.slice(0);
1825
+ break;
1826
+ case "eval":
1827
+ userArgs = argv.slice(1);
1828
+ break;
1829
+ default:
1830
+ throw new Error(
1831
+ `unexpected parse option { from: '${parseOptions.from}' }`
1832
+ );
1833
+ }
1834
+ if (!this._name && this._scriptPath)
1835
+ this.nameFromFilename(this._scriptPath);
1836
+ this._name = this._name || "program";
1837
+ return userArgs;
1838
+ }
1839
+ /**
1840
+ * Parse `argv`, setting options and invoking commands when defined.
1841
+ *
1842
+ * Use parseAsync instead of parse if any of your action handlers are async.
1843
+ *
1844
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1845
+ *
1846
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1847
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1848
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1849
+ * - `'user'`: just user arguments
1850
+ *
1851
+ * @example
1852
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1853
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1854
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1855
+ *
1856
+ * @param {string[]} [argv] - optional, defaults to process.argv
1857
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1858
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1859
+ * @return {Command} `this` command for chaining
1860
+ */
1861
+ parse(argv, parseOptions) {
1862
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1863
+ this._parseCommand([], userArgs);
1864
+ return this;
1865
+ }
1866
+ /**
1867
+ * Parse `argv`, setting options and invoking commands when defined.
1868
+ *
1869
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1870
+ *
1871
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1872
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1873
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1874
+ * - `'user'`: just user arguments
1875
+ *
1876
+ * @example
1877
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1878
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1879
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1880
+ *
1881
+ * @param {string[]} [argv]
1882
+ * @param {object} [parseOptions]
1883
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1884
+ * @return {Promise}
1885
+ */
1886
+ async parseAsync(argv, parseOptions) {
1887
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1888
+ await this._parseCommand([], userArgs);
1889
+ return this;
1890
+ }
1891
+ /**
1892
+ * Execute a sub-command executable.
1893
+ *
1894
+ * @private
1895
+ */
1896
+ _executeSubCommand(subcommand, args) {
1897
+ args = args.slice();
1898
+ let launchWithNode = false;
1899
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1900
+ function findFile(baseDir, baseName) {
1901
+ const localBin = path.resolve(baseDir, baseName);
1902
+ if (fs.existsSync(localBin)) return localBin;
1903
+ if (sourceExt.includes(path.extname(baseName))) return void 0;
1904
+ const foundExt = sourceExt.find(
1905
+ (ext) => fs.existsSync(`${localBin}${ext}`)
1906
+ );
1907
+ if (foundExt) return `${localBin}${foundExt}`;
1908
+ return void 0;
1909
+ }
1910
+ this._checkForMissingMandatoryOptions();
1911
+ this._checkForConflictingOptions();
1912
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1913
+ let executableDir = this._executableDir || "";
1914
+ if (this._scriptPath) {
1915
+ let resolvedScriptPath;
1916
+ try {
1917
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1918
+ } catch (err) {
1919
+ resolvedScriptPath = this._scriptPath;
1920
+ }
1921
+ executableDir = path.resolve(
1922
+ path.dirname(resolvedScriptPath),
1923
+ executableDir
1924
+ );
1925
+ }
1926
+ if (executableDir) {
1927
+ let localFile = findFile(executableDir, executableFile);
1928
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1929
+ const legacyName = path.basename(
1930
+ this._scriptPath,
1931
+ path.extname(this._scriptPath)
1932
+ );
1933
+ if (legacyName !== this._name) {
1934
+ localFile = findFile(
1935
+ executableDir,
1936
+ `${legacyName}-${subcommand._name}`
1937
+ );
1938
+ }
1939
+ }
1940
+ executableFile = localFile || executableFile;
1941
+ }
1942
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1943
+ let proc;
1944
+ if (process2.platform !== "win32") {
1945
+ if (launchWithNode) {
1946
+ args.unshift(executableFile);
1947
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1948
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1949
+ } else {
1950
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1951
+ }
1952
+ } else {
1953
+ args.unshift(executableFile);
1954
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1955
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1956
+ }
1957
+ if (!proc.killed) {
1958
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1959
+ signals.forEach((signal) => {
1960
+ process2.on(signal, () => {
1961
+ if (proc.killed === false && proc.exitCode === null) {
1962
+ proc.kill(signal);
1963
+ }
1964
+ });
1965
+ });
1966
+ }
1967
+ const exitCallback = this._exitCallback;
1968
+ proc.on("close", (code) => {
1969
+ code = code ?? 1;
1970
+ if (!exitCallback) {
1971
+ process2.exit(code);
1972
+ } else {
1973
+ exitCallback(
1974
+ new CommanderError2(
1975
+ code,
1976
+ "commander.executeSubCommandAsync",
1977
+ "(close)"
1978
+ )
1979
+ );
1980
+ }
1981
+ });
1982
+ proc.on("error", (err) => {
1983
+ if (err.code === "ENOENT") {
1984
+ const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
1985
+ const executableMissing = `'${executableFile}' does not exist
1986
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1987
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1988
+ - ${executableDirMessage}`;
1989
+ throw new Error(executableMissing);
1990
+ } else if (err.code === "EACCES") {
1991
+ throw new Error(`'${executableFile}' not executable`);
1992
+ }
1993
+ if (!exitCallback) {
1994
+ process2.exit(1);
1995
+ } else {
1996
+ const wrappedError = new CommanderError2(
1997
+ 1,
1998
+ "commander.executeSubCommandAsync",
1999
+ "(error)"
2000
+ );
2001
+ wrappedError.nestedError = err;
2002
+ exitCallback(wrappedError);
2003
+ }
2004
+ });
2005
+ this.runningCommand = proc;
2006
+ }
2007
+ /**
2008
+ * @private
2009
+ */
2010
+ _dispatchSubcommand(commandName, operands, unknown) {
2011
+ const subCommand = this._findCommand(commandName);
2012
+ if (!subCommand) this.help({ error: true });
2013
+ let promiseChain;
2014
+ promiseChain = this._chainOrCallSubCommandHook(
2015
+ promiseChain,
2016
+ subCommand,
2017
+ "preSubcommand"
2018
+ );
2019
+ promiseChain = this._chainOrCall(promiseChain, () => {
2020
+ if (subCommand._executableHandler) {
2021
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2022
+ } else {
2023
+ return subCommand._parseCommand(operands, unknown);
2024
+ }
2025
+ });
2026
+ return promiseChain;
2027
+ }
2028
+ /**
2029
+ * Invoke help directly if possible, or dispatch if necessary.
2030
+ * e.g. help foo
2031
+ *
2032
+ * @private
2033
+ */
2034
+ _dispatchHelpCommand(subcommandName) {
2035
+ if (!subcommandName) {
2036
+ this.help();
2037
+ }
2038
+ const subCommand = this._findCommand(subcommandName);
2039
+ if (subCommand && !subCommand._executableHandler) {
2040
+ subCommand.help();
2041
+ }
2042
+ return this._dispatchSubcommand(
2043
+ subcommandName,
2044
+ [],
2045
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2046
+ );
2047
+ }
2048
+ /**
2049
+ * Check this.args against expected this.registeredArguments.
2050
+ *
2051
+ * @private
2052
+ */
2053
+ _checkNumberOfArguments() {
2054
+ this.registeredArguments.forEach((arg, i) => {
2055
+ if (arg.required && this.args[i] == null) {
2056
+ this.missingArgument(arg.name());
2057
+ }
2058
+ });
2059
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2060
+ return;
2061
+ }
2062
+ if (this.args.length > this.registeredArguments.length) {
2063
+ this._excessArguments(this.args);
2064
+ }
2065
+ }
2066
+ /**
2067
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2068
+ *
2069
+ * @private
2070
+ */
2071
+ _processArguments() {
2072
+ const myParseArg = (argument, value, previous) => {
2073
+ let parsedValue = value;
2074
+ if (value !== null && argument.parseArg) {
2075
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2076
+ parsedValue = this._callParseArg(
2077
+ argument,
2078
+ value,
2079
+ previous,
2080
+ invalidValueMessage
2081
+ );
2082
+ }
2083
+ return parsedValue;
2084
+ };
2085
+ this._checkNumberOfArguments();
2086
+ const processedArgs = [];
2087
+ this.registeredArguments.forEach((declaredArg, index) => {
2088
+ let value = declaredArg.defaultValue;
2089
+ if (declaredArg.variadic) {
2090
+ if (index < this.args.length) {
2091
+ value = this.args.slice(index);
2092
+ if (declaredArg.parseArg) {
2093
+ value = value.reduce((processed, v) => {
2094
+ return myParseArg(declaredArg, v, processed);
2095
+ }, declaredArg.defaultValue);
2096
+ }
2097
+ } else if (value === void 0) {
2098
+ value = [];
2099
+ }
2100
+ } else if (index < this.args.length) {
2101
+ value = this.args[index];
2102
+ if (declaredArg.parseArg) {
2103
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2104
+ }
2105
+ }
2106
+ processedArgs[index] = value;
2107
+ });
2108
+ this.processedArgs = processedArgs;
2109
+ }
2110
+ /**
2111
+ * Once we have a promise we chain, but call synchronously until then.
2112
+ *
2113
+ * @param {(Promise|undefined)} promise
2114
+ * @param {Function} fn
2115
+ * @return {(Promise|undefined)}
2116
+ * @private
2117
+ */
2118
+ _chainOrCall(promise, fn) {
2119
+ if (promise && promise.then && typeof promise.then === "function") {
2120
+ return promise.then(() => fn());
2121
+ }
2122
+ return fn();
2123
+ }
2124
+ /**
2125
+ *
2126
+ * @param {(Promise|undefined)} promise
2127
+ * @param {string} event
2128
+ * @return {(Promise|undefined)}
2129
+ * @private
2130
+ */
2131
+ _chainOrCallHooks(promise, event) {
2132
+ let result = promise;
2133
+ const hooks = [];
2134
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2135
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2136
+ hooks.push({ hookedCommand, callback });
2137
+ });
2138
+ });
2139
+ if (event === "postAction") {
2140
+ hooks.reverse();
2141
+ }
2142
+ hooks.forEach((hookDetail) => {
2143
+ result = this._chainOrCall(result, () => {
2144
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2145
+ });
2146
+ });
2147
+ return result;
2148
+ }
2149
+ /**
2150
+ *
2151
+ * @param {(Promise|undefined)} promise
2152
+ * @param {Command} subCommand
2153
+ * @param {string} event
2154
+ * @return {(Promise|undefined)}
2155
+ * @private
2156
+ */
2157
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2158
+ let result = promise;
2159
+ if (this._lifeCycleHooks[event] !== void 0) {
2160
+ this._lifeCycleHooks[event].forEach((hook) => {
2161
+ result = this._chainOrCall(result, () => {
2162
+ return hook(this, subCommand);
2163
+ });
2164
+ });
2165
+ }
2166
+ return result;
2167
+ }
2168
+ /**
2169
+ * Process arguments in context of this command.
2170
+ * Returns action result, in case it is a promise.
2171
+ *
2172
+ * @private
2173
+ */
2174
+ _parseCommand(operands, unknown) {
2175
+ const parsed = this.parseOptions(unknown);
2176
+ this._parseOptionsEnv();
2177
+ this._parseOptionsImplied();
2178
+ operands = operands.concat(parsed.operands);
2179
+ unknown = parsed.unknown;
2180
+ this.args = operands.concat(unknown);
2181
+ if (operands && this._findCommand(operands[0])) {
2182
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2183
+ }
2184
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2185
+ return this._dispatchHelpCommand(operands[1]);
2186
+ }
2187
+ if (this._defaultCommandName) {
2188
+ this._outputHelpIfRequested(unknown);
2189
+ return this._dispatchSubcommand(
2190
+ this._defaultCommandName,
2191
+ operands,
2192
+ unknown
2193
+ );
2194
+ }
2195
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2196
+ this.help({ error: true });
2197
+ }
2198
+ this._outputHelpIfRequested(parsed.unknown);
2199
+ this._checkForMissingMandatoryOptions();
2200
+ this._checkForConflictingOptions();
2201
+ const checkForUnknownOptions = () => {
2202
+ if (parsed.unknown.length > 0) {
2203
+ this.unknownOption(parsed.unknown[0]);
2204
+ }
2205
+ };
2206
+ const commandEvent = `command:${this.name()}`;
2207
+ if (this._actionHandler) {
2208
+ checkForUnknownOptions();
2209
+ this._processArguments();
2210
+ let promiseChain;
2211
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2212
+ promiseChain = this._chainOrCall(
2213
+ promiseChain,
2214
+ () => this._actionHandler(this.processedArgs)
2215
+ );
2216
+ if (this.parent) {
2217
+ promiseChain = this._chainOrCall(promiseChain, () => {
2218
+ this.parent.emit(commandEvent, operands, unknown);
2219
+ });
2220
+ }
2221
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2222
+ return promiseChain;
2223
+ }
2224
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
2225
+ checkForUnknownOptions();
2226
+ this._processArguments();
2227
+ this.parent.emit(commandEvent, operands, unknown);
2228
+ } else if (operands.length) {
2229
+ if (this._findCommand("*")) {
2230
+ return this._dispatchSubcommand("*", operands, unknown);
2231
+ }
2232
+ if (this.listenerCount("command:*")) {
2233
+ this.emit("command:*", operands, unknown);
2234
+ } else if (this.commands.length) {
2235
+ this.unknownCommand();
2236
+ } else {
2237
+ checkForUnknownOptions();
2238
+ this._processArguments();
2239
+ }
2240
+ } else if (this.commands.length) {
2241
+ checkForUnknownOptions();
2242
+ this.help({ error: true });
2243
+ } else {
2244
+ checkForUnknownOptions();
2245
+ this._processArguments();
2246
+ }
2247
+ }
2248
+ /**
2249
+ * Find matching command.
2250
+ *
2251
+ * @private
2252
+ * @return {Command | undefined}
2253
+ */
2254
+ _findCommand(name) {
2255
+ if (!name) return void 0;
2256
+ return this.commands.find(
2257
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
2258
+ );
2259
+ }
2260
+ /**
2261
+ * Return an option matching `arg` if any.
2262
+ *
2263
+ * @param {string} arg
2264
+ * @return {Option}
2265
+ * @package
2266
+ */
2267
+ _findOption(arg) {
2268
+ return this.options.find((option) => option.is(arg));
2269
+ }
2270
+ /**
2271
+ * Display an error message if a mandatory option does not have a value.
2272
+ * Called after checking for help flags in leaf subcommand.
2273
+ *
2274
+ * @private
2275
+ */
2276
+ _checkForMissingMandatoryOptions() {
2277
+ this._getCommandAndAncestors().forEach((cmd) => {
2278
+ cmd.options.forEach((anOption) => {
2279
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2280
+ cmd.missingMandatoryOptionValue(anOption);
2281
+ }
2282
+ });
2283
+ });
2284
+ }
2285
+ /**
2286
+ * Display an error message if conflicting options are used together in this.
2287
+ *
2288
+ * @private
2289
+ */
2290
+ _checkForConflictingLocalOptions() {
2291
+ const definedNonDefaultOptions = this.options.filter((option) => {
2292
+ const optionKey = option.attributeName();
2293
+ if (this.getOptionValue(optionKey) === void 0) {
2294
+ return false;
2295
+ }
2296
+ return this.getOptionValueSource(optionKey) !== "default";
2297
+ });
2298
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2299
+ (option) => option.conflictsWith.length > 0
2300
+ );
2301
+ optionsWithConflicting.forEach((option) => {
2302
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2303
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2304
+ );
2305
+ if (conflictingAndDefined) {
2306
+ this._conflictingOption(option, conflictingAndDefined);
2307
+ }
2308
+ });
2309
+ }
2310
+ /**
2311
+ * Display an error message if conflicting options are used together.
2312
+ * Called after checking for help flags in leaf subcommand.
2313
+ *
2314
+ * @private
2315
+ */
2316
+ _checkForConflictingOptions() {
2317
+ this._getCommandAndAncestors().forEach((cmd) => {
2318
+ cmd._checkForConflictingLocalOptions();
2319
+ });
2320
+ }
2321
+ /**
2322
+ * Parse options from `argv` removing known options,
2323
+ * and return argv split into operands and unknown arguments.
2324
+ *
2325
+ * Examples:
2326
+ *
2327
+ * argv => operands, unknown
2328
+ * --known kkk op => [op], []
2329
+ * op --known kkk => [op], []
2330
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2331
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2332
+ *
2333
+ * @param {string[]} argv
2334
+ * @return {{operands: string[], unknown: string[]}}
2335
+ */
2336
+ parseOptions(argv) {
2337
+ const operands = [];
2338
+ const unknown = [];
2339
+ let dest = operands;
2340
+ const args = argv.slice();
2341
+ function maybeOption(arg) {
2342
+ return arg.length > 1 && arg[0] === "-";
2343
+ }
2344
+ let activeVariadicOption = null;
2345
+ while (args.length) {
2346
+ const arg = args.shift();
2347
+ if (arg === "--") {
2348
+ if (dest === unknown) dest.push(arg);
2349
+ dest.push(...args);
2350
+ break;
2351
+ }
2352
+ if (activeVariadicOption && !maybeOption(arg)) {
2353
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2354
+ continue;
2355
+ }
2356
+ activeVariadicOption = null;
2357
+ if (maybeOption(arg)) {
2358
+ const option = this._findOption(arg);
2359
+ if (option) {
2360
+ if (option.required) {
2361
+ const value = args.shift();
2362
+ if (value === void 0) this.optionMissingArgument(option);
2363
+ this.emit(`option:${option.name()}`, value);
2364
+ } else if (option.optional) {
2365
+ let value = null;
2366
+ if (args.length > 0 && !maybeOption(args[0])) {
2367
+ value = args.shift();
2368
+ }
2369
+ this.emit(`option:${option.name()}`, value);
2370
+ } else {
2371
+ this.emit(`option:${option.name()}`);
2372
+ }
2373
+ activeVariadicOption = option.variadic ? option : null;
2374
+ continue;
2375
+ }
2376
+ }
2377
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2378
+ const option = this._findOption(`-${arg[1]}`);
2379
+ if (option) {
2380
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2381
+ this.emit(`option:${option.name()}`, arg.slice(2));
2382
+ } else {
2383
+ this.emit(`option:${option.name()}`);
2384
+ args.unshift(`-${arg.slice(2)}`);
2385
+ }
2386
+ continue;
2387
+ }
2388
+ }
2389
+ if (/^--[^=]+=/.test(arg)) {
2390
+ const index = arg.indexOf("=");
2391
+ const option = this._findOption(arg.slice(0, index));
2392
+ if (option && (option.required || option.optional)) {
2393
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2394
+ continue;
2395
+ }
2396
+ }
2397
+ if (maybeOption(arg)) {
2398
+ dest = unknown;
2399
+ }
2400
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2401
+ if (this._findCommand(arg)) {
2402
+ operands.push(arg);
2403
+ if (args.length > 0) unknown.push(...args);
2404
+ break;
2405
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2406
+ operands.push(arg);
2407
+ if (args.length > 0) operands.push(...args);
2408
+ break;
2409
+ } else if (this._defaultCommandName) {
2410
+ unknown.push(arg);
2411
+ if (args.length > 0) unknown.push(...args);
2412
+ break;
2413
+ }
2414
+ }
2415
+ if (this._passThroughOptions) {
2416
+ dest.push(arg);
2417
+ if (args.length > 0) dest.push(...args);
2418
+ break;
2419
+ }
2420
+ dest.push(arg);
2421
+ }
2422
+ return { operands, unknown };
2423
+ }
2424
+ /**
2425
+ * Return an object containing local option values as key-value pairs.
2426
+ *
2427
+ * @return {object}
2428
+ */
2429
+ opts() {
2430
+ if (this._storeOptionsAsProperties) {
2431
+ const result = {};
2432
+ const len = this.options.length;
2433
+ for (let i = 0; i < len; i++) {
2434
+ const key = this.options[i].attributeName();
2435
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2436
+ }
2437
+ return result;
2438
+ }
2439
+ return this._optionValues;
2440
+ }
2441
+ /**
2442
+ * Return an object containing merged local and global option values as key-value pairs.
2443
+ *
2444
+ * @return {object}
2445
+ */
2446
+ optsWithGlobals() {
2447
+ return this._getCommandAndAncestors().reduce(
2448
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2449
+ {}
2450
+ );
2451
+ }
2452
+ /**
2453
+ * Display error message and exit (or call exitOverride).
2454
+ *
2455
+ * @param {string} message
2456
+ * @param {object} [errorOptions]
2457
+ * @param {string} [errorOptions.code] - an id string representing the error
2458
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2459
+ */
2460
+ error(message, errorOptions) {
2461
+ this._outputConfiguration.outputError(
2462
+ `${message}
2463
+ `,
2464
+ this._outputConfiguration.writeErr
2465
+ );
2466
+ if (typeof this._showHelpAfterError === "string") {
2467
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2468
+ `);
2469
+ } else if (this._showHelpAfterError) {
2470
+ this._outputConfiguration.writeErr("\n");
2471
+ this.outputHelp({ error: true });
2472
+ }
2473
+ const config = errorOptions || {};
2474
+ const exitCode = config.exitCode || 1;
2475
+ const code = config.code || "commander.error";
2476
+ this._exit(exitCode, code, message);
2477
+ }
2478
+ /**
2479
+ * Apply any option related environment variables, if option does
2480
+ * not have a value from cli or client code.
2481
+ *
2482
+ * @private
2483
+ */
2484
+ _parseOptionsEnv() {
2485
+ this.options.forEach((option) => {
2486
+ if (option.envVar && option.envVar in process2.env) {
2487
+ const optionKey = option.attributeName();
2488
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
2489
+ this.getOptionValueSource(optionKey)
2490
+ )) {
2491
+ if (option.required || option.optional) {
2492
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2493
+ } else {
2494
+ this.emit(`optionEnv:${option.name()}`);
2495
+ }
2496
+ }
2497
+ }
2498
+ });
2499
+ }
2500
+ /**
2501
+ * Apply any implied option values, if option is undefined or default value.
2502
+ *
2503
+ * @private
2504
+ */
2505
+ _parseOptionsImplied() {
2506
+ const dualHelper = new DualOptions(this.options);
2507
+ const hasCustomOptionValue = (optionKey) => {
2508
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2509
+ };
2510
+ this.options.filter(
2511
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
2512
+ this.getOptionValue(option.attributeName()),
2513
+ option
2514
+ )
2515
+ ).forEach((option) => {
2516
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2517
+ this.setOptionValueWithSource(
2518
+ impliedKey,
2519
+ option.implied[impliedKey],
2520
+ "implied"
2521
+ );
2522
+ });
2523
+ });
2524
+ }
2525
+ /**
2526
+ * Argument `name` is missing.
2527
+ *
2528
+ * @param {string} name
2529
+ * @private
2530
+ */
2531
+ missingArgument(name) {
2532
+ const message = `error: missing required argument '${name}'`;
2533
+ this.error(message, { code: "commander.missingArgument" });
2534
+ }
2535
+ /**
2536
+ * `Option` is missing an argument.
2537
+ *
2538
+ * @param {Option} option
2539
+ * @private
2540
+ */
2541
+ optionMissingArgument(option) {
2542
+ const message = `error: option '${option.flags}' argument missing`;
2543
+ this.error(message, { code: "commander.optionMissingArgument" });
2544
+ }
2545
+ /**
2546
+ * `Option` does not have a value, and is a mandatory option.
2547
+ *
2548
+ * @param {Option} option
2549
+ * @private
2550
+ */
2551
+ missingMandatoryOptionValue(option) {
2552
+ const message = `error: required option '${option.flags}' not specified`;
2553
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2554
+ }
2555
+ /**
2556
+ * `Option` conflicts with another option.
2557
+ *
2558
+ * @param {Option} option
2559
+ * @param {Option} conflictingOption
2560
+ * @private
2561
+ */
2562
+ _conflictingOption(option, conflictingOption) {
2563
+ const findBestOptionFromValue = (option2) => {
2564
+ const optionKey = option2.attributeName();
2565
+ const optionValue = this.getOptionValue(optionKey);
2566
+ const negativeOption = this.options.find(
2567
+ (target) => target.negate && optionKey === target.attributeName()
2568
+ );
2569
+ const positiveOption = this.options.find(
2570
+ (target) => !target.negate && optionKey === target.attributeName()
2571
+ );
2572
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2573
+ return negativeOption;
2574
+ }
2575
+ return positiveOption || option2;
2576
+ };
2577
+ const getErrorMessage = (option2) => {
2578
+ const bestOption = findBestOptionFromValue(option2);
2579
+ const optionKey = bestOption.attributeName();
2580
+ const source = this.getOptionValueSource(optionKey);
2581
+ if (source === "env") {
2582
+ return `environment variable '${bestOption.envVar}'`;
2583
+ }
2584
+ return `option '${bestOption.flags}'`;
2585
+ };
2586
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2587
+ this.error(message, { code: "commander.conflictingOption" });
2588
+ }
2589
+ /**
2590
+ * Unknown option `flag`.
2591
+ *
2592
+ * @param {string} flag
2593
+ * @private
2594
+ */
2595
+ unknownOption(flag) {
2596
+ if (this._allowUnknownOption) return;
2597
+ let suggestion = "";
2598
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2599
+ let candidateFlags = [];
2600
+ let command = this;
2601
+ do {
2602
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2603
+ candidateFlags = candidateFlags.concat(moreFlags);
2604
+ command = command.parent;
2605
+ } while (command && !command._enablePositionalOptions);
2606
+ suggestion = suggestSimilar(flag, candidateFlags);
2607
+ }
2608
+ const message = `error: unknown option '${flag}'${suggestion}`;
2609
+ this.error(message, { code: "commander.unknownOption" });
2610
+ }
2611
+ /**
2612
+ * Excess arguments, more than expected.
2613
+ *
2614
+ * @param {string[]} receivedArgs
2615
+ * @private
2616
+ */
2617
+ _excessArguments(receivedArgs) {
2618
+ if (this._allowExcessArguments) return;
2619
+ const expected = this.registeredArguments.length;
2620
+ const s = expected === 1 ? "" : "s";
2621
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2622
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2623
+ this.error(message, { code: "commander.excessArguments" });
2624
+ }
2625
+ /**
2626
+ * Unknown command.
2627
+ *
2628
+ * @private
2629
+ */
2630
+ unknownCommand() {
2631
+ const unknownName = this.args[0];
2632
+ let suggestion = "";
2633
+ if (this._showSuggestionAfterError) {
2634
+ const candidateNames = [];
2635
+ this.createHelp().visibleCommands(this).forEach((command) => {
2636
+ candidateNames.push(command.name());
2637
+ if (command.alias()) candidateNames.push(command.alias());
2638
+ });
2639
+ suggestion = suggestSimilar(unknownName, candidateNames);
2640
+ }
2641
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2642
+ this.error(message, { code: "commander.unknownCommand" });
2643
+ }
2644
+ /**
2645
+ * Get or set the program version.
2646
+ *
2647
+ * This method auto-registers the "-V, --version" option which will print the version number.
2648
+ *
2649
+ * You can optionally supply the flags and description to override the defaults.
2650
+ *
2651
+ * @param {string} [str]
2652
+ * @param {string} [flags]
2653
+ * @param {string} [description]
2654
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2655
+ */
2656
+ version(str, flags, description) {
2657
+ if (str === void 0) return this._version;
2658
+ this._version = str;
2659
+ flags = flags || "-V, --version";
2660
+ description = description || "output the version number";
2661
+ const versionOption = this.createOption(flags, description);
2662
+ this._versionOptionName = versionOption.attributeName();
2663
+ this._registerOption(versionOption);
2664
+ this.on("option:" + versionOption.name(), () => {
2665
+ this._outputConfiguration.writeOut(`${str}
2666
+ `);
2667
+ this._exit(0, "commander.version", str);
2668
+ });
2669
+ return this;
2670
+ }
2671
+ /**
2672
+ * Set the description.
2673
+ *
2674
+ * @param {string} [str]
2675
+ * @param {object} [argsDescription]
2676
+ * @return {(string|Command)}
2677
+ */
2678
+ description(str, argsDescription) {
2679
+ if (str === void 0 && argsDescription === void 0)
2680
+ return this._description;
2681
+ this._description = str;
2682
+ if (argsDescription) {
2683
+ this._argsDescription = argsDescription;
2684
+ }
2685
+ return this;
2686
+ }
2687
+ /**
2688
+ * Set the summary. Used when listed as subcommand of parent.
2689
+ *
2690
+ * @param {string} [str]
2691
+ * @return {(string|Command)}
2692
+ */
2693
+ summary(str) {
2694
+ if (str === void 0) return this._summary;
2695
+ this._summary = str;
2696
+ return this;
2697
+ }
2698
+ /**
2699
+ * Set an alias for the command.
2700
+ *
2701
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2702
+ *
2703
+ * @param {string} [alias]
2704
+ * @return {(string|Command)}
2705
+ */
2706
+ alias(alias) {
2707
+ if (alias === void 0) return this._aliases[0];
2708
+ let command = this;
2709
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2710
+ command = this.commands[this.commands.length - 1];
2711
+ }
2712
+ if (alias === command._name)
2713
+ throw new Error("Command alias can't be the same as its name");
2714
+ const matchingCommand = this.parent?._findCommand(alias);
2715
+ if (matchingCommand) {
2716
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2717
+ throw new Error(
2718
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
2719
+ );
2720
+ }
2721
+ command._aliases.push(alias);
2722
+ return this;
2723
+ }
2724
+ /**
2725
+ * Set aliases for the command.
2726
+ *
2727
+ * Only the first alias is shown in the auto-generated help.
2728
+ *
2729
+ * @param {string[]} [aliases]
2730
+ * @return {(string[]|Command)}
2731
+ */
2732
+ aliases(aliases) {
2733
+ if (aliases === void 0) return this._aliases;
2734
+ aliases.forEach((alias) => this.alias(alias));
2735
+ return this;
2736
+ }
2737
+ /**
2738
+ * Set / get the command usage `str`.
2739
+ *
2740
+ * @param {string} [str]
2741
+ * @return {(string|Command)}
2742
+ */
2743
+ usage(str) {
2744
+ if (str === void 0) {
2745
+ if (this._usage) return this._usage;
2746
+ const args = this.registeredArguments.map((arg) => {
2747
+ return humanReadableArgName(arg);
2748
+ });
2749
+ return [].concat(
2750
+ this.options.length || this._helpOption !== null ? "[options]" : [],
2751
+ this.commands.length ? "[command]" : [],
2752
+ this.registeredArguments.length ? args : []
2753
+ ).join(" ");
2754
+ }
2755
+ this._usage = str;
2756
+ return this;
2757
+ }
2758
+ /**
2759
+ * Get or set the name of the command.
2760
+ *
2761
+ * @param {string} [str]
2762
+ * @return {(string|Command)}
2763
+ */
2764
+ name(str) {
2765
+ if (str === void 0) return this._name;
2766
+ this._name = str;
2767
+ return this;
2768
+ }
2769
+ /**
2770
+ * Set the name of the command from script filename, such as process.argv[1],
2771
+ * or require.main.filename, or __filename.
2772
+ *
2773
+ * (Used internally and public although not documented in README.)
2774
+ *
2775
+ * @example
2776
+ * program.nameFromFilename(require.main.filename);
2777
+ *
2778
+ * @param {string} filename
2779
+ * @return {Command}
2780
+ */
2781
+ nameFromFilename(filename) {
2782
+ this._name = path.basename(filename, path.extname(filename));
2783
+ return this;
2784
+ }
2785
+ /**
2786
+ * Get or set the directory for searching for executable subcommands of this command.
2787
+ *
2788
+ * @example
2789
+ * program.executableDir(__dirname);
2790
+ * // or
2791
+ * program.executableDir('subcommands');
2792
+ *
2793
+ * @param {string} [path]
2794
+ * @return {(string|null|Command)}
2795
+ */
2796
+ executableDir(path2) {
2797
+ if (path2 === void 0) return this._executableDir;
2798
+ this._executableDir = path2;
2799
+ return this;
2800
+ }
2801
+ /**
2802
+ * Return program help documentation.
2803
+ *
2804
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2805
+ * @return {string}
2806
+ */
2807
+ helpInformation(contextOptions) {
2808
+ const helper = this.createHelp();
2809
+ if (helper.helpWidth === void 0) {
2810
+ helper.helpWidth = contextOptions && contextOptions.error ? this._outputConfiguration.getErrHelpWidth() : this._outputConfiguration.getOutHelpWidth();
2811
+ }
2812
+ return helper.formatHelp(this, helper);
2813
+ }
2814
+ /**
2815
+ * @private
2816
+ */
2817
+ _getHelpContext(contextOptions) {
2818
+ contextOptions = contextOptions || {};
2819
+ const context = { error: !!contextOptions.error };
2820
+ let write;
2821
+ if (context.error) {
2822
+ write = (arg) => this._outputConfiguration.writeErr(arg);
2823
+ } else {
2824
+ write = (arg) => this._outputConfiguration.writeOut(arg);
2825
+ }
2826
+ context.write = contextOptions.write || write;
2827
+ context.command = this;
2828
+ return context;
2829
+ }
2830
+ /**
2831
+ * Output help information for this command.
2832
+ *
2833
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2834
+ *
2835
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2836
+ */
2837
+ outputHelp(contextOptions) {
2838
+ let deprecatedCallback;
2839
+ if (typeof contextOptions === "function") {
2840
+ deprecatedCallback = contextOptions;
2841
+ contextOptions = void 0;
2842
+ }
2843
+ const context = this._getHelpContext(contextOptions);
2844
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", context));
2845
+ this.emit("beforeHelp", context);
2846
+ let helpInformation = this.helpInformation(context);
2847
+ if (deprecatedCallback) {
2848
+ helpInformation = deprecatedCallback(helpInformation);
2849
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
2850
+ throw new Error("outputHelp callback must return a string or a Buffer");
2851
+ }
2852
+ }
2853
+ context.write(helpInformation);
2854
+ if (this._getHelpOption()?.long) {
2855
+ this.emit(this._getHelpOption().long);
2856
+ }
2857
+ this.emit("afterHelp", context);
2858
+ this._getCommandAndAncestors().forEach(
2859
+ (command) => command.emit("afterAllHelp", context)
2860
+ );
2861
+ }
2862
+ /**
2863
+ * You can pass in flags and a description to customise the built-in help option.
2864
+ * Pass in false to disable the built-in help option.
2865
+ *
2866
+ * @example
2867
+ * program.helpOption('-?, --help' 'show help'); // customise
2868
+ * program.helpOption(false); // disable
2869
+ *
2870
+ * @param {(string | boolean)} flags
2871
+ * @param {string} [description]
2872
+ * @return {Command} `this` command for chaining
2873
+ */
2874
+ helpOption(flags, description) {
2875
+ if (typeof flags === "boolean") {
2876
+ if (flags) {
2877
+ this._helpOption = this._helpOption ?? void 0;
2878
+ } else {
2879
+ this._helpOption = null;
2880
+ }
2881
+ return this;
2882
+ }
2883
+ flags = flags ?? "-h, --help";
2884
+ description = description ?? "display help for command";
2885
+ this._helpOption = this.createOption(flags, description);
2886
+ return this;
2887
+ }
2888
+ /**
2889
+ * Lazy create help option.
2890
+ * Returns null if has been disabled with .helpOption(false).
2891
+ *
2892
+ * @returns {(Option | null)} the help option
2893
+ * @package
2894
+ */
2895
+ _getHelpOption() {
2896
+ if (this._helpOption === void 0) {
2897
+ this.helpOption(void 0, void 0);
2898
+ }
2899
+ return this._helpOption;
2900
+ }
2901
+ /**
2902
+ * Supply your own option to use for the built-in help option.
2903
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2904
+ *
2905
+ * @param {Option} option
2906
+ * @return {Command} `this` command for chaining
2907
+ */
2908
+ addHelpOption(option) {
2909
+ this._helpOption = option;
2910
+ return this;
2911
+ }
2912
+ /**
2913
+ * Output help information and exit.
2914
+ *
2915
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2916
+ *
2917
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2918
+ */
2919
+ help(contextOptions) {
2920
+ this.outputHelp(contextOptions);
2921
+ let exitCode = process2.exitCode || 0;
2922
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2923
+ exitCode = 1;
2924
+ }
2925
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2926
+ }
2927
+ /**
2928
+ * Add additional text to be displayed with the built-in help.
2929
+ *
2930
+ * Position is 'before' or 'after' to affect just this command,
2931
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2932
+ *
2933
+ * @param {string} position - before or after built-in help
2934
+ * @param {(string | Function)} text - string to add, or a function returning a string
2935
+ * @return {Command} `this` command for chaining
2936
+ */
2937
+ addHelpText(position, text) {
2938
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2939
+ if (!allowedValues.includes(position)) {
2940
+ throw new Error(`Unexpected value for position to addHelpText.
2941
+ Expecting one of '${allowedValues.join("', '")}'`);
2942
+ }
2943
+ const helpEvent = `${position}Help`;
2944
+ this.on(helpEvent, (context) => {
2945
+ let helpStr;
2946
+ if (typeof text === "function") {
2947
+ helpStr = text({ error: context.error, command: context.command });
2948
+ } else {
2949
+ helpStr = text;
2950
+ }
2951
+ if (helpStr) {
2952
+ context.write(`${helpStr}
2953
+ `);
2954
+ }
2955
+ });
2956
+ return this;
2957
+ }
2958
+ /**
2959
+ * Output help information if help flags specified
2960
+ *
2961
+ * @param {Array} args - array of options to search for help flags
2962
+ * @private
2963
+ */
2964
+ _outputHelpIfRequested(args) {
2965
+ const helpOption = this._getHelpOption();
2966
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2967
+ if (helpRequested) {
2968
+ this.outputHelp();
2969
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2970
+ }
2971
+ }
2972
+ };
2973
+ function incrementNodeInspectorPort(args) {
2974
+ return args.map((arg) => {
2975
+ if (!arg.startsWith("--inspect")) {
2976
+ return arg;
2977
+ }
2978
+ let debugOption;
2979
+ let debugHost = "127.0.0.1";
2980
+ let debugPort = "9229";
2981
+ let match;
2982
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2983
+ debugOption = match[1];
2984
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2985
+ debugOption = match[1];
2986
+ if (/^\d+$/.test(match[3])) {
2987
+ debugPort = match[3];
2988
+ } else {
2989
+ debugHost = match[3];
2990
+ }
2991
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2992
+ debugOption = match[1];
2993
+ debugHost = match[3];
2994
+ debugPort = match[4];
2995
+ }
2996
+ if (debugOption && debugPort !== "0") {
2997
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2998
+ }
2999
+ return arg;
3000
+ });
3001
+ }
3002
+ exports.Command = Command2;
3003
+ }
3004
+ });
3005
+
3006
+ // ../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/index.js
3007
+ var require_commander = __commonJS({
3008
+ "../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/index.js"(exports) {
3009
+ var { Argument: Argument2 } = require_argument();
3010
+ var { Command: Command2 } = require_command();
3011
+ var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
3012
+ var { Help: Help2 } = require_help();
3013
+ var { Option: Option2 } = require_option();
3014
+ exports.program = new Command2();
3015
+ exports.createCommand = (name) => new Command2(name);
3016
+ exports.createOption = (flags, description) => new Option2(flags, description);
3017
+ exports.createArgument = (name, description) => new Argument2(name, description);
3018
+ exports.Command = Command2;
3019
+ exports.Option = Option2;
3020
+ exports.Argument = Argument2;
3021
+ exports.Help = Help2;
3022
+ exports.CommanderError = CommanderError2;
3023
+ exports.InvalidArgumentError = InvalidArgumentError2;
3024
+ exports.InvalidOptionArgumentError = InvalidArgumentError2;
3025
+ }
3026
+ });
3027
+
3028
+ // ../../node_modules/.pnpm/commander@12.1.0/node_modules/commander/esm.mjs
3029
+ var import_index = __toESM(require_commander(), 1);
3030
+ var {
3031
+ program,
3032
+ createCommand,
3033
+ createArgument,
3034
+ createOption,
3035
+ CommanderError,
3036
+ InvalidArgumentError,
3037
+ InvalidOptionArgumentError,
3038
+ // deprecated old name
3039
+ Command,
3040
+ Argument,
3041
+ Option,
3042
+ Help
3043
+ } = import_index.default;
3044
+
3045
+ // ../../node_modules/.pnpm/@antasphere+cli-core@0.1.0/node_modules/@antasphere/cli-core/dist/config.js
3046
+ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3047
+ import { dirname, join } from "node:path";
3048
+ var HUB_TOOL = "hub";
3049
+ var TOOL_RE = /^[a-z][a-z0-9-]*$/;
3050
+ function assertToolNamespace(tool) {
3051
+ if (!TOOL_RE.test(tool)) {
3052
+ throw new Error(`Invalid tool namespace "${tool}" \u2014 lowercase slugs only ([a-z][a-z0-9-]*).`);
3053
+ }
3054
+ }
3055
+ function configPath(env, tool) {
3056
+ assertToolNamespace(tool);
3057
+ const base = env.XDG_CONFIG_HOME || (env.HOME ? join(env.HOME, ".config") : null);
3058
+ if (!base)
3059
+ return null;
3060
+ const home = join(base, "antasphere");
3061
+ return tool === HUB_TOOL ? join(home, "config.json") : join(home, "tools", `${tool}.json`);
3062
+ }
3063
+ var EMPTY = { profiles: {} };
3064
+ function parseConfig(raw) {
3065
+ try {
3066
+ const parsed = JSON.parse(raw);
3067
+ const profiles = parsed.profiles && typeof parsed.profiles === "object" ? parsed.profiles : {};
3068
+ return {
3069
+ ...typeof parsed.activeProfile === "string" ? { activeProfile: parsed.activeProfile } : {},
3070
+ profiles
3071
+ };
3072
+ } catch {
3073
+ return { ...EMPTY, profiles: {} };
3074
+ }
3075
+ }
3076
+ function loadConfig(env, tool) {
3077
+ const path = configPath(env, tool);
3078
+ if (!path || !existsSync(path))
3079
+ return { ...EMPTY, profiles: {} };
3080
+ try {
3081
+ return parseConfig(readFileSync(path, "utf8"));
3082
+ } catch {
3083
+ return { ...EMPTY, profiles: {} };
3084
+ }
3085
+ }
3086
+ function saveConfig(env, tool, config) {
3087
+ const path = configPath(env, tool);
3088
+ if (!path) {
3089
+ throw new Error("Cannot locate a config directory \u2014 set HOME or XDG_CONFIG_HOME, or pass --api-key/--api-url explicitly.");
3090
+ }
3091
+ const dir = dirname(path);
3092
+ mkdirSync(dir, { recursive: true, mode: 448 });
3093
+ chmodSync(dir, 448);
3094
+ const home = dirname(configPath(env, HUB_TOOL));
3095
+ if (dir !== home)
3096
+ chmodSync(home, 448);
3097
+ writeFileSync(path, `${JSON.stringify(config, null, 2)}
3098
+ `, { mode: 384 });
3099
+ chmodSync(path, 384);
3100
+ return path;
3101
+ }
3102
+ function clearConfig(env, tool) {
3103
+ const path = configPath(env, tool);
3104
+ if (path && existsSync(path))
3105
+ rmSync(path);
3106
+ }
3107
+ function redactKey(key) {
3108
+ if (key.length <= 16)
3109
+ return "****";
3110
+ return `${key.slice(0, 13)}\u2026${key.slice(-4)}`;
3111
+ }
3112
+
3113
+ // ../../node_modules/.pnpm/@antasphere+cli-core@0.1.0/node_modules/@antasphere/cli-core/dist/io.js
3114
+ function printJson(io, value) {
3115
+ io.out.write(`${JSON.stringify(value, null, 2)}
3116
+ `);
3117
+ }
3118
+
3119
+ // ../../node_modules/.pnpm/@antasphere+cli-core@0.1.0/node_modules/@antasphere/cli-core/dist/resolve.js
3120
+ var CliUsageError = class extends Error {
3121
+ };
3122
+ function resolveProfile(config, requested, opts = {}) {
3123
+ if (requested) {
3124
+ const profile2 = config.profiles[requested];
3125
+ if (!profile2) {
3126
+ throw new CliUsageError(`Unknown profile "${requested}"${opts.unknownHint ? ` \u2014 ${opts.unknownHint}` : ""}`);
3127
+ }
3128
+ return { name: requested, profile: profile2 };
3129
+ }
3130
+ const name = config.activeProfile;
3131
+ const profile = name ? config.profiles[name] : void 0;
3132
+ return { name: profile ? name : void 0, profile };
3133
+ }
3134
+ function resolveBaseUrl(opts) {
3135
+ const raw = opts.flag ?? opts.env[opts.envVar] ?? opts.profile?.baseUrl ?? opts.defaultUrl;
3136
+ if (!raw) {
3137
+ throw new CliUsageError(opts.missingMessage ?? `No instance configured \u2014 pass --api-url <url> or set ${opts.envVar}.`);
3138
+ }
3139
+ return raw.replace(/\/+$/, "");
3140
+ }
3141
+ function resolveApiKey(opts) {
3142
+ return opts.flag ?? opts.env[opts.envVar] ?? opts.profile?.apiKey;
3143
+ }
3144
+
3145
+ // ../../node_modules/.pnpm/@antasphere+cli-core@0.1.0/node_modules/@antasphere/cli-core/dist/auth.js
3146
+ var CliAuthError = class extends Error {
3147
+ status;
3148
+ code;
3149
+ details;
3150
+ constructor(status, code, message, details) {
3151
+ super(message);
3152
+ this.status = status;
3153
+ this.code = code;
3154
+ this.details = details;
3155
+ this.name = "CliAuthError";
3156
+ }
3157
+ };
3158
+ var CliAuthClient = class {
3159
+ baseUrl;
3160
+ fetchImpl;
3161
+ constructor(options) {
3162
+ this.baseUrl = options.baseUrl.replace(/\/+$/, "");
3163
+ this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
3164
+ }
3165
+ /** Public: request a sign-in code by email. Generic success — no enumeration. */
3166
+ request(body) {
3167
+ return this.call("POST", "/cli/auth/request", body);
3168
+ }
3169
+ /** Public: verify the code and mint an API key (returned once, like every mint). */
3170
+ complete(body) {
3171
+ return this.call("POST", "/cli/auth/complete", body);
3172
+ }
3173
+ /** CLI logout: revoke the PRESENTING API key (self-revocation). */
3174
+ revoke(apiKey) {
3175
+ return this.call("DELETE", "/cli/auth/key", void 0, apiKey);
3176
+ }
3177
+ /** Mirrors the platform SDK's parse: `{ error: { code, message, details } }` envelopes. */
3178
+ async call(method, path, body, apiKey) {
3179
+ const headers = {};
3180
+ if (apiKey)
3181
+ headers["authorization"] = `Bearer ${apiKey}`;
3182
+ if (body !== void 0)
3183
+ headers["content-type"] = "application/json";
3184
+ const res = await this.fetchImpl(`${this.baseUrl}/api/v1${path}`, {
3185
+ method,
3186
+ headers,
3187
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
3188
+ });
3189
+ if (res.status === 204)
3190
+ return void 0;
3191
+ const json = await res.json().catch(() => null);
3192
+ if (!res.ok) {
3193
+ const errBody = json ?? {};
3194
+ throw new CliAuthError(res.status, errBody.error?.code ?? "unknown_error", errBody.error?.message ?? `Request failed with ${res.status}`, errBody.error?.details);
3195
+ }
3196
+ return json;
3197
+ }
3198
+ };
3199
+
3200
+ // ../../node_modules/.pnpm/@antasphere+cli-core@0.1.0/node_modules/@antasphere/cli-core/dist/migrate.js
3201
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
3202
+ import { join as join2 } from "node:path";
3203
+ function migrateLegacyConfig(env, spec) {
3204
+ assertToolNamespace(spec.tool);
3205
+ assertToolNamespace(spec.legacyDir);
3206
+ const to = configPath(env, spec.tool);
3207
+ if (!to)
3208
+ return { migrated: false };
3209
+ const current = loadConfig(env, spec.tool);
3210
+ if (Object.keys(current.profiles).length > 0)
3211
+ return { migrated: false };
3212
+ const base = env.XDG_CONFIG_HOME || (env.HOME ? join2(env.HOME, ".config") : null);
3213
+ if (!base)
3214
+ return { migrated: false };
3215
+ const from = join2(base, spec.legacyDir, "config.json");
3216
+ if (!existsSync2(from))
3217
+ return { migrated: false };
3218
+ let raw;
3219
+ try {
3220
+ raw = readFileSync2(from, "utf8");
3221
+ } catch {
3222
+ return { migrated: false };
3223
+ }
3224
+ const legacy = parseConfig(raw);
3225
+ if (Object.keys(legacy.profiles).length === 0)
3226
+ return { migrated: false };
3227
+ saveConfig(env, spec.tool, legacy);
3228
+ return { migrated: true, from, to };
3229
+ }
3230
+
3231
+ // ../sdk/dist/index.js
3232
+ var PlatformApiError = class extends Error {
3233
+ status;
3234
+ code;
3235
+ details;
3236
+ constructor(status, code, message, details) {
3237
+ super(message);
3238
+ this.status = status;
3239
+ this.code = code;
3240
+ this.details = details;
3241
+ this.name = "PlatformApiError";
3242
+ }
3243
+ };
3244
+ function idempotencyHeader(opts) {
3245
+ return opts.idempotencyKey ? { "idempotency-key": opts.idempotencyKey } : void 0;
3246
+ }
3247
+ var PlatformClient = class {
3248
+ baseUrl;
3249
+ apiKey;
3250
+ workspaceId;
3251
+ fetchImpl;
3252
+ constructor(options = {}) {
3253
+ this.baseUrl = options.baseUrl?.replace(/\/$/, "") ?? "";
3254
+ this.apiKey = options.apiKey;
3255
+ this.workspaceId = options.workspaceId;
3256
+ this.fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
3257
+ }
3258
+ /** Set (or clear) the active workspace all subsequent requests target. */
3259
+ setWorkspace(workspaceId) {
3260
+ this.workspaceId = workspaceId ?? void 0;
3261
+ }
3262
+ /** Base headers shared by every call: credential + active workspace. */
3263
+ baseHeaders() {
3264
+ const headers = {};
3265
+ if (this.apiKey)
3266
+ headers["authorization"] = `Bearer ${this.apiKey}`;
3267
+ if (this.workspaceId)
3268
+ headers["x-workspace-id"] = this.workspaceId;
3269
+ return headers;
3270
+ }
3271
+ async parse(res) {
3272
+ if (res.status === 204)
3273
+ return void 0;
3274
+ const json = await res.json().catch(() => null);
3275
+ if (!res.ok) {
3276
+ const errBody = json ?? {};
3277
+ throw new PlatformApiError(res.status, errBody.error?.code ?? "unknown_error", errBody.error?.message ?? `Request failed with ${res.status}`, errBody.error?.details);
3278
+ }
3279
+ return json;
3280
+ }
3281
+ /** Append cursor-pagination params to a list path. */
3282
+ pathWithQuery(base, params) {
3283
+ const query = new URLSearchParams();
3284
+ if (params.cursor)
3285
+ query.set("cursor", params.cursor);
3286
+ if (params.limit !== void 0)
3287
+ query.set("limit", String(params.limit));
3288
+ const qs = query.toString();
3289
+ return qs ? `${base}?${qs}` : base;
3290
+ }
3291
+ async request(method, path, body, extraHeaders) {
3292
+ const headers = { ...this.baseHeaders(), ...extraHeaders };
3293
+ if (body !== void 0)
3294
+ headers["content-type"] = "application/json";
3295
+ const res = await this.fetchImpl(`${this.baseUrl}/api/v1${path}`, {
3296
+ method,
3297
+ headers,
3298
+ credentials: "same-origin",
3299
+ // Always see live state: /instance flips setupRequired the moment the
3300
+ // wizard completes but is served with public max-age for CLI/MCP
3301
+ // discovery — the browser HTTP cache must not answer for the app.
3302
+ // (`cache` is a browser-only field; cast keeps this isomorphic under a
3303
+ // Node lib where RequestInit omits it.)
3304
+ cache: "no-store",
3305
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
3306
+ });
3307
+ return this.parse(res);
3308
+ }
3309
+ instance() {
3310
+ return this.request("GET", "/instance");
3311
+ }
3312
+ setup(req) {
3313
+ return this.request("POST", "/setup", req);
3314
+ }
3315
+ me() {
3316
+ return this.request("GET", "/me");
3317
+ }
3318
+ /** Better Auth session probe — null when signed out. */
3319
+ async session() {
3320
+ return this.request("GET", "/auth/get-session");
3321
+ }
3322
+ signInEmail(email, password) {
3323
+ return this.request("POST", "/auth/sign-in/email", { email, password });
3324
+ }
3325
+ signOut() {
3326
+ return this.request("POST", "/auth/sign-out", {});
3327
+ }
3328
+ // ── CLI auth (browserless email-OTP → API key) ────────────────────────────
3329
+ /** Public: email a sign-in code. Generic success — silent about account existence. */
3330
+ cliAuthRequest(req) {
3331
+ return this.request("POST", "/cli/auth/request", req);
3332
+ }
3333
+ /**
3334
+ * Public: verify the code and mint an `slk_` API key (presentations:read +
3335
+ * presentations:write). The returned `key` appears only here.
3336
+ */
3337
+ cliAuthComplete(req) {
3338
+ return this.request("POST", "/cli/auth/complete", req);
3339
+ }
3340
+ // ── Members ───────────────────────────────────────────────────────────────
3341
+ members(params = {}) {
3342
+ return this.request("GET", this.pathWithQuery("/members", params));
3343
+ }
3344
+ updateMember(id, patch) {
3345
+ return this.request("PATCH", `/members/${encodeURIComponent(id)}`, patch);
3346
+ }
3347
+ /**
3348
+ * Admin: delete a member's account (GDPR erasure). Sessions only — the
3349
+ * endpoint is unlisted in the machine scope allowlist, so API keys 403.
3350
+ * Files the member uploaded stay with the workspace.
3351
+ */
3352
+ deleteMember(id) {
3353
+ return this.request("DELETE", `/members/${encodeURIComponent(id)}`);
3354
+ }
3355
+ /** Admin: mint a one-time password reset link for a member (SMTP-free recovery). */
3356
+ createMemberResetLink(id, opts = {}) {
3357
+ return this.request("POST", `/members/${encodeURIComponent(id)}/reset-link`, void 0, idempotencyHeader(opts));
3358
+ }
3359
+ /**
3360
+ * Admin: mint a one-time email change link for a member (SMTP-free email
3361
+ * change). ⚠️ The link updates the email AND signs the member in — share
3362
+ * it with the target member only.
3363
+ */
3364
+ createMemberChangeEmailLink(id, req, opts = {}) {
3365
+ return this.request("POST", `/members/${encodeURIComponent(id)}/change-email-link`, req, idempotencyHeader(opts));
3366
+ }
3367
+ // ── Break-glass (superadmin recovery, ADR 010) ────────────────────────────
3368
+ /**
3369
+ * Superadmin: make the caller (or a named existing user) an ACTIVE OWNER
3370
+ * of the workspace — creating, reactivating, or promoting the membership.
3371
+ * Adds an owner, never removes one. Sessions only: the endpoint is
3372
+ * unlisted in the machine scope allowlist (API keys/tokens 403), and the
3373
+ * calling session's VERIFIED email must be on SUPERADMIN_EMAILS.
3374
+ */
3375
+ breakGlassClaimOwnership(req = {}) {
3376
+ return this.request("POST", "/admin/break-glass/claim-ownership", req);
3377
+ }
3378
+ /** Superadmin: clear a locked-out user's 2FA (sessions only, audited). */
3379
+ breakGlassResetTwoFactor(req) {
3380
+ return this.request("POST", "/admin/break-glass/reset-2fa", req);
3381
+ }
3382
+ // ── API keys ──────────────────────────────────────────────────────────────
3383
+ apiKeys(params = {}) {
3384
+ return this.request("GET", this.pathWithQuery("/api-keys", params));
3385
+ }
3386
+ /** The returned `key` is the full secret — shown once, never retrievable. */
3387
+ createApiKey(req, opts = {}) {
3388
+ return this.request("POST", "/api-keys", req, idempotencyHeader(opts));
3389
+ }
3390
+ revokeApiKey(id) {
3391
+ return this.request("DELETE", `/api-keys/${encodeURIComponent(id)}`);
3392
+ }
3393
+ // ── Invitations ───────────────────────────────────────────────────────────
3394
+ invitations(params = {}) {
3395
+ return this.request("GET", this.pathWithQuery("/invitations", params));
3396
+ }
3397
+ /** `acceptUrl` is always returned — email delivery is best-effort on top. */
3398
+ createInvitation(req, opts = {}) {
3399
+ return this.request("POST", "/invitations", req, idempotencyHeader(opts));
3400
+ }
3401
+ revokeInvitation(id) {
3402
+ return this.request("DELETE", `/invitations/${encodeURIComponent(id)}`);
3403
+ }
3404
+ /** Public: resolves an invitation token for the acceptance page. */
3405
+ lookupInvitation(token) {
3406
+ return this.request("GET", `/invitations/lookup?token=${encodeURIComponent(token)}`);
3407
+ }
3408
+ /** Public: accepts an invitation (creates the account when needed). */
3409
+ acceptInvitation(req) {
3410
+ return this.request("POST", "/invitations/accept", req);
3411
+ }
3412
+ // ── OAuth consent ─────────────────────────────────────────────────────────
3413
+ /**
3414
+ * Park the workspace the upcoming OAuth consent should bind (ADR 014).
3415
+ * Sessions only; the consent page calls it right before approving when
3416
+ * the user picked a non-default workspace.
3417
+ */
3418
+ oauthConsentWorkspace(workspaceId) {
3419
+ return this.request("POST", "/oauth/consent-workspace", { workspaceId });
3420
+ }
3421
+ // ── Audit ─────────────────────────────────────────────────────────────────
3422
+ audit(params = {}) {
3423
+ return this.request("GET", this.pathWithQuery("/audit", params));
3424
+ }
3425
+ // ── Files ─────────────────────────────────────────────────────────────────
3426
+ files(params = {}) {
3427
+ return this.request("GET", this.pathWithQuery("/files", params));
3428
+ }
3429
+ /** Uploads raw bytes; the filename travels as a query param. */
3430
+ async uploadFile(name, body, contentType) {
3431
+ const type = contentType ?? (typeof Blob !== "undefined" && body instanceof Blob && body.type ? body.type : "application/octet-stream");
3432
+ const headers = { ...this.baseHeaders(), "content-type": type };
3433
+ const res = await this.fetchImpl(`${this.baseUrl}/api/v1/files?name=${encodeURIComponent(name)}`, {
3434
+ method: "POST",
3435
+ headers,
3436
+ credentials: "same-origin",
3437
+ body
3438
+ });
3439
+ return this.parse(res);
3440
+ }
3441
+ deleteFile(id) {
3442
+ return this.request("DELETE", `/files/${encodeURIComponent(id)}`);
3443
+ }
3444
+ file(id) {
3445
+ return this.request("GET", `/files/${encodeURIComponent(id)}`);
3446
+ }
3447
+ /** URL of the streamed (Range-capable) content endpoint for a file. */
3448
+ fileContentUrl(id) {
3449
+ return `${this.baseUrl}/api/v1/files/${encodeURIComponent(id)}/content`;
3450
+ }
3451
+ // ── Presentations ─────────────────────────────────────────────────────────
3452
+ presentations(params = {}) {
3453
+ return this.request("GET", this.pathWithQuery("/presentations", params));
3454
+ }
3455
+ presentation(id) {
3456
+ return this.request("GET", `/presentations/${encodeURIComponent(id)}`);
3457
+ }
3458
+ /** Soft delete: versions and share tokens stop resolving. */
3459
+ deletePresentation(id) {
3460
+ return this.request("DELETE", `/presentations/${encodeURIComponent(id)}`);
3461
+ }
3462
+ // ── Upload (push) ─────────────────────────────────────────────────────────
3463
+ /** Reserve a new-deck upload session (~1 h): mints the future presentation id. */
3464
+ createUploadSession(opts = {}) {
3465
+ return this.request("POST", "/presentations/uploads", void 0, idempotencyHeader(opts));
3466
+ }
3467
+ /** Which of these blobs the workspace is missing (upload exactly those). */
3468
+ precheckAssets(sha256) {
3469
+ return this.request("POST", "/presentations/precheck", { sha256 });
3470
+ }
3471
+ /** Upload one deck asset (multipart); the server re-hashes and rejects a mismatch. */
3472
+ async uploadAsset(sha256, body, contentType) {
3473
+ const blob = typeof Blob !== "undefined" && body instanceof Blob ? body : new Blob([body], contentType ? { type: contentType } : void 0);
3474
+ const form = new FormData();
3475
+ form.set("sha256", sha256);
3476
+ form.set("file", blob, sha256);
3477
+ const headers = this.baseHeaders();
3478
+ const res = await this.fetchImpl(`${this.baseUrl}/api/v1/presentations/assets`, {
3479
+ method: "POST",
3480
+ headers,
3481
+ // content-type comes from FormData (boundary included)
3482
+ credentials: "same-origin",
3483
+ body: form
3484
+ });
3485
+ return this.parse(res);
3486
+ }
3487
+ /** Commit an upload session: creates the deck and its version 1 (one-shot). */
3488
+ commitUploadSession(sessionId, req) {
3489
+ return this.request("POST", `/presentations/uploads/${encodeURIComponent(sessionId)}/commit`, req);
3490
+ }
3491
+ /**
3492
+ * Commit a new immutable version. `expectedBaseVersion` must equal the
3493
+ * deck's currentVersion or the server answers 409 version_conflict.
3494
+ */
3495
+ commitVersion(id, req) {
3496
+ return this.request("POST", `/presentations/${encodeURIComponent(id)}/versions`, req);
3497
+ }
3498
+ // ── Pull ──────────────────────────────────────────────────────────────────
3499
+ presentationVersions(id, params = {}) {
3500
+ return this.request("GET", this.pathWithQuery(`/presentations/${encodeURIComponent(id)}/versions`, params));
3501
+ }
3502
+ /** One version including its full manifest (path → sha256). */
3503
+ presentationVersion(id, version) {
3504
+ return this.request("GET", `/presentations/${encodeURIComponent(id)}/versions/${version}`);
3505
+ }
3506
+ /** URL of the streamed asset download endpoint (content-addressed). */
3507
+ presentationAssetUrl(id, sha256) {
3508
+ return `${this.baseUrl}/api/v1/presentations/${encodeURIComponent(id)}/assets/${encodeURIComponent(sha256)}`;
3509
+ }
3510
+ /**
3511
+ * Downloads one deck blob. Returns the raw Response so callers can stream
3512
+ * the bytes; a non-2xx answer throws PlatformApiError like every method.
3513
+ */
3514
+ async downloadPresentationAsset(id, sha256) {
3515
+ const headers = this.baseHeaders();
3516
+ const res = await this.fetchImpl(this.presentationAssetUrl(id, sha256), {
3517
+ method: "GET",
3518
+ headers,
3519
+ credentials: "same-origin",
3520
+ // Browser-only field; cast keeps this isomorphic under a Node lib.
3521
+ cache: "no-store"
3522
+ });
3523
+ if (!res.ok) {
3524
+ await this.parse(res);
3525
+ }
3526
+ return res;
3527
+ }
3528
+ // ── Sharing ───────────────────────────────────────────────────────────────
3529
+ shareTokens(id, params = {}) {
3530
+ return this.request("GET", this.pathWithQuery(`/presentations/${encodeURIComponent(id)}/tokens`, params));
3531
+ }
3532
+ /** The returned `secret`/`url` appear only here — never retrievable again. */
3533
+ createShareToken(id, req, opts = {}) {
3534
+ return this.request("POST", `/presentations/${encodeURIComponent(id)}/tokens`, req, idempotencyHeader(opts));
3535
+ }
3536
+ /**
3537
+ * Mint the dashboard's transient preview token (deck owner / workspace
3538
+ * admin only — 403 for dev collaborators). Server-fixed: purpose
3539
+ * 'preview', 1 h expiry, hidden from the sharing panel, excluded from view
3540
+ * stats, immutable. `version` pins the preview; omitted = latest.
3541
+ */
3542
+ createPreviewToken(id, req = {}) {
3543
+ return this.request("POST", `/presentations/${encodeURIComponent(id)}/preview-token`, req);
3544
+ }
3545
+ /** Pin/unpin version, rename, annotate flag, expiry, password (null clears). */
3546
+ updateShareToken(id, tokenId, patch) {
3547
+ return this.request("PATCH", `/presentations/${encodeURIComponent(id)}/tokens/${encodeURIComponent(tokenId)}`, patch);
3548
+ }
3549
+ /** Soft revoke — access stats survive. */
3550
+ revokeShareToken(id, tokenId) {
3551
+ return this.request("DELETE", `/presentations/${encodeURIComponent(id)}/tokens/${encodeURIComponent(tokenId)}`);
3552
+ }
3553
+ /** Email the viewer link to a recipient (best-effort on top of the copyable URL). */
3554
+ sendShareToken(id, tokenId, req) {
3555
+ return this.request("POST", `/presentations/${encodeURIComponent(id)}/tokens/${encodeURIComponent(tokenId)}/send`, req);
3556
+ }
3557
+ // ── Collaborators ─────────────────────────────────────────────────────────
3558
+ collaborators(id, params = {}) {
3559
+ return this.request("GET", this.pathWithQuery(`/presentations/${encodeURIComponent(id)}/collaborators`, params));
3560
+ }
3561
+ /** `claimUrl` is always returned — email delivery is best-effort on top. */
3562
+ inviteCollaborator(id, req, opts = {}) {
3563
+ return this.request("POST", `/presentations/${encodeURIComponent(id)}/collaborators`, req, idempotencyHeader(opts));
3564
+ }
3565
+ removeCollaborator(id, collaboratorId) {
3566
+ return this.request("DELETE", `/presentations/${encodeURIComponent(id)}/collaborators/${encodeURIComponent(collaboratorId)}`);
3567
+ }
3568
+ /** Public: resolves a collaborator claim token for the claim page. */
3569
+ lookupCollaboratorInvite(token) {
3570
+ return this.request("GET", `/collaborators/lookup?token=${encodeURIComponent(token)}`);
3571
+ }
3572
+ /** Public: claims a collaborator grant (creates the account when needed). */
3573
+ claimCollaboratorInvite(req) {
3574
+ return this.request("POST", "/collaborators/claim", req);
3575
+ }
3576
+ // ── Annotations ───────────────────────────────────────────────────────────
3577
+ pathWithAnnotationQuery(base, params) {
3578
+ const query = new URLSearchParams();
3579
+ if (params.cursor)
3580
+ query.set("cursor", params.cursor);
3581
+ if (params.limit !== void 0)
3582
+ query.set("limit", String(params.limit));
3583
+ if (params.version !== void 0)
3584
+ query.set("version", String(params.version));
3585
+ if (params.status)
3586
+ query.set("status", params.status);
3587
+ const qs = query.toString();
3588
+ return qs ? `${base}?${qs}` : base;
3589
+ }
3590
+ annotations(id, params = {}) {
3591
+ return this.request("GET", this.pathWithAnnotationQuery(`/presentations/${encodeURIComponent(id)}/annotations`, params));
3592
+ }
3593
+ /** Workspace-wide inbox: annotations across all decks, newest first. */
3594
+ annotationInbox(params = {}) {
3595
+ return this.request("GET", this.pathWithAnnotationQuery("/annotations", params));
3596
+ }
3597
+ createAnnotation(id, req) {
3598
+ return this.request("POST", `/presentations/${encodeURIComponent(id)}/annotations`, req);
3599
+ }
3600
+ updateAnnotation(id, annotationId, patch) {
3601
+ return this.request("PATCH", `/presentations/${encodeURIComponent(id)}/annotations/${encodeURIComponent(annotationId)}`, patch);
3602
+ }
3603
+ deleteAnnotation(id, annotationId) {
3604
+ return this.request("DELETE", `/presentations/${encodeURIComponent(id)}/annotations/${encodeURIComponent(annotationId)}`);
3605
+ }
3606
+ // ── Workspace export ──────────────────────────────────────────────────────
3607
+ /** URL of the workspace export endpoint (admin+; keys need data:export). */
3608
+ workspaceExportUrl() {
3609
+ return `${this.baseUrl}/api/v1/workspace/export`;
3610
+ }
3611
+ /**
3612
+ * Downloads the full workspace export. Returns the raw Response so callers
3613
+ * can stream the zip (exports can be large — never buffer by default);
3614
+ * a non-2xx answer throws PlatformApiError like every other method.
3615
+ */
3616
+ async downloadExport() {
3617
+ const headers = this.baseHeaders();
3618
+ const res = await this.fetchImpl(this.workspaceExportUrl(), {
3619
+ method: "GET",
3620
+ headers,
3621
+ credentials: "same-origin",
3622
+ // Browser-only field; cast keeps this isomorphic under a Node lib.
3623
+ cache: "no-store"
3624
+ });
3625
+ if (!res.ok) {
3626
+ await this.parse(res);
3627
+ }
3628
+ return res;
3629
+ }
3630
+ };
3631
+
3632
+ // src/config.ts
3633
+ var TOOL = "slideless";
3634
+ var LEGACY = { tool: TOOL, legacyDir: "slideless" };
3635
+ function configPath2(env) {
3636
+ return configPath(env, TOOL);
3637
+ }
3638
+ function loadConfig2(env) {
3639
+ try {
3640
+ migrateLegacyConfig(env, LEGACY);
3641
+ } catch {
3642
+ }
3643
+ return loadConfig(env, TOOL);
3644
+ }
3645
+ function saveConfig2(env, config) {
3646
+ return saveConfig(env, TOOL, config);
3647
+ }
3648
+ function clearConfig2(env) {
3649
+ clearConfig(env, TOOL);
3650
+ }
3651
+
3652
+ // src/context.ts
3653
+ function resolveProfile2(config, requested) {
3654
+ const resolved = resolveProfile(config, requested, {
3655
+ unknownHint: "run `slideless profiles` to list them."
3656
+ });
3657
+ return resolved;
3658
+ }
3659
+ function resolveContext(cmd, io) {
3660
+ const opts = cmd.optsWithGlobals();
3661
+ const config = loadConfig2(io.env);
3662
+ const { name: profileName, profile } = resolveProfile2(config, opts.profile);
3663
+ const baseUrl = resolveBaseUrl({
3664
+ flag: opts.apiUrl ?? opts.url,
3665
+ env: io.env,
3666
+ envVar: "SLIDELESS_URL",
3667
+ profile,
3668
+ missingMessage: "No instance configured. Pass --api-url <url>, set SLIDELESS_URL, or sign in once with `slideless auth login-request --api-url <url> --email <you>` to save a profile."
3669
+ });
3670
+ const apiKey = resolveApiKey({ flag: opts.apiKey, env: io.env, envVar: "SLIDELESS_API_KEY", profile });
3671
+ const fetchImpl = io.fetch ?? globalThis.fetch.bind(globalThis);
3672
+ return {
3673
+ client: new PlatformClient({ baseUrl, ...apiKey ? { apiKey } : {}, fetch: fetchImpl }),
3674
+ baseUrl,
3675
+ apiKey,
3676
+ json: Boolean(opts.json),
3677
+ io,
3678
+ profileName,
3679
+ config
3680
+ };
3681
+ }
3682
+ function requireApiKey(ctx) {
3683
+ if (!ctx.apiKey) {
3684
+ throw new CliUsageError(
3685
+ "An API key is required. Sign in (`slideless auth login-request --email <you>`), paste one (`slideless login`), pass --api-key, or set SLIDELESS_API_KEY."
3686
+ );
3687
+ }
3688
+ return ctx.apiKey;
3689
+ }
3690
+ function table(rows) {
3691
+ if (rows.length === 0) return "";
3692
+ const first = rows[0];
3693
+ const widths = first.map((_, i) => Math.max(...rows.map((r) => (r[i] ?? "").length)));
3694
+ return rows.map(
3695
+ (r) => r.map((cell, i) => i === r.length - 1 ? cell : (cell ?? "").padEnd(widths[i] ?? 0)).join(" ").trimEnd()
3696
+ ).join("\n") + "\n";
3697
+ }
3698
+
3699
+ // src/commands/auth.ts
3700
+ var DEFAULT_PROFILE2 = "default";
3701
+ function resolveAuthUrl(cmd, io) {
3702
+ const opts = cmd.optsWithGlobals();
3703
+ const config = loadConfig2(io.env);
3704
+ const profileName = opts.profile ?? config.activeProfile;
3705
+ const profile = profileName ? config.profiles[profileName] : void 0;
3706
+ const raw = opts.apiUrl ?? opts.url ?? io.env.SLIDELESS_URL ?? profile?.baseUrl;
3707
+ if (!raw) {
3708
+ throw new CliUsageError("No instance to talk to \u2014 pass --api-url <url> (or set SLIDELESS_URL).");
3709
+ }
3710
+ return raw.replace(/\/+$/, "");
3711
+ }
3712
+ function saveProfileKey(io, profileName, baseUrl, apiKey) {
3713
+ const config = loadConfig2(io.env);
3714
+ config.profiles[profileName] = { ...config.profiles[profileName], apiKey, baseUrl };
3715
+ config.activeProfile = profileName;
3716
+ const path = saveConfig2(io.env, config);
3717
+ return { config, path };
3718
+ }
3719
+ async function readLineFromStdin() {
3720
+ const chunks = [];
3721
+ for await (const chunk of process.stdin) chunks.push(chunk);
3722
+ return Buffer.concat(chunks).toString("utf8").split("\n")[0]?.trim() ?? "";
3723
+ }
3724
+ function registerAuthCommands(program2, io) {
3725
+ const auth = program2.command("auth").description("Sign in over email OTP (mints an API key)");
3726
+ auth.command("login-request").description("Email a 6-digit sign-in code (existing accounts only \u2014 sign-up stays closed)").requiredOption("--email <email>", "account email on the instance").action(async (opts, cmd) => {
3727
+ const baseUrl = resolveAuthUrl(cmd, io);
3728
+ const client = new CliAuthClient({ baseUrl, ...io.fetch ? { fetch: io.fetch } : {} });
3729
+ const result = await client.request({ email: opts.email });
3730
+ const json = Boolean(cmd.optsWithGlobals().json);
3731
+ if (json) return printJson(io, { ...result, email: opts.email, baseUrl });
3732
+ io.out.write(
3733
+ `If ${opts.email} has an account on ${baseUrl}, a sign-in code is on its way.
3734
+ Complete with: slideless auth login-complete --email ${opts.email} --code <code>
3735
+ `
3736
+ );
3737
+ });
3738
+ auth.command("login-complete").description("Verify the emailed code; stores the minted API key as a profile").requiredOption("--email <email>", "the email the code was sent to").requiredOption("--code <code>", "the 6-digit code from the email").option("--key-name <name>", "display name for the minted API key").option(
3739
+ "--expires-in-days <n>",
3740
+ "key TTL in days (default: never expires)",
3741
+ (v) => parseInt(v, 10)
3742
+ ).action(
3743
+ async (opts, cmd) => {
3744
+ const globals = cmd.optsWithGlobals();
3745
+ const baseUrl = resolveAuthUrl(cmd, io);
3746
+ const client = new CliAuthClient({ baseUrl, ...io.fetch ? { fetch: io.fetch } : {} });
3747
+ const result = await client.complete({
3748
+ email: opts.email,
3749
+ otp: opts.code,
3750
+ ...opts.keyName ? { keyName: opts.keyName } : {},
3751
+ ...opts.expiresInDays ? { expiresInDays: opts.expiresInDays } : {}
3752
+ });
3753
+ const profileName = globals.profile ?? DEFAULT_PROFILE2;
3754
+ const { path } = saveProfileKey(io, profileName, baseUrl, result.key);
3755
+ if (globals.json) {
3756
+ return printJson(io, {
3757
+ profile: profileName,
3758
+ baseUrl,
3759
+ user: result.user,
3760
+ apiKey: result.apiKey,
3761
+ configPath: path
3762
+ });
3763
+ }
3764
+ io.out.write(
3765
+ `Signed in as ${result.user.email} on ${baseUrl}.
3766
+ API key "${result.apiKey.name}" (${redactKey(result.key)}) saved to profile "${profileName}" (${path}).
3767
+ `
3768
+ );
3769
+ }
3770
+ );
3771
+ program2.command("login").description("Save an existing slk_ API key as a profile (pass --api-key or pipe it on stdin)").action(async (_opts, cmd) => {
3772
+ const globals = cmd.optsWithGlobals();
3773
+ const baseUrl = resolveAuthUrl(cmd, io);
3774
+ let key = globals.apiKey ?? io.env.SLIDELESS_API_KEY;
3775
+ if (!key) {
3776
+ key = await readLineFromStdin();
3777
+ }
3778
+ if (!key || !key.startsWith("slk_")) {
3779
+ throw new CliUsageError("No API key provided \u2014 pass --api-key slk_\u2026 or pipe the key on stdin.");
3780
+ }
3781
+ const fetchImpl = io.fetch ?? globalThis.fetch.bind(globalThis);
3782
+ const client = new PlatformClient({ baseUrl, apiKey: key, fetch: fetchImpl });
3783
+ const me = await client.me();
3784
+ const profileName = globals.profile ?? DEFAULT_PROFILE2;
3785
+ const { path } = saveProfileKey(io, profileName, baseUrl, key);
3786
+ if (globals.json) {
3787
+ return printJson(io, { profile: profileName, baseUrl, user: me.user, configPath: path });
3788
+ }
3789
+ io.out.write(
3790
+ `Key verified for ${me.user.email} on ${baseUrl} \u2014 saved to profile "${profileName}" (${path}).
3791
+ `
3792
+ );
3793
+ });
3794
+ program2.command("logout").description("Forget the stored API key of the active (or named) profile").action(async (_opts, cmd) => {
3795
+ const globals = cmd.optsWithGlobals();
3796
+ const config2 = loadConfig2(io.env);
3797
+ const profileName = globals.profile ?? config2.activeProfile;
3798
+ const profile = profileName ? config2.profiles[profileName] : void 0;
3799
+ if (!profileName || !profile) {
3800
+ throw new CliUsageError("No profile to log out of.");
3801
+ }
3802
+ delete profile.apiKey;
3803
+ if (!profile.baseUrl) delete config2.profiles[profileName];
3804
+ saveConfig2(io.env, config2);
3805
+ if (globals.json) return printJson(io, { loggedOut: profileName });
3806
+ io.out.write(
3807
+ `Logged out of profile "${profileName}" (key forgotten; revoke it in the dashboard to kill it server-side).
3808
+ `
3809
+ );
3810
+ });
3811
+ program2.command("whoami").description("Show the identity behind the resolved API key").action(async (_opts, cmd) => {
3812
+ const ctx = resolveContext(cmd, io);
3813
+ requireApiKey(ctx);
3814
+ const me = await ctx.client.me();
3815
+ if (ctx.json) return printJson(io, me);
3816
+ io.out.write(
3817
+ `${me.user.name} <${me.user.email}>
3818
+ instance: ${ctx.baseUrl}
3819
+ workspace: ${me.workspace.name}
3820
+ role: ${me.role} (via ${me.via})
3821
+ scopes: ${me.scopes ? me.scopes.join(", ") : "full (session)"}
3822
+ ` + (me.via === "api_key" ? ` key expires: ${me.apiKeyExpiresAt ?? "never"}
3823
+ ` : "")
3824
+ );
3825
+ });
3826
+ program2.command("verify").description("Check that the resolved instance + key work (exit 0 = ok)").action(async (_opts, cmd) => {
3827
+ const ctx = resolveContext(cmd, io);
3828
+ requireApiKey(ctx);
3829
+ const me = await ctx.client.me();
3830
+ if (ctx.json) return printJson(io, { ok: true, baseUrl: ctx.baseUrl, user: me.user });
3831
+ io.out.write(`ok \u2014 ${me.user.email} (${me.role}) @ ${ctx.baseUrl}
3832
+ `);
3833
+ });
3834
+ program2.command("use <profile>").description("Switch the active profile").action(async (name, _opts, cmd) => {
3835
+ const globals = cmd.optsWithGlobals();
3836
+ const config2 = loadConfig2(io.env);
3837
+ if (!config2.profiles[name]) {
3838
+ throw new CliUsageError(`Unknown profile "${name}" \u2014 run \`slideless profiles\`.`);
3839
+ }
3840
+ config2.activeProfile = name;
3841
+ saveConfig2(io.env, config2);
3842
+ if (globals.json) return printJson(io, { activeProfile: name });
3843
+ io.out.write(`Active profile: ${name}
3844
+ `);
3845
+ });
3846
+ program2.command("profiles").description("List saved profiles").action(async (_opts, cmd) => {
3847
+ const globals = cmd.optsWithGlobals();
3848
+ const config2 = loadConfig2(io.env);
3849
+ const names = Object.keys(config2.profiles);
3850
+ if (globals.json) {
3851
+ return printJson(io, {
3852
+ activeProfile: config2.activeProfile ?? null,
3853
+ profiles: Object.fromEntries(
3854
+ names.map((n) => {
3855
+ const p = config2.profiles[n];
3856
+ return [n, { baseUrl: p.baseUrl ?? null, apiKey: p.apiKey ? redactKey(p.apiKey) : null }];
3857
+ })
3858
+ )
3859
+ });
3860
+ }
3861
+ if (names.length === 0) {
3862
+ io.out.write(
3863
+ "No profiles. Sign in with `slideless auth login-request --api-url <url> --email <you>`.\n"
3864
+ );
3865
+ return;
3866
+ }
3867
+ io.out.write(
3868
+ table(
3869
+ names.map((n) => {
3870
+ const p = config2.profiles[n];
3871
+ return [
3872
+ config2.activeProfile === n ? "*" : " ",
3873
+ n,
3874
+ p.baseUrl ?? "(no url)",
3875
+ p.apiKey ? redactKey(p.apiKey) : "(no key)"
3876
+ ];
3877
+ })
3878
+ )
3879
+ );
3880
+ });
3881
+ const config = program2.command("config").description("Inspect or reset the CLI config file");
3882
+ config.command("show").description("Show the config path, active profile, and redacted keys").action(async (_opts, cmd) => {
3883
+ const globals = cmd.optsWithGlobals();
3884
+ const cfg = loadConfig2(io.env);
3885
+ const path = configPath2(io.env);
3886
+ const redacted = {
3887
+ path,
3888
+ activeProfile: cfg.activeProfile ?? null,
3889
+ profiles: Object.fromEntries(
3890
+ Object.entries(cfg.profiles).map(([n, p]) => [
3891
+ n,
3892
+ { baseUrl: p.baseUrl ?? null, apiKey: p.apiKey ? redactKey(p.apiKey) : null }
3893
+ ])
3894
+ )
3895
+ };
3896
+ if (globals.json) return printJson(io, redacted);
3897
+ io.out.write(`config: ${path ?? "(no HOME/XDG_CONFIG_HOME \u2014 config disabled)"}
3898
+ `);
3899
+ io.out.write(`${JSON.stringify(redacted, null, 2)}
3900
+ `);
3901
+ });
3902
+ config.command("clear").description("Delete the config file (all profiles and stored keys)").action(async (_opts, cmd) => {
3903
+ const globals = cmd.optsWithGlobals();
3904
+ clearConfig2(io.env);
3905
+ if (globals.json) return printJson(io, { cleared: true });
3906
+ io.out.write("Config cleared.\n");
3907
+ });
3908
+ }
3909
+
3910
+ // src/commands/decks.ts
3911
+ function registerDeckCommands(program2, io) {
3912
+ program2.command("list").description("List presentations (newest first, cursor-paginated)").option("--cursor <cursor>", "resume from a previous nextCursor").option("--limit <n>", "page size (1-100)", (v) => parseInt(v, 10)).option("--all", "follow nextCursor until every page is fetched", false).action(async (opts, cmd) => {
3913
+ const ctx = resolveContext(cmd, io);
3914
+ requireApiKey(ctx);
3915
+ const params = {};
3916
+ if (opts.cursor) params.cursor = opts.cursor;
3917
+ if (opts.limit !== void 0) params.limit = opts.limit;
3918
+ const first = await ctx.client.presentations(params);
3919
+ const rows = [...first.presentations];
3920
+ if (opts.all) {
3921
+ let cursor = first.nextCursor;
3922
+ while (cursor) {
3923
+ const page = await ctx.client.presentations({ ...params, cursor });
3924
+ rows.push(...page.presentations);
3925
+ cursor = page.nextCursor;
3926
+ }
3927
+ }
3928
+ const nextCursor = opts.all ? null : first.nextCursor;
3929
+ if (ctx.json) return printJson(io, { presentations: rows, nextCursor });
3930
+ if (rows.length === 0) {
3931
+ io.out.write("No presentations.\n");
3932
+ return;
3933
+ }
3934
+ io.out.write(table(rows.map((p) => [p.id, `v${p.currentVersion}`, p.kind, p.title])));
3935
+ if (nextCursor) {
3936
+ io.out.write(`More available: rerun with --cursor ${nextCursor} or --all
3937
+ `);
3938
+ }
3939
+ });
3940
+ program2.command("get <id>").description("Show one presentation (metadata + latest version)").action(async (id, _opts, cmd) => {
3941
+ const ctx = resolveContext(cmd, io);
3942
+ requireApiKey(ctx);
3943
+ const deck = await ctx.client.presentation(id);
3944
+ if (ctx.json) return printJson(io, deck);
3945
+ io.out.write(
3946
+ `${deck.title}
3947
+ id: ${deck.id}
3948
+ kind: ${deck.kind}${deck.interactive ? " (interactive)" : ""}
3949
+ version: ${deck.currentVersion}
3950
+ entry: ${deck.entryPath}
3951
+ owner: ${deck.ownerUserId ?? "(deleted user)"}
3952
+ created: ${deck.createdAt}
3953
+ updated: ${deck.updatedAt}
3954
+ `
3955
+ );
3956
+ });
3957
+ program2.command("delete <id>").description("Delete a presentation (soft delete; versions and share links stop resolving)").action(async (id, _opts, cmd) => {
3958
+ const ctx = resolveContext(cmd, io);
3959
+ requireApiKey(ctx);
3960
+ const deck = await ctx.client.deletePresentation(id);
3961
+ if (ctx.json) return printJson(io, deck);
3962
+ io.out.write(`Deleted "${deck.title}" (${deck.id}).
3963
+ `);
3964
+ });
3965
+ }
3966
+
3967
+ // src/commands/content.ts
3968
+ import { spawn } from "node:child_process";
3969
+ import { readFile as readFile3, mkdir, writeFile as writeFile2 } from "node:fs/promises";
3970
+ import { dirname as dirname3, join as join4, resolve as resolve3 } from "node:path";
3971
+
3972
+ // src/manifest.ts
3973
+ import { createHash } from "node:crypto";
3974
+ import { createReadStream } from "node:fs";
3975
+ import { readdir, readFile, stat, writeFile } from "node:fs/promises";
3976
+ import { basename, dirname as dirname2, extname, join as join3, resolve, sep } from "node:path";
3977
+ var LINK_FILENAME = ".slideless.json";
3978
+ var IGNORE_FILENAME = ".slidelessignore";
3979
+ var DEFAULT_IGNORES = [".git", "node_modules", ".DS_Store", "Thumbs.db", LINK_FILENAME, IGNORE_FILENAME];
3980
+ var CONTENT_TYPES = {
3981
+ ".html": "text/html",
3982
+ ".htm": "text/html",
3983
+ ".css": "text/css",
3984
+ ".js": "text/javascript",
3985
+ ".mjs": "text/javascript",
3986
+ ".cjs": "text/javascript",
3987
+ ".json": "application/json",
3988
+ ".map": "application/json",
3989
+ ".png": "image/png",
3990
+ ".jpg": "image/jpeg",
3991
+ ".jpeg": "image/jpeg",
3992
+ ".gif": "image/gif",
3993
+ ".svg": "image/svg+xml",
3994
+ ".webp": "image/webp",
3995
+ ".avif": "image/avif",
3996
+ ".ico": "image/x-icon",
3997
+ ".woff": "font/woff",
3998
+ ".woff2": "font/woff2",
3999
+ ".ttf": "font/ttf",
4000
+ ".otf": "font/otf",
4001
+ ".eot": "application/vnd.ms-fontobject",
4002
+ ".mp4": "video/mp4",
4003
+ ".webm": "video/webm",
4004
+ ".mp3": "audio/mpeg",
4005
+ ".wav": "audio/wav",
4006
+ ".ogg": "audio/ogg",
4007
+ ".pdf": "application/pdf",
4008
+ ".txt": "text/plain",
4009
+ ".md": "text/markdown",
4010
+ ".xml": "application/xml",
4011
+ ".csv": "text/csv",
4012
+ ".wasm": "application/wasm"
4013
+ };
4014
+ function contentTypeFor(path) {
4015
+ return CONTENT_TYPES[extname(path).toLowerCase()] ?? "application/octet-stream";
4016
+ }
4017
+ async function sha256File(absPath) {
4018
+ const hash = createHash("sha256");
4019
+ await new Promise((resolvePromise, reject) => {
4020
+ createReadStream(absPath).on("data", (chunk) => hash.update(chunk)).on("end", () => resolvePromise()).on("error", reject);
4021
+ });
4022
+ return hash.digest("hex");
4023
+ }
4024
+ function globToRegex(glob) {
4025
+ let out = "";
4026
+ for (let i = 0; i < glob.length; i++) {
4027
+ const ch = glob[i];
4028
+ if (ch === "*") {
4029
+ if (glob[i + 1] === "*") {
4030
+ out += ".*";
4031
+ i++;
4032
+ if (glob[i + 1] === "/") {
4033
+ out = out.slice(0, -2) + "(?:.*/)?";
4034
+ i++;
4035
+ }
4036
+ } else {
4037
+ out += "[^/]*";
4038
+ }
4039
+ } else if (ch === "?") {
4040
+ out += "[^/]";
4041
+ } else {
4042
+ out += ch.replace(/[.+^${}()|[\]\\]/g, "\\$&");
4043
+ }
4044
+ }
4045
+ return out;
4046
+ }
4047
+ function parseIgnoreFile(content) {
4048
+ const rules = [];
4049
+ for (const rawLine of content.split("\n")) {
4050
+ const line = rawLine.trim();
4051
+ if (line === "" || line.startsWith("#")) continue;
4052
+ let pattern = line;
4053
+ const dirOnly = pattern.endsWith("/");
4054
+ if (dirOnly) pattern = pattern.slice(0, -1);
4055
+ const anchored = pattern.includes("/");
4056
+ if (pattern.startsWith("/")) pattern = pattern.slice(1);
4057
+ rules.push({ regex: new RegExp(`^${globToRegex(pattern)}$`), dirOnly, anchored });
4058
+ }
4059
+ return rules;
4060
+ }
4061
+ function isIgnored(relPath, isDir, rules) {
4062
+ const base = relPath.split("/").pop() ?? relPath;
4063
+ if (DEFAULT_IGNORES.includes(base)) return true;
4064
+ for (const rule of rules) {
4065
+ if (rule.dirOnly && !isDir) continue;
4066
+ const subject = rule.anchored ? relPath : base;
4067
+ if (rule.regex.test(subject)) return true;
4068
+ }
4069
+ return false;
4070
+ }
4071
+ async function walk(rootDir, dir, rules, out) {
4072
+ const entries = await readdir(dir, { withFileTypes: true });
4073
+ for (const entry of entries) {
4074
+ const absPath = join3(dir, entry.name);
4075
+ const relPath = absPath.slice(rootDir.length + 1).split(sep).join("/");
4076
+ if (entry.isSymbolicLink()) continue;
4077
+ if (entry.isDirectory()) {
4078
+ if (isIgnored(relPath, true, rules)) continue;
4079
+ await walk(rootDir, absPath, rules, out);
4080
+ } else if (entry.isFile()) {
4081
+ if (isIgnored(relPath, false, rules)) continue;
4082
+ out.push({ path: relPath, absPath });
4083
+ }
4084
+ }
4085
+ }
4086
+ async function scanDeck(target) {
4087
+ const abs = resolve(target);
4088
+ const info = await stat(abs).catch(() => null);
4089
+ if (!info) throw new Error(`No such file or directory: ${target}`);
4090
+ let rootDir;
4091
+ let listed;
4092
+ if (info.isFile()) {
4093
+ rootDir = dirname2(abs);
4094
+ listed = [{ path: basename(abs), absPath: abs }];
4095
+ } else {
4096
+ rootDir = abs;
4097
+ let rules = [];
4098
+ const ignoreFile = await readFile(join3(abs, IGNORE_FILENAME), "utf8").catch(() => null);
4099
+ if (ignoreFile !== null) rules = parseIgnoreFile(ignoreFile);
4100
+ listed = [];
4101
+ await walk(rootDir, rootDir, rules, listed);
4102
+ }
4103
+ if (listed.length === 0) {
4104
+ throw new Error(`Nothing to push: ${target} has no files (after ignores)`);
4105
+ }
4106
+ if (listed.length > 5e3) {
4107
+ throw new Error(`Deck too large: ${listed.length} files (the server caps manifests at 5000)`);
4108
+ }
4109
+ const files = [];
4110
+ for (const item of listed) {
4111
+ const s = await stat(item.absPath);
4112
+ files.push({
4113
+ path: item.path,
4114
+ absPath: item.absPath,
4115
+ sha256: await sha256File(item.absPath),
4116
+ sizeBytes: s.size,
4117
+ contentType: contentTypeFor(item.path)
4118
+ });
4119
+ }
4120
+ files.sort((a, b) => a.path < b.path ? -1 : 1);
4121
+ return { rootDir, files };
4122
+ }
4123
+ function detectEntry(scan, explicit) {
4124
+ if (explicit) {
4125
+ const normalized = explicit.replace(/^\.\//, "");
4126
+ if (!scan.files.some((f) => f.path === normalized)) {
4127
+ throw new Error(`--entry ${explicit} is not among the deck's files`);
4128
+ }
4129
+ return normalized;
4130
+ }
4131
+ if (scan.files.some((f) => f.path === "index.html")) return "index.html";
4132
+ const htmls = scan.files.filter((f) => f.path.endsWith(".html") || f.path.endsWith(".htm"));
4133
+ if (htmls.length === 1) return htmls[0].path;
4134
+ if (htmls.length === 0) throw new Error("No HTML entry found \u2014 a deck needs at least one .html file");
4135
+ throw new Error(
4136
+ `Multiple HTML files and no index.html \u2014 pick one with --entry (${htmls.map((h) => h.path).slice(0, 5).join(", ")}${htmls.length > 5 ? ", \u2026" : ""})`
4137
+ );
4138
+ }
4139
+ async function readLink(rootDir) {
4140
+ try {
4141
+ const parsed = JSON.parse(await readFile(join3(rootDir, LINK_FILENAME), "utf8"));
4142
+ if (typeof parsed.presentationId === "string" && typeof parsed.baseUrl === "string") {
4143
+ return { presentationId: parsed.presentationId, baseUrl: parsed.baseUrl };
4144
+ }
4145
+ return null;
4146
+ } catch {
4147
+ return null;
4148
+ }
4149
+ }
4150
+ async function writeLink(rootDir, link) {
4151
+ await writeFile(join3(rootDir, LINK_FILENAME), `${JSON.stringify(link, null, 2)}
4152
+ `);
4153
+ }
4154
+
4155
+ // src/devserver.ts
4156
+ import { watch } from "node:fs";
4157
+ import { readFile as readFile2, stat as stat2 } from "node:fs/promises";
4158
+ import { createServer } from "node:http";
4159
+ import { resolve as resolve2, sep as sep2 } from "node:path";
4160
+ var DEV_SANDBOX_CSP = "sandbox allow-scripts allow-forms allow-popups allow-modals allow-downloads";
4161
+ var CONTENT_HEADERS = {
4162
+ "content-security-policy": DEV_SANDBOX_CSP,
4163
+ "x-content-type-options": "nosniff",
4164
+ "referrer-policy": "no-referrer",
4165
+ "cache-control": "no-store"
4166
+ };
4167
+ var RELOAD_PATH = "/__slideless/reload";
4168
+ var RELOAD_SNIPPET = `<script>
4169
+ (() => {
4170
+ const connect = () => {
4171
+ const es = new EventSource('${RELOAD_PATH}');
4172
+ es.addEventListener('reload', () => location.reload());
4173
+ es.onerror = () => { es.close(); setTimeout(connect, 1000); };
4174
+ };
4175
+ connect();
4176
+ })();
4177
+ </script>`;
4178
+ function injectReload(html) {
4179
+ const idx = html.lastIndexOf("</body>");
4180
+ if (idx === -1) return html + RELOAD_SNIPPET;
4181
+ return html.slice(0, idx) + RELOAD_SNIPPET + html.slice(idx);
4182
+ }
4183
+ async function startDevServer(options) {
4184
+ const root = resolve2(options.root);
4185
+ const host = options.host ?? "127.0.0.1";
4186
+ const sseClients = /* @__PURE__ */ new Set();
4187
+ const server = createServer((req, res) => {
4188
+ void (async () => {
4189
+ const url = new URL(req.url ?? "/", "http://localhost");
4190
+ let pathname;
4191
+ try {
4192
+ pathname = decodeURIComponent(url.pathname);
4193
+ } catch {
4194
+ res.writeHead(400, CONTENT_HEADERS).end("Bad request");
4195
+ return;
4196
+ }
4197
+ if (pathname === RELOAD_PATH) {
4198
+ res.writeHead(200, {
4199
+ "content-type": "text/event-stream",
4200
+ "cache-control": "no-store",
4201
+ connection: "keep-alive"
4202
+ });
4203
+ res.write(": connected\n\n");
4204
+ sseClients.add(res);
4205
+ req.on("close", () => sseClients.delete(res));
4206
+ return;
4207
+ }
4208
+ const relPath = pathname === "/" ? options.entryPath : pathname.replace(/^\/+/, "");
4209
+ const target = resolve2(root, relPath);
4210
+ if (target !== root && !target.startsWith(root + sep2)) {
4211
+ res.writeHead(404, CONTENT_HEADERS).end("Not found");
4212
+ return;
4213
+ }
4214
+ const info = await stat2(target).catch(() => null);
4215
+ if (!info || !info.isFile()) {
4216
+ res.writeHead(404, CONTENT_HEADERS).end("Not found");
4217
+ return;
4218
+ }
4219
+ const contentType = contentTypeFor(target);
4220
+ if (contentType === "text/html") {
4221
+ const html = injectReload(await readFile2(target, "utf8"));
4222
+ res.writeHead(200, { ...CONTENT_HEADERS, "content-type": "text/html; charset=utf-8" }).end(html);
4223
+ return;
4224
+ }
4225
+ const bytes = await readFile2(target);
4226
+ res.writeHead(200, { ...CONTENT_HEADERS, "content-type": contentType }).end(bytes);
4227
+ })().catch(() => {
4228
+ if (!res.headersSent) res.writeHead(500, CONTENT_HEADERS);
4229
+ res.end("Internal error");
4230
+ });
4231
+ });
4232
+ let watcher = null;
4233
+ let debounce = null;
4234
+ const broadcast = () => {
4235
+ if (debounce) clearTimeout(debounce);
4236
+ debounce = setTimeout(() => {
4237
+ for (const client of sseClients) client.write("event: reload\ndata: now\n\n");
4238
+ }, 100);
4239
+ };
4240
+ try {
4241
+ watcher = watch(root, { recursive: true }, broadcast);
4242
+ } catch {
4243
+ try {
4244
+ watcher = watch(root, broadcast);
4245
+ } catch {
4246
+ watcher = null;
4247
+ }
4248
+ }
4249
+ await new Promise((resolvePromise, reject) => {
4250
+ server.once("error", reject);
4251
+ server.listen(options.port, host, () => resolvePromise());
4252
+ });
4253
+ const address = server.address();
4254
+ const port = typeof address === "object" && address ? address.port : options.port;
4255
+ return {
4256
+ url: `http://${host}:${port}/`,
4257
+ port,
4258
+ close: async () => {
4259
+ watcher?.close();
4260
+ if (debounce) clearTimeout(debounce);
4261
+ for (const client of sseClients) client.end();
4262
+ sseClients.clear();
4263
+ await new Promise((resolvePromise) => server.close(() => resolvePromise()));
4264
+ }
4265
+ };
4266
+ }
4267
+
4268
+ // src/commands/content.ts
4269
+ var UPLOAD_CONCURRENCY = 4;
4270
+ function fmtBytes(n) {
4271
+ if (n < 1024) return `${n} B`;
4272
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
4273
+ return `${(n / (1024 * 1024)).toFixed(1)} MB`;
4274
+ }
4275
+ function toManifest(scan) {
4276
+ return scan.files.map((f) => ({
4277
+ path: f.path,
4278
+ sha256: f.sha256,
4279
+ sizeBytes: f.sizeBytes,
4280
+ contentType: f.contentType
4281
+ }));
4282
+ }
4283
+ async function uploadMissing(ctx, scan) {
4284
+ const shas = [...new Set(scan.files.map((f) => f.sha256))];
4285
+ const { missing } = await ctx.client.precheckAssets(shas);
4286
+ const missingSet = new Set(missing);
4287
+ const queue = [
4288
+ ...new Map(scan.files.filter((f) => missingSet.has(f.sha256)).map((f) => [f.sha256, f])).values()
4289
+ ];
4290
+ let index = 0;
4291
+ const workers = Array.from({ length: Math.min(UPLOAD_CONCURRENCY, queue.length) }, async () => {
4292
+ while (index < queue.length) {
4293
+ const file = queue[index++];
4294
+ const bytes = await readFile3(file.absPath);
4295
+ await ctx.client.uploadAsset(file.sha256, new Uint8Array(bytes), file.contentType);
4296
+ }
4297
+ });
4298
+ await Promise.all(workers);
4299
+ return queue.length;
4300
+ }
4301
+ function safeRelPath(p) {
4302
+ return !p.startsWith("/") && !p.includes("\\") && p.split("/").every((seg) => seg !== "" && seg !== "." && seg !== "..");
4303
+ }
4304
+ function registerContentCommands(program2, io) {
4305
+ program2.command("push [path]").description(
4306
+ `Upload a deck folder (or single HTML file) as a new deck, or as a new version of the deck linked via ${LINK_FILENAME} / --id`
4307
+ ).option("--title <title>", "deck title (default: existing title, or the folder name)").option("--entry <path>", "entry document (default: index.html, or the only .html)").option("--kind <kind>", "presentation | app | plan (new decks only)", "presentation").option("--interactive", "mark the deck as embedding interactive content (new decks only)", false).option("--id <deckId>", "push a new version of this existing deck").option("--new", `force a NEW deck even when ${LINK_FILENAME} links one`, false).action(
4308
+ async (path, opts, cmd) => {
4309
+ const ctx = resolveContext(cmd, io);
4310
+ requireApiKey(ctx);
4311
+ const target = path ?? ".";
4312
+ const scan = await scanDeck(target);
4313
+ const entryPath = detectEntry(scan, opts.entry);
4314
+ const manifest = toManifest(scan);
4315
+ const totalBytes = scan.files.reduce((sum, f) => sum + f.sizeBytes, 0);
4316
+ const link = await readLink(scan.rootDir);
4317
+ let existingId = opts.id ?? null;
4318
+ if (!existingId && !opts.new && link) {
4319
+ if (link.baseUrl === ctx.baseUrl) {
4320
+ existingId = link.presentationId;
4321
+ } else {
4322
+ throw new CliUsageError(
4323
+ `${LINK_FILENAME} links this folder to ${link.baseUrl}, but you are pushing to ${ctx.baseUrl}. Pass --new to create a fresh deck here, or --id <deckId> to target one explicitly.`
4324
+ );
4325
+ }
4326
+ }
4327
+ if (existingId) {
4328
+ const deck = await ctx.client.presentation(existingId);
4329
+ const uploaded2 = await uploadMissing(ctx, scan);
4330
+ let committed2;
4331
+ try {
4332
+ committed2 = await ctx.client.commitVersion(existingId, {
4333
+ expectedBaseVersion: deck.currentVersion,
4334
+ entryPath,
4335
+ manifest,
4336
+ ...opts.title ? { title: opts.title } : {}
4337
+ });
4338
+ } catch (e) {
4339
+ if (e instanceof PlatformApiError && e.code === "version_conflict") {
4340
+ throw new CliUsageError(
4341
+ "Someone pushed a new version while this push was running \u2014 rerun to retry on top of it."
4342
+ );
4343
+ }
4344
+ throw e;
4345
+ }
4346
+ await writeLink(scan.rootDir, { presentationId: existingId, baseUrl: ctx.baseUrl });
4347
+ if (ctx.json) return printJson(io, committed2);
4348
+ io.out.write(
4349
+ `Pushed "${committed2.presentation.title}" \u2192 version ${committed2.version.version} (${scan.files.length} files, ${fmtBytes(totalBytes)}, ${uploaded2} uploaded)
4350
+ id: ${committed2.presentation.id}
4351
+ `
4352
+ );
4353
+ return;
4354
+ }
4355
+ const kind = opts.kind;
4356
+ if (!["presentation", "app", "plan"].includes(kind)) {
4357
+ throw new CliUsageError("--kind must be presentation, app, or plan");
4358
+ }
4359
+ const title = opts.title ?? scan.rootDir.split("/").filter(Boolean).pop() ?? "Untitled deck";
4360
+ const { uploadSession } = await ctx.client.createUploadSession();
4361
+ const uploaded = await uploadMissing(ctx, scan);
4362
+ const committed = await ctx.client.commitUploadSession(uploadSession.id, {
4363
+ title,
4364
+ kind,
4365
+ interactive: opts.interactive,
4366
+ entryPath,
4367
+ manifest
4368
+ });
4369
+ await writeLink(scan.rootDir, {
4370
+ presentationId: committed.presentation.id,
4371
+ baseUrl: ctx.baseUrl
4372
+ });
4373
+ if (ctx.json) return printJson(io, committed);
4374
+ io.out.write(
4375
+ `Created "${committed.presentation.title}" at version 1 (${scan.files.length} files, ${fmtBytes(totalBytes)}, ${uploaded} uploaded)
4376
+ id: ${committed.presentation.id}
4377
+ linked: ${join4(scan.rootDir, LINK_FILENAME)}
4378
+ `
4379
+ );
4380
+ }
4381
+ );
4382
+ program2.command("pull [id] [path]").description(
4383
+ `Download a deck version to a folder (id defaults to the ${LINK_FILENAME} link in the target)`
4384
+ ).option("--at <version>", "pull this version instead of the latest", (v) => parseInt(v, 10)).action(async (id, path, opts, cmd) => {
4385
+ const ctx = resolveContext(cmd, io);
4386
+ requireApiKey(ctx);
4387
+ let deckId = id ?? null;
4388
+ let dest = path ?? null;
4389
+ if (!deckId) {
4390
+ const link = await readLink(resolve3(dest ?? "."));
4391
+ if (!link) {
4392
+ throw new CliUsageError(
4393
+ `No deck id given and no ${LINK_FILENAME} found \u2014 run \`slideless pull <id> [path]\`.`
4394
+ );
4395
+ }
4396
+ deckId = link.presentationId;
4397
+ dest = dest ?? ".";
4398
+ }
4399
+ dest = dest ?? deckId;
4400
+ const deck = await ctx.client.presentation(deckId);
4401
+ const version = opts.at ?? deck.currentVersion;
4402
+ if (version < 1) throw new CliUsageError("This deck has no committed versions yet.");
4403
+ const detail = await ctx.client.presentationVersion(deckId, version);
4404
+ const destRoot = resolve3(dest);
4405
+ await mkdir(destRoot, { recursive: true });
4406
+ for (const entry of detail.manifest) {
4407
+ if (!safeRelPath(entry.path)) {
4408
+ throw new Error(`Refusing to write unsafe manifest path: ${entry.path}`);
4409
+ }
4410
+ const res = await ctx.client.downloadPresentationAsset(deckId, entry.sha256);
4411
+ const bytes = Buffer.from(await res.arrayBuffer());
4412
+ const target = join4(destRoot, entry.path);
4413
+ await mkdir(dirname3(target), { recursive: true });
4414
+ await writeFile2(target, bytes);
4415
+ }
4416
+ await writeLink(destRoot, { presentationId: deckId, baseUrl: ctx.baseUrl });
4417
+ if (ctx.json) {
4418
+ return printJson(io, {
4419
+ presentation: deck,
4420
+ version: detail,
4421
+ path: destRoot,
4422
+ files: detail.manifest.length
4423
+ });
4424
+ }
4425
+ io.out.write(`Pulled "${deck.title}" v${version} \u2192 ${destRoot} (${detail.manifest.length} files)
4426
+ `);
4427
+ });
4428
+ program2.command("pull-annotations [id]").description(`List a deck's annotations (id defaults to the ${LINK_FILENAME} link in .)`).option("--version <n>", "only notes anchored to this version", (v) => parseInt(v, 10)).option("--status <status>", "open | resolved").option("--out <file>", "write the annotations as JSON to this file").action(
4429
+ async (id, opts, cmd) => {
4430
+ const ctx = resolveContext(cmd, io);
4431
+ requireApiKey(ctx);
4432
+ let deckId = id ?? null;
4433
+ if (!deckId) {
4434
+ const link = await readLink(resolve3("."));
4435
+ if (!link) {
4436
+ throw new CliUsageError(`No deck id given and no ${LINK_FILENAME} in the current folder.`);
4437
+ }
4438
+ deckId = link.presentationId;
4439
+ }
4440
+ if (opts.status && opts.status !== "open" && opts.status !== "resolved") {
4441
+ throw new CliUsageError("--status must be open or resolved");
4442
+ }
4443
+ const params = {
4444
+ ...opts.version !== void 0 ? { version: opts.version } : {},
4445
+ ...opts.status ? { status: opts.status } : {}
4446
+ };
4447
+ const rows = [];
4448
+ let cursor = null;
4449
+ do {
4450
+ const page = await ctx.client.annotations(deckId, {
4451
+ ...params,
4452
+ ...cursor ? { cursor } : {}
4453
+ });
4454
+ rows.push(...page.annotations);
4455
+ cursor = page.nextCursor;
4456
+ } while (cursor);
4457
+ if (opts.out) {
4458
+ await writeFile2(resolve3(opts.out), `${JSON.stringify(rows, null, 2)}
4459
+ `);
4460
+ }
4461
+ if (ctx.json) return printJson(io, { annotations: rows });
4462
+ if (rows.length === 0) {
4463
+ io.out.write("No annotations.\n");
4464
+ return;
4465
+ }
4466
+ io.out.write(
4467
+ table(
4468
+ rows.map((a) => [
4469
+ a.id,
4470
+ `v${a.version}`,
4471
+ a.status,
4472
+ a.authorName ?? a.authorUserId ?? "unknown",
4473
+ a.body.length > 60 ? `${a.body.slice(0, 57)}...` : a.body
4474
+ ])
4475
+ )
4476
+ );
4477
+ if (opts.out) io.out.write(`Written to ${opts.out}
4478
+ `);
4479
+ }
4480
+ );
4481
+ program2.command("dev [path]").description(
4482
+ "Serve the deck folder locally with the exact viewer sandbox headers + live reload (no backend)"
4483
+ ).option("--port <n>", "port (default 4173)", (v) => parseInt(v, 10), 4173).option("--entry <path>", "entry document (default: index.html, or the only .html)").option("--no-open", "do not open the browser").action(
4484
+ async (path, opts, cmd) => {
4485
+ const ctx = resolveContextForDev(cmd, io);
4486
+ const target = path ?? ".";
4487
+ const scan = await scanDeck(target);
4488
+ const entryPath = detectEntry(scan, opts.entry);
4489
+ const server = await startDevServer({
4490
+ root: scan.rootDir,
4491
+ entryPath,
4492
+ port: opts.port
4493
+ });
4494
+ if (ctx.json) {
4495
+ io.out.write(`${JSON.stringify({ url: server.url, entry: entryPath })}
4496
+ `);
4497
+ } else {
4498
+ io.out.write(
4499
+ `Serving ${scan.rootDir} at ${server.url} (entry: ${entryPath})
4500
+ Live reload on; sandbox headers match the public viewer. Ctrl-C to stop.
4501
+ `
4502
+ );
4503
+ }
4504
+ if (opts.open) {
4505
+ const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
4506
+ try {
4507
+ spawn(opener, [server.url], { stdio: "ignore", detached: true }).unref();
4508
+ } catch {
4509
+ }
4510
+ }
4511
+ await new Promise((resolvePromise) => {
4512
+ const stop = () => {
4513
+ void server.close().finally(() => resolvePromise());
4514
+ };
4515
+ process.once("SIGINT", stop);
4516
+ process.once("SIGTERM", stop);
4517
+ });
4518
+ }
4519
+ );
4520
+ }
4521
+ function resolveContextForDev(cmd, _io) {
4522
+ const opts = cmd.optsWithGlobals();
4523
+ return { json: Boolean(opts.json) };
4524
+ }
4525
+
4526
+ // src/commands/sharing.ts
4527
+ function shareOptionsOf(opts) {
4528
+ if (opts.expires && Number.isNaN(Date.parse(opts.expires))) {
4529
+ throw new CliUsageError("--expires must be an ISO datetime, e.g. 2026-12-31T23:59:59Z");
4530
+ }
4531
+ return {
4532
+ name: opts.name ?? "cli",
4533
+ versionMode: opts.toVersion !== void 0 ? "pinned" : "latest",
4534
+ ...opts.toVersion !== void 0 ? { pinnedVersion: opts.toVersion } : {},
4535
+ canAnnotate: opts.annotator,
4536
+ ...opts.expires ? { expiresAt: new Date(opts.expires).toISOString() } : {},
4537
+ ...opts.password ? { password: opts.password } : {}
4538
+ };
4539
+ }
4540
+ function registerSharingCommands(program2, io) {
4541
+ program2.command("share <id>").description("Create a per-recipient share link (prints the viewer URL \u2014 shown once)").option("--name <name>", "owner-facing recipient label", "cli").option("--to-version <n>", "pin the recipient to this version", (v) => parseInt(v, 10)).option("--annotator", "let the recipient annotate", false).option("--expires <datetime>", "ISO expiry, e.g. 2026-12-31T23:59:59Z").option("--password <password>", "viewer password (min 4 chars)").action(
4542
+ async (id, opts, cmd) => {
4543
+ const ctx = resolveContext(cmd, io);
4544
+ requireApiKey(ctx);
4545
+ const created = await ctx.client.createShareToken(id, shareOptionsOf(opts));
4546
+ if (ctx.json) return printJson(io, created);
4547
+ io.out.write(
4548
+ `${created.url}
4549
+ token: ${created.shareToken.id} ("${created.shareToken.name}", ${created.shareToken.versionMode}${created.shareToken.pinnedVersion ? ` v${created.shareToken.pinnedVersion}` : ""}${created.shareToken.canAnnotate ? ", annotator" : ""}${created.shareToken.hasPassword ? ", password" : ""})
4550
+ The URL is shown once \u2014 copy it now.
4551
+ `
4552
+ );
4553
+ }
4554
+ );
4555
+ program2.command("unshare <id>").description("Revoke one share token (--token) or ALL active tokens of the deck").option("--token <tokenId>", "revoke only this token").action(async (id, opts, cmd) => {
4556
+ const ctx = resolveContext(cmd, io);
4557
+ requireApiKey(ctx);
4558
+ if (opts.token) {
4559
+ const revoked2 = await ctx.client.revokeShareToken(id, opts.token);
4560
+ if (ctx.json) return printJson(io, revoked2);
4561
+ io.out.write(`Revoked share token ${revoked2.id} ("${revoked2.name}").
4562
+ `);
4563
+ return;
4564
+ }
4565
+ const revoked = [];
4566
+ let cursor = null;
4567
+ do {
4568
+ const page = await ctx.client.shareTokens(id, cursor ? { cursor } : {});
4569
+ for (const token of page.shareTokens) {
4570
+ if (!token.revokedAt) {
4571
+ await ctx.client.revokeShareToken(id, token.id);
4572
+ revoked.push(token.id);
4573
+ }
4574
+ }
4575
+ cursor = page.nextCursor;
4576
+ } while (cursor);
4577
+ if (ctx.json) return printJson(io, { revoked });
4578
+ io.out.write(
4579
+ revoked.length === 0 ? "No active share tokens to revoke.\n" : `Revoked ${revoked.length} share token${revoked.length === 1 ? "" : "s"}.
4580
+ `
4581
+ );
4582
+ });
4583
+ program2.command("share-email <id>").description("Create a personal share link per recipient and email it (one token per address)").requiredOption("--to <email...>", "recipient email(s)").option("--to-version <n>", "pin recipients to this version", (v) => parseInt(v, 10)).option("--annotator", "let recipients annotate", false).option("--expires <datetime>", "ISO expiry").option("--password <password>", "viewer password (tell recipients separately)").option("--message <text>", "personal note included in the email").action(
4584
+ async (id, opts, cmd) => {
4585
+ const ctx = resolveContext(cmd, io);
4586
+ requireApiKey(ctx);
4587
+ const results = [];
4588
+ for (const email of opts.to) {
4589
+ const created = await ctx.client.createShareToken(id, shareOptionsOf({ ...opts, name: email }));
4590
+ const sent = await ctx.client.sendShareToken(id, created.shareToken.id, {
4591
+ email,
4592
+ ...opts.message ? { message: opts.message } : {}
4593
+ });
4594
+ results.push({ email, tokenId: created.shareToken.id, emailSent: sent.emailSent });
4595
+ }
4596
+ if (ctx.json) return printJson(io, { sent: results });
4597
+ io.out.write(
4598
+ table(results.map((r) => [r.email, r.tokenId, r.emailSent ? "sent" : "NOT SENT (no email driver)"]))
4599
+ );
4600
+ }
4601
+ );
4602
+ program2.command("pin <id> <tokenId>").description("Pin a share token to a version, or set it back to following the latest").option("--to-version <n>", "freeze the recipient on this version", (v) => parseInt(v, 10)).option("--latest", "follow the latest version again", false).action(
4603
+ async (id, tokenId, opts, cmd) => {
4604
+ const ctx = resolveContext(cmd, io);
4605
+ requireApiKey(ctx);
4606
+ if (opts.latest === (opts.toVersion !== void 0)) {
4607
+ throw new CliUsageError("Pass exactly one of --to-version <n> or --latest.");
4608
+ }
4609
+ const patch = opts.toVersion !== void 0 ? { versionMode: "pinned", pinnedVersion: opts.toVersion } : { versionMode: "latest" };
4610
+ const updated = await ctx.client.updateShareToken(id, tokenId, patch);
4611
+ if (ctx.json) return printJson(io, updated);
4612
+ io.out.write(
4613
+ updated.versionMode === "pinned" ? `Token ${updated.id} pinned to v${updated.pinnedVersion}.
4614
+ ` : `Token ${updated.id} now follows the latest version.
4615
+ `
4616
+ );
4617
+ }
4618
+ );
4619
+ program2.command("invite <id>").description("Invite a dev collaborator to one deck (prints the claim link)").requiredOption("--email <email>", "invitee email").action(async (id, opts, cmd) => {
4620
+ const ctx = resolveContext(cmd, io);
4621
+ requireApiKey(ctx);
4622
+ const invited = await ctx.client.inviteCollaborator(id, { email: opts.email });
4623
+ if (ctx.json) return printJson(io, invited);
4624
+ io.out.write(
4625
+ `Invited ${opts.email} as a dev collaborator (grant ${invited.collaborator.id}).
4626
+ claim link: ${invited.claimUrl}
4627
+ email: ${invited.emailSent ? "sent" : "NOT sent (no email driver) \u2014 share the link yourself"}
4628
+ `
4629
+ );
4630
+ });
4631
+ program2.command("uninvite <id> <collaboratorId>").description("Revoke a collaborator grant (pending or active)").action(async (id, collaboratorId, _opts, cmd) => {
4632
+ const ctx = resolveContext(cmd, io);
4633
+ requireApiKey(ctx);
4634
+ const revoked = await ctx.client.removeCollaborator(id, collaboratorId);
4635
+ if (ctx.json) return printJson(io, revoked);
4636
+ io.out.write(`Revoked collaborator grant ${revoked.id} (${revoked.email}).
4637
+ `);
4638
+ });
4639
+ }
4640
+
4641
+ // src/commands/files.ts
4642
+ import { createWriteStream } from "node:fs";
4643
+ import { readFile as readFile4, writeFile as writeFile3 } from "node:fs/promises";
4644
+ import { basename as basename2 } from "node:path";
4645
+ import { Readable } from "node:stream";
4646
+ import { pipeline } from "node:stream/promises";
4647
+ function fmtBytes2(n) {
4648
+ if (n < 1024) return `${n} B`;
4649
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
4650
+ return `${(n / (1024 * 1024)).toFixed(1)} MB`;
4651
+ }
4652
+ function registerFileCommands(program2, io) {
4653
+ program2.command("instance").description("Show instance discovery (public: name, version, auth methods)").action(async (_opts, cmd) => {
4654
+ const ctx = resolveContext(cmd, io);
4655
+ const info = await ctx.client.instance();
4656
+ if (ctx.json) return printJson(io, info);
4657
+ io.out.write(
4658
+ `${info.name} v${info.version} (${info.edition})
4659
+ setup required: ${info.setupRequired}
4660
+ auth methods: ${info.auth.methods.join(", ")}
4661
+ `
4662
+ );
4663
+ });
4664
+ program2.command("export").description("Download the full workspace export as a zip (key needs data:export)").option("-o, --out <path>", "write to this path (defaults to export-<date>.zip)").action(async (opts, cmd) => {
4665
+ const ctx = resolveContext(cmd, io);
4666
+ requireApiKey(ctx);
4667
+ const res = await ctx.client.downloadExport();
4668
+ if (!res.body) {
4669
+ throw new Error("The export response carried no body");
4670
+ }
4671
+ const out = opts.out ?? `export-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.zip`;
4672
+ await pipeline(Readable.fromWeb(res.body), createWriteStream(out));
4673
+ if (ctx.json) return printJson(io, { path: out });
4674
+ io.out.write(`Export written to ${out}
4675
+ `);
4676
+ });
4677
+ const files = program2.command("files").description("Manage workspace files");
4678
+ files.command("list").description("List files in the workspace (newest first, cursor-paginated)").option("--cursor <cursor>", "resume from a previous nextCursor").option("--limit <n>", "page size (1-100)", (v) => parseInt(v, 10)).option("--all", "follow nextCursor until every page is fetched", false).action(async (opts, cmd) => {
4679
+ const ctx = resolveContext(cmd, io);
4680
+ requireApiKey(ctx);
4681
+ const params = {};
4682
+ if (opts.cursor) params.cursor = opts.cursor;
4683
+ if (opts.limit !== void 0) params.limit = opts.limit;
4684
+ const first = await ctx.client.files(params);
4685
+ const rows = [...first.files];
4686
+ if (opts.all) {
4687
+ let cursor = first.nextCursor;
4688
+ while (cursor) {
4689
+ const page = await ctx.client.files({ ...params, cursor });
4690
+ rows.push(...page.files);
4691
+ cursor = page.nextCursor;
4692
+ }
4693
+ }
4694
+ const nextCursor = opts.all ? null : first.nextCursor;
4695
+ if (ctx.json) return printJson(io, { files: rows, nextCursor });
4696
+ if (rows.length === 0) {
4697
+ io.out.write("No files.\n");
4698
+ return;
4699
+ }
4700
+ for (const f of rows) {
4701
+ io.out.write(`${f.id} ${fmtBytes2(f.sizeBytes).padStart(9)} ${f.originalName}
4702
+ `);
4703
+ }
4704
+ if (nextCursor) {
4705
+ io.out.write(`More available: rerun with --cursor ${nextCursor} or --all
4706
+ `);
4707
+ }
4708
+ });
4709
+ files.command("upload <path>").description("Upload a local file").option("--name <name>", "stored file name (defaults to the local basename)").option("--content-type <type>", "content type", "application/octet-stream").action(async (path, opts, cmd) => {
4710
+ const ctx = resolveContext(cmd, io);
4711
+ requireApiKey(ctx);
4712
+ const bytes = await readFile4(path);
4713
+ const name = opts.name ?? basename2(path);
4714
+ const result = await ctx.client.uploadFile(name, new Uint8Array(bytes), opts.contentType);
4715
+ if (ctx.json) return printJson(io, result);
4716
+ io.out.write(
4717
+ `Uploaded ${result.file.originalName} (${fmtBytes2(result.file.sizeBytes)})${result.deduplicated ? " [deduplicated]" : ""}
4718
+ id: ${result.file.id}
4719
+ `
4720
+ );
4721
+ });
4722
+ files.command("download <id>").description("Download a file by id").option("--out <path>", "write to this path (defaults to the stored name)").action(async (id, opts, cmd) => {
4723
+ const ctx = resolveContext(cmd, io);
4724
+ const apiKey = requireApiKey(ctx);
4725
+ const meta = await ctx.client.file(id);
4726
+ const fetchImpl = io.fetch ?? globalThis.fetch.bind(globalThis);
4727
+ const res = await fetchImpl(ctx.client.fileContentUrl(id), {
4728
+ headers: { authorization: `Bearer ${apiKey}` }
4729
+ });
4730
+ if (!res.ok) {
4731
+ throw new PlatformApiError(res.status, "download_failed", `Download failed with ${res.status}`);
4732
+ }
4733
+ const buf = Buffer.from(await res.arrayBuffer());
4734
+ const out = opts.out ?? meta.originalName;
4735
+ await writeFile3(out, buf);
4736
+ io.out.write(`Downloaded ${meta.originalName} \u2192 ${out} (${fmtBytes2(buf.length)})
4737
+ `);
4738
+ });
4739
+ files.command("rm <id>").description("Delete a file by id").action(async (id, _opts, cmd) => {
4740
+ const ctx = resolveContext(cmd, io);
4741
+ requireApiKey(ctx);
4742
+ await ctx.client.deleteFile(id);
4743
+ if (ctx.json) return printJson(io, { deleted: id });
4744
+ io.out.write(`Deleted ${id}
4745
+ `);
4746
+ });
4747
+ }
4748
+
4749
+ // src/commands/completion.ts
4750
+ function commandTree(program2) {
4751
+ return program2.commands.filter((c) => !c.name().startsWith("help")).map((c) => ({
4752
+ name: c.name(),
4753
+ subs: c.commands.map((s) => s.name())
4754
+ }));
4755
+ }
4756
+ function bashScript(tree) {
4757
+ const top = tree.map((c) => c.name).join(" ");
4758
+ const cases = tree.filter((c) => c.subs.length > 0).map((c) => ` ${c.name}) COMPREPLY=( $(compgen -W "${c.subs.join(" ")}" -- "$cur") ); return ;;`).join("\n");
4759
+ return `# bash completion for slideless \u2014 eval "$(slideless completion bash)"
4760
+ _slideless_completions() {
4761
+ local cur prev
4762
+ cur="\${COMP_WORDS[COMP_CWORD]}"
4763
+ prev="\${COMP_WORDS[1]}"
4764
+ if [ "$COMP_CWORD" -eq 1 ]; then
4765
+ COMPREPLY=( $(compgen -W "${top}" -- "$cur") )
4766
+ return
4767
+ fi
4768
+ case "$prev" in
4769
+ ${cases}
4770
+ esac
4771
+ }
4772
+ complete -F _slideless_completions slideless
4773
+ `;
4774
+ }
4775
+ function zshScript(tree) {
4776
+ const top = tree.map((c) => c.name).join(" ");
4777
+ const cases = tree.filter((c) => c.subs.length > 0).map((c) => ` ${c.name}) compadd ${c.subs.join(" ")} ;;`).join("\n");
4778
+ return `#compdef slideless
4779
+ # zsh completion for slideless \u2014 eval "$(slideless completion zsh)"
4780
+ _slideless() {
4781
+ if (( CURRENT == 2 )); then
4782
+ compadd ${top}
4783
+ return
4784
+ fi
4785
+ case "\${words[2]}" in
4786
+ ${cases}
4787
+ esac
4788
+ }
4789
+ compdef _slideless slideless
4790
+ `;
4791
+ }
4792
+ function fishScript(tree) {
4793
+ const lines = [
4794
+ "# fish completion for slideless \u2014 slideless completion fish | source",
4795
+ `complete -c slideless -f -n "__fish_use_subcommand" -a "${tree.map((c) => c.name).join(" ")}"`
4796
+ ];
4797
+ for (const c of tree) {
4798
+ if (c.subs.length > 0) {
4799
+ lines.push(
4800
+ `complete -c slideless -f -n "__fish_seen_subcommand_from ${c.name}" -a "${c.subs.join(" ")}"`
4801
+ );
4802
+ }
4803
+ }
4804
+ return `${lines.join("\n")}
4805
+ `;
4806
+ }
4807
+ function registerCompletionCommand(program2, io) {
4808
+ program2.command("completion <shell>").description("Print a completion script for bash, zsh, or fish").action(async (shell) => {
4809
+ const tree = commandTree(program2);
4810
+ switch (shell) {
4811
+ case "bash":
4812
+ io.out.write(bashScript(tree));
4813
+ return;
4814
+ case "zsh":
4815
+ io.out.write(zshScript(tree));
4816
+ return;
4817
+ case "fish":
4818
+ io.out.write(fishScript(tree));
4819
+ return;
4820
+ default:
4821
+ throw new CliUsageError(`Unsupported shell "${shell}" \u2014 bash, zsh, or fish.`);
4822
+ }
4823
+ });
4824
+ }
4825
+
4826
+ // src/index.ts
4827
+ var VERSION = "0.2.0";
4828
+ function buildProgram(io) {
4829
+ const program2 = new Command();
4830
+ program2.name("slideless").description("Command-line client for a Slideless instance (push, share, pull, preview)").version(VERSION).option("--api-url <url>", "instance base URL (or SLIDELESS_URL / profile baseUrl)").option("--url <url>", "alias of --api-url").option("--api-key <key>", "API key (or SLIDELESS_API_KEY / profile apiKey)").option("--profile <name>", "use this saved profile instead of the active one").option("--json", "machine-readable JSON output", false);
4831
+ registerAuthCommands(program2, io);
4832
+ registerDeckCommands(program2, io);
4833
+ registerContentCommands(program2, io);
4834
+ registerSharingCommands(program2, io);
4835
+ registerFileCommands(program2, io);
4836
+ registerCompletionCommand(program2, io);
4837
+ return program2;
4838
+ }
4839
+ async function run(argv, io) {
4840
+ const program2 = buildProgram(io);
4841
+ program2.exitOverride();
4842
+ program2.configureOutput({
4843
+ writeOut: (s) => io.out.write(s),
4844
+ writeErr: (s) => io.err.write(s)
4845
+ });
4846
+ try {
4847
+ await program2.parseAsync(argv, { from: "user" });
4848
+ return 0;
4849
+ } catch (e) {
4850
+ if (e instanceof CommanderError) {
4851
+ return e.exitCode;
4852
+ }
4853
+ if (e instanceof PlatformApiError || e instanceof CliAuthError) {
4854
+ const hint = e.status === 403 ? " (this API key is not allowed to do that)" : e.code === "version_conflict" ? " (someone pushed in between \u2014 rerun to retry)" : e.status === 401 ? " (check the key: `slideless verify`)" : "";
4855
+ io.err.write(`Error: ${e.message}${hint}
4856
+ `);
4857
+ return 1;
4858
+ }
4859
+ if (e instanceof CliUsageError) {
4860
+ io.err.write(`Error: ${e.message}
4861
+ `);
4862
+ return 1;
4863
+ }
4864
+ io.err.write(`Error: ${e instanceof Error ? e.message : String(e)}
4865
+ `);
4866
+ return 1;
4867
+ }
4868
+ }
4869
+
4870
+ // src/bin.ts
4871
+ void run(process.argv.slice(2), {
4872
+ env: process.env,
4873
+ out: process.stdout,
4874
+ err: process.stderr
4875
+ }).then((code) => process.exit(code));