@p11-core/cli 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,4427 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __p11CreateRequire } from "node:module"; const require = __p11CreateRequire(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/commander/lib/error.js
36
+ var require_error = __commonJS({
37
+ "../../node_modules/commander/lib/error.js"(exports) {
38
+ "use strict";
39
+ var CommanderError2 = class extends Error {
40
+ /**
41
+ * Constructs the CommanderError class
42
+ * @param {number} exitCode suggested exit code which could be used with process.exit
43
+ * @param {string} code an id string representing the error
44
+ * @param {string} message human-readable description of the error
45
+ */
46
+ constructor(exitCode, code, message) {
47
+ super(message);
48
+ Error.captureStackTrace(this, this.constructor);
49
+ this.name = this.constructor.name;
50
+ this.code = code;
51
+ this.exitCode = exitCode;
52
+ this.nestedError = void 0;
53
+ }
54
+ };
55
+ var InvalidArgumentError2 = class extends CommanderError2 {
56
+ /**
57
+ * Constructs the InvalidArgumentError class
58
+ * @param {string} [message] explanation of why argument is invalid
59
+ */
60
+ constructor(message) {
61
+ super(1, "commander.invalidArgument", message);
62
+ Error.captureStackTrace(this, this.constructor);
63
+ this.name = this.constructor.name;
64
+ }
65
+ };
66
+ exports.CommanderError = CommanderError2;
67
+ exports.InvalidArgumentError = InvalidArgumentError2;
68
+ }
69
+ });
70
+
71
+ // ../../node_modules/commander/lib/argument.js
72
+ var require_argument = __commonJS({
73
+ "../../node_modules/commander/lib/argument.js"(exports) {
74
+ "use strict";
75
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
76
+ var Argument2 = class {
77
+ /**
78
+ * Initialize a new command argument with the given name and description.
79
+ * The default is that the argument is required, and you can explicitly
80
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
81
+ *
82
+ * @param {string} name
83
+ * @param {string} [description]
84
+ */
85
+ constructor(name, description) {
86
+ this.description = description || "";
87
+ this.variadic = false;
88
+ this.parseArg = void 0;
89
+ this.defaultValue = void 0;
90
+ this.defaultValueDescription = void 0;
91
+ this.argChoices = void 0;
92
+ switch (name[0]) {
93
+ case "<":
94
+ this.required = true;
95
+ this._name = name.slice(1, -1);
96
+ break;
97
+ case "[":
98
+ this.required = false;
99
+ this._name = name.slice(1, -1);
100
+ break;
101
+ default:
102
+ this.required = true;
103
+ this._name = name;
104
+ break;
105
+ }
106
+ if (this._name.endsWith("...")) {
107
+ this.variadic = true;
108
+ this._name = this._name.slice(0, -3);
109
+ }
110
+ }
111
+ /**
112
+ * Return argument name.
113
+ *
114
+ * @return {string}
115
+ */
116
+ name() {
117
+ return this._name;
118
+ }
119
+ /**
120
+ * @package
121
+ */
122
+ _collectValue(value, previous) {
123
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
124
+ return [value];
125
+ }
126
+ previous.push(value);
127
+ return previous;
128
+ }
129
+ /**
130
+ * Set the default value, and optionally supply the description to be displayed in the help.
131
+ *
132
+ * @param {*} value
133
+ * @param {string} [description]
134
+ * @return {Argument}
135
+ */
136
+ default(value, description) {
137
+ this.defaultValue = value;
138
+ this.defaultValueDescription = description;
139
+ return this;
140
+ }
141
+ /**
142
+ * Set the custom handler for processing CLI command arguments into argument values.
143
+ *
144
+ * @param {Function} [fn]
145
+ * @return {Argument}
146
+ */
147
+ argParser(fn) {
148
+ this.parseArg = fn;
149
+ return this;
150
+ }
151
+ /**
152
+ * Only allow argument value to be one of choices.
153
+ *
154
+ * @param {string[]} values
155
+ * @return {Argument}
156
+ */
157
+ choices(values) {
158
+ this.argChoices = values.slice();
159
+ this.parseArg = (arg, previous) => {
160
+ if (!this.argChoices.includes(arg)) {
161
+ throw new InvalidArgumentError2(
162
+ `Allowed choices are ${this.argChoices.join(", ")}.`
163
+ );
164
+ }
165
+ if (this.variadic) {
166
+ return this._collectValue(arg, previous);
167
+ }
168
+ return arg;
169
+ };
170
+ return this;
171
+ }
172
+ /**
173
+ * Make argument required.
174
+ *
175
+ * @returns {Argument}
176
+ */
177
+ argRequired() {
178
+ this.required = true;
179
+ return this;
180
+ }
181
+ /**
182
+ * Make argument optional.
183
+ *
184
+ * @returns {Argument}
185
+ */
186
+ argOptional() {
187
+ this.required = false;
188
+ return this;
189
+ }
190
+ };
191
+ function humanReadableArgName(arg) {
192
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
193
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
194
+ }
195
+ exports.Argument = Argument2;
196
+ exports.humanReadableArgName = humanReadableArgName;
197
+ }
198
+ });
199
+
200
+ // ../../node_modules/commander/lib/help.js
201
+ var require_help = __commonJS({
202
+ "../../node_modules/commander/lib/help.js"(exports) {
203
+ "use strict";
204
+ var { humanReadableArgName } = require_argument();
205
+ var Help2 = class {
206
+ constructor() {
207
+ this.helpWidth = void 0;
208
+ this.minWidthToWrap = 40;
209
+ this.sortSubcommands = false;
210
+ this.sortOptions = false;
211
+ this.showGlobalOptions = false;
212
+ }
213
+ /**
214
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
215
+ * and just before calling `formatHelp()`.
216
+ *
217
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
218
+ *
219
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
220
+ */
221
+ prepareContext(contextOptions) {
222
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
223
+ }
224
+ /**
225
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
226
+ *
227
+ * @param {Command} cmd
228
+ * @returns {Command[]}
229
+ */
230
+ visibleCommands(cmd) {
231
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
232
+ const helpCommand = cmd._getHelpCommand();
233
+ if (helpCommand && !helpCommand._hidden) {
234
+ visibleCommands.push(helpCommand);
235
+ }
236
+ if (this.sortSubcommands) {
237
+ visibleCommands.sort((a, b) => {
238
+ return a.name().localeCompare(b.name());
239
+ });
240
+ }
241
+ return visibleCommands;
242
+ }
243
+ /**
244
+ * Compare options for sort.
245
+ *
246
+ * @param {Option} a
247
+ * @param {Option} b
248
+ * @returns {number}
249
+ */
250
+ compareOptions(a, b) {
251
+ const getSortKey = (option) => {
252
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
253
+ };
254
+ return getSortKey(a).localeCompare(getSortKey(b));
255
+ }
256
+ /**
257
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
258
+ *
259
+ * @param {Command} cmd
260
+ * @returns {Option[]}
261
+ */
262
+ visibleOptions(cmd) {
263
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
264
+ const helpOption = cmd._getHelpOption();
265
+ if (helpOption && !helpOption.hidden) {
266
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
267
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
268
+ if (!removeShort && !removeLong) {
269
+ visibleOptions.push(helpOption);
270
+ } else if (helpOption.long && !removeLong) {
271
+ visibleOptions.push(
272
+ cmd.createOption(helpOption.long, helpOption.description)
273
+ );
274
+ } else if (helpOption.short && !removeShort) {
275
+ visibleOptions.push(
276
+ cmd.createOption(helpOption.short, helpOption.description)
277
+ );
278
+ }
279
+ }
280
+ if (this.sortOptions) {
281
+ visibleOptions.sort(this.compareOptions);
282
+ }
283
+ return visibleOptions;
284
+ }
285
+ /**
286
+ * Get an array of the visible global options. (Not including help.)
287
+ *
288
+ * @param {Command} cmd
289
+ * @returns {Option[]}
290
+ */
291
+ visibleGlobalOptions(cmd) {
292
+ if (!this.showGlobalOptions) return [];
293
+ const globalOptions = [];
294
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
295
+ const visibleOptions = ancestorCmd.options.filter(
296
+ (option) => !option.hidden
297
+ );
298
+ globalOptions.push(...visibleOptions);
299
+ }
300
+ if (this.sortOptions) {
301
+ globalOptions.sort(this.compareOptions);
302
+ }
303
+ return globalOptions;
304
+ }
305
+ /**
306
+ * Get an array of the arguments if any have a description.
307
+ *
308
+ * @param {Command} cmd
309
+ * @returns {Argument[]}
310
+ */
311
+ visibleArguments(cmd) {
312
+ if (cmd._argsDescription) {
313
+ cmd.registeredArguments.forEach((argument) => {
314
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
315
+ });
316
+ }
317
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
318
+ return cmd.registeredArguments;
319
+ }
320
+ return [];
321
+ }
322
+ /**
323
+ * Get the command term to show in the list of subcommands.
324
+ *
325
+ * @param {Command} cmd
326
+ * @returns {string}
327
+ */
328
+ subcommandTerm(cmd) {
329
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
330
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
331
+ (args ? " " + args : "");
332
+ }
333
+ /**
334
+ * Get the option term to show in the list of options.
335
+ *
336
+ * @param {Option} option
337
+ * @returns {string}
338
+ */
339
+ optionTerm(option) {
340
+ return option.flags;
341
+ }
342
+ /**
343
+ * Get the argument term to show in the list of arguments.
344
+ *
345
+ * @param {Argument} argument
346
+ * @returns {string}
347
+ */
348
+ argumentTerm(argument) {
349
+ return argument.name();
350
+ }
351
+ /**
352
+ * Get the longest command term length.
353
+ *
354
+ * @param {Command} cmd
355
+ * @param {Help} helper
356
+ * @returns {number}
357
+ */
358
+ longestSubcommandTermLength(cmd, helper) {
359
+ return helper.visibleCommands(cmd).reduce((max, command) => {
360
+ return Math.max(
361
+ max,
362
+ this.displayWidth(
363
+ helper.styleSubcommandTerm(helper.subcommandTerm(command))
364
+ )
365
+ );
366
+ }, 0);
367
+ }
368
+ /**
369
+ * Get the longest option term length.
370
+ *
371
+ * @param {Command} cmd
372
+ * @param {Help} helper
373
+ * @returns {number}
374
+ */
375
+ longestOptionTermLength(cmd, helper) {
376
+ return helper.visibleOptions(cmd).reduce((max, option) => {
377
+ return Math.max(
378
+ max,
379
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
380
+ );
381
+ }, 0);
382
+ }
383
+ /**
384
+ * Get the longest global option term length.
385
+ *
386
+ * @param {Command} cmd
387
+ * @param {Help} helper
388
+ * @returns {number}
389
+ */
390
+ longestGlobalOptionTermLength(cmd, helper) {
391
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
392
+ return Math.max(
393
+ max,
394
+ this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
395
+ );
396
+ }, 0);
397
+ }
398
+ /**
399
+ * Get the longest argument term length.
400
+ *
401
+ * @param {Command} cmd
402
+ * @param {Help} helper
403
+ * @returns {number}
404
+ */
405
+ longestArgumentTermLength(cmd, helper) {
406
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
407
+ return Math.max(
408
+ max,
409
+ this.displayWidth(
410
+ helper.styleArgumentTerm(helper.argumentTerm(argument))
411
+ )
412
+ );
413
+ }, 0);
414
+ }
415
+ /**
416
+ * Get the command usage to be displayed at the top of the built-in help.
417
+ *
418
+ * @param {Command} cmd
419
+ * @returns {string}
420
+ */
421
+ commandUsage(cmd) {
422
+ let cmdName = cmd._name;
423
+ if (cmd._aliases[0]) {
424
+ cmdName = cmdName + "|" + cmd._aliases[0];
425
+ }
426
+ let ancestorCmdNames = "";
427
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
428
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
429
+ }
430
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
431
+ }
432
+ /**
433
+ * Get the description for the command.
434
+ *
435
+ * @param {Command} cmd
436
+ * @returns {string}
437
+ */
438
+ commandDescription(cmd) {
439
+ return cmd.description();
440
+ }
441
+ /**
442
+ * Get the subcommand summary to show in the list of subcommands.
443
+ * (Fallback to description for backwards compatibility.)
444
+ *
445
+ * @param {Command} cmd
446
+ * @returns {string}
447
+ */
448
+ subcommandDescription(cmd) {
449
+ return cmd.summary() || cmd.description();
450
+ }
451
+ /**
452
+ * Get the option description to show in the list of options.
453
+ *
454
+ * @param {Option} option
455
+ * @return {string}
456
+ */
457
+ optionDescription(option) {
458
+ const extraInfo = [];
459
+ if (option.argChoices) {
460
+ extraInfo.push(
461
+ // use stringify to match the display of the default value
462
+ `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
463
+ );
464
+ }
465
+ if (option.defaultValue !== void 0) {
466
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
467
+ if (showDefault) {
468
+ extraInfo.push(
469
+ `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
470
+ );
471
+ }
472
+ }
473
+ if (option.presetArg !== void 0 && option.optional) {
474
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
475
+ }
476
+ if (option.envVar !== void 0) {
477
+ extraInfo.push(`env: ${option.envVar}`);
478
+ }
479
+ if (extraInfo.length > 0) {
480
+ const extraDescription = `(${extraInfo.join(", ")})`;
481
+ if (option.description) {
482
+ return `${option.description} ${extraDescription}`;
483
+ }
484
+ return extraDescription;
485
+ }
486
+ return option.description;
487
+ }
488
+ /**
489
+ * Get the argument description to show in the list of arguments.
490
+ *
491
+ * @param {Argument} argument
492
+ * @return {string}
493
+ */
494
+ argumentDescription(argument) {
495
+ const extraInfo = [];
496
+ if (argument.argChoices) {
497
+ extraInfo.push(
498
+ // use stringify to match the display of the default value
499
+ `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
500
+ );
501
+ }
502
+ if (argument.defaultValue !== void 0) {
503
+ extraInfo.push(
504
+ `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
505
+ );
506
+ }
507
+ if (extraInfo.length > 0) {
508
+ const extraDescription = `(${extraInfo.join(", ")})`;
509
+ if (argument.description) {
510
+ return `${argument.description} ${extraDescription}`;
511
+ }
512
+ return extraDescription;
513
+ }
514
+ return argument.description;
515
+ }
516
+ /**
517
+ * Format a list of items, given a heading and an array of formatted items.
518
+ *
519
+ * @param {string} heading
520
+ * @param {string[]} items
521
+ * @param {Help} helper
522
+ * @returns string[]
523
+ */
524
+ formatItemList(heading, items, helper) {
525
+ if (items.length === 0) return [];
526
+ return [helper.styleTitle(heading), ...items, ""];
527
+ }
528
+ /**
529
+ * Group items by their help group heading.
530
+ *
531
+ * @param {Command[] | Option[]} unsortedItems
532
+ * @param {Command[] | Option[]} visibleItems
533
+ * @param {Function} getGroup
534
+ * @returns {Map<string, Command[] | Option[]>}
535
+ */
536
+ groupItems(unsortedItems, visibleItems, getGroup) {
537
+ const result = /* @__PURE__ */ new Map();
538
+ unsortedItems.forEach((item) => {
539
+ const group = getGroup(item);
540
+ if (!result.has(group)) result.set(group, []);
541
+ });
542
+ visibleItems.forEach((item) => {
543
+ const group = getGroup(item);
544
+ if (!result.has(group)) {
545
+ result.set(group, []);
546
+ }
547
+ result.get(group).push(item);
548
+ });
549
+ return result;
550
+ }
551
+ /**
552
+ * Generate the built-in help text.
553
+ *
554
+ * @param {Command} cmd
555
+ * @param {Help} helper
556
+ * @returns {string}
557
+ */
558
+ formatHelp(cmd, helper) {
559
+ const termWidth = helper.padWidth(cmd, helper);
560
+ const helpWidth = helper.helpWidth ?? 80;
561
+ function callFormatItem(term, description) {
562
+ return helper.formatItem(term, termWidth, description, helper);
563
+ }
564
+ let output = [
565
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
566
+ ""
567
+ ];
568
+ const commandDescription = helper.commandDescription(cmd);
569
+ if (commandDescription.length > 0) {
570
+ output = output.concat([
571
+ helper.boxWrap(
572
+ helper.styleCommandDescription(commandDescription),
573
+ helpWidth
574
+ ),
575
+ ""
576
+ ]);
577
+ }
578
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
579
+ return callFormatItem(
580
+ helper.styleArgumentTerm(helper.argumentTerm(argument)),
581
+ helper.styleArgumentDescription(helper.argumentDescription(argument))
582
+ );
583
+ });
584
+ output = output.concat(
585
+ this.formatItemList("Arguments:", argumentList, helper)
586
+ );
587
+ const optionGroups = this.groupItems(
588
+ cmd.options,
589
+ helper.visibleOptions(cmd),
590
+ (option) => option.helpGroupHeading ?? "Options:"
591
+ );
592
+ optionGroups.forEach((options, group) => {
593
+ const optionList = options.map((option) => {
594
+ return callFormatItem(
595
+ helper.styleOptionTerm(helper.optionTerm(option)),
596
+ helper.styleOptionDescription(helper.optionDescription(option))
597
+ );
598
+ });
599
+ output = output.concat(this.formatItemList(group, optionList, helper));
600
+ });
601
+ if (helper.showGlobalOptions) {
602
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
603
+ return callFormatItem(
604
+ helper.styleOptionTerm(helper.optionTerm(option)),
605
+ helper.styleOptionDescription(helper.optionDescription(option))
606
+ );
607
+ });
608
+ output = output.concat(
609
+ this.formatItemList("Global Options:", globalOptionList, helper)
610
+ );
611
+ }
612
+ const commandGroups = this.groupItems(
613
+ cmd.commands,
614
+ helper.visibleCommands(cmd),
615
+ (sub) => sub.helpGroup() || "Commands:"
616
+ );
617
+ commandGroups.forEach((commands, group) => {
618
+ const commandList = commands.map((sub) => {
619
+ return callFormatItem(
620
+ helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
621
+ helper.styleSubcommandDescription(helper.subcommandDescription(sub))
622
+ );
623
+ });
624
+ output = output.concat(this.formatItemList(group, commandList, helper));
625
+ });
626
+ return output.join("\n");
627
+ }
628
+ /**
629
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
630
+ *
631
+ * @param {string} str
632
+ * @returns {number}
633
+ */
634
+ displayWidth(str) {
635
+ return stripColor(str).length;
636
+ }
637
+ /**
638
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
639
+ *
640
+ * @param {string} str
641
+ * @returns {string}
642
+ */
643
+ styleTitle(str) {
644
+ return str;
645
+ }
646
+ styleUsage(str) {
647
+ return str.split(" ").map((word) => {
648
+ if (word === "[options]") return this.styleOptionText(word);
649
+ if (word === "[command]") return this.styleSubcommandText(word);
650
+ if (word[0] === "[" || word[0] === "<")
651
+ return this.styleArgumentText(word);
652
+ return this.styleCommandText(word);
653
+ }).join(" ");
654
+ }
655
+ styleCommandDescription(str) {
656
+ return this.styleDescriptionText(str);
657
+ }
658
+ styleOptionDescription(str) {
659
+ return this.styleDescriptionText(str);
660
+ }
661
+ styleSubcommandDescription(str) {
662
+ return this.styleDescriptionText(str);
663
+ }
664
+ styleArgumentDescription(str) {
665
+ return this.styleDescriptionText(str);
666
+ }
667
+ styleDescriptionText(str) {
668
+ return str;
669
+ }
670
+ styleOptionTerm(str) {
671
+ return this.styleOptionText(str);
672
+ }
673
+ styleSubcommandTerm(str) {
674
+ return str.split(" ").map((word) => {
675
+ if (word === "[options]") return this.styleOptionText(word);
676
+ if (word[0] === "[" || word[0] === "<")
677
+ return this.styleArgumentText(word);
678
+ return this.styleSubcommandText(word);
679
+ }).join(" ");
680
+ }
681
+ styleArgumentTerm(str) {
682
+ return this.styleArgumentText(str);
683
+ }
684
+ styleOptionText(str) {
685
+ return str;
686
+ }
687
+ styleArgumentText(str) {
688
+ return str;
689
+ }
690
+ styleSubcommandText(str) {
691
+ return str;
692
+ }
693
+ styleCommandText(str) {
694
+ return str;
695
+ }
696
+ /**
697
+ * Calculate the pad width from the maximum term length.
698
+ *
699
+ * @param {Command} cmd
700
+ * @param {Help} helper
701
+ * @returns {number}
702
+ */
703
+ padWidth(cmd, helper) {
704
+ return Math.max(
705
+ helper.longestOptionTermLength(cmd, helper),
706
+ helper.longestGlobalOptionTermLength(cmd, helper),
707
+ helper.longestSubcommandTermLength(cmd, helper),
708
+ helper.longestArgumentTermLength(cmd, helper)
709
+ );
710
+ }
711
+ /**
712
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
713
+ *
714
+ * @param {string} str
715
+ * @returns {boolean}
716
+ */
717
+ preformatted(str) {
718
+ return /\n[^\S\r\n]/.test(str);
719
+ }
720
+ /**
721
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
722
+ *
723
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
724
+ * TTT DDD DDDD
725
+ * DD DDD
726
+ *
727
+ * @param {string} term
728
+ * @param {number} termWidth
729
+ * @param {string} description
730
+ * @param {Help} helper
731
+ * @returns {string}
732
+ */
733
+ formatItem(term, termWidth, description, helper) {
734
+ const itemIndent = 2;
735
+ const itemIndentStr = " ".repeat(itemIndent);
736
+ if (!description) return itemIndentStr + term;
737
+ const paddedTerm = term.padEnd(
738
+ termWidth + term.length - helper.displayWidth(term)
739
+ );
740
+ const spacerWidth = 2;
741
+ const helpWidth = this.helpWidth ?? 80;
742
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
743
+ let formattedDescription;
744
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
745
+ formattedDescription = description;
746
+ } else {
747
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
748
+ formattedDescription = wrappedDescription.replace(
749
+ /\n/g,
750
+ "\n" + " ".repeat(termWidth + spacerWidth)
751
+ );
752
+ }
753
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
754
+ ${itemIndentStr}`);
755
+ }
756
+ /**
757
+ * Wrap a string at whitespace, preserving existing line breaks.
758
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
759
+ *
760
+ * @param {string} str
761
+ * @param {number} width
762
+ * @returns {string}
763
+ */
764
+ boxWrap(str, width) {
765
+ if (width < this.minWidthToWrap) return str;
766
+ const rawLines = str.split(/\r\n|\n/);
767
+ const chunkPattern = /[\s]*[^\s]+/g;
768
+ const wrappedLines = [];
769
+ rawLines.forEach((line) => {
770
+ const chunks = line.match(chunkPattern);
771
+ if (chunks === null) {
772
+ wrappedLines.push("");
773
+ return;
774
+ }
775
+ let sumChunks = [chunks.shift()];
776
+ let sumWidth = this.displayWidth(sumChunks[0]);
777
+ chunks.forEach((chunk) => {
778
+ const visibleWidth = this.displayWidth(chunk);
779
+ if (sumWidth + visibleWidth <= width) {
780
+ sumChunks.push(chunk);
781
+ sumWidth += visibleWidth;
782
+ return;
783
+ }
784
+ wrappedLines.push(sumChunks.join(""));
785
+ const nextChunk = chunk.trimStart();
786
+ sumChunks = [nextChunk];
787
+ sumWidth = this.displayWidth(nextChunk);
788
+ });
789
+ wrappedLines.push(sumChunks.join(""));
790
+ });
791
+ return wrappedLines.join("\n");
792
+ }
793
+ };
794
+ function stripColor(str) {
795
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
796
+ return str.replace(sgrPattern, "");
797
+ }
798
+ exports.Help = Help2;
799
+ exports.stripColor = stripColor;
800
+ }
801
+ });
802
+
803
+ // ../../node_modules/commander/lib/option.js
804
+ var require_option = __commonJS({
805
+ "../../node_modules/commander/lib/option.js"(exports) {
806
+ "use strict";
807
+ var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
808
+ var Option2 = class {
809
+ /**
810
+ * Initialize a new `Option` with the given `flags` and `description`.
811
+ *
812
+ * @param {string} flags
813
+ * @param {string} [description]
814
+ */
815
+ constructor(flags, description) {
816
+ this.flags = flags;
817
+ this.description = description || "";
818
+ this.required = flags.includes("<");
819
+ this.optional = flags.includes("[");
820
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
821
+ this.mandatory = false;
822
+ const optionFlags = splitOptionFlags(flags);
823
+ this.short = optionFlags.shortFlag;
824
+ this.long = optionFlags.longFlag;
825
+ this.negate = false;
826
+ if (this.long) {
827
+ this.negate = this.long.startsWith("--no-");
828
+ }
829
+ this.defaultValue = void 0;
830
+ this.defaultValueDescription = void 0;
831
+ this.presetArg = void 0;
832
+ this.envVar = void 0;
833
+ this.parseArg = void 0;
834
+ this.hidden = false;
835
+ this.argChoices = void 0;
836
+ this.conflictsWith = [];
837
+ this.implied = void 0;
838
+ this.helpGroupHeading = void 0;
839
+ }
840
+ /**
841
+ * Set the default value, and optionally supply the description to be displayed in the help.
842
+ *
843
+ * @param {*} value
844
+ * @param {string} [description]
845
+ * @return {Option}
846
+ */
847
+ default(value, description) {
848
+ this.defaultValue = value;
849
+ this.defaultValueDescription = description;
850
+ return this;
851
+ }
852
+ /**
853
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
854
+ * The custom processing (parseArg) is called.
855
+ *
856
+ * @example
857
+ * new Option('--color').default('GREYSCALE').preset('RGB');
858
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
859
+ *
860
+ * @param {*} arg
861
+ * @return {Option}
862
+ */
863
+ preset(arg) {
864
+ this.presetArg = arg;
865
+ return this;
866
+ }
867
+ /**
868
+ * Add option name(s) that conflict with this option.
869
+ * An error will be displayed if conflicting options are found during parsing.
870
+ *
871
+ * @example
872
+ * new Option('--rgb').conflicts('cmyk');
873
+ * new Option('--js').conflicts(['ts', 'jsx']);
874
+ *
875
+ * @param {(string | string[])} names
876
+ * @return {Option}
877
+ */
878
+ conflicts(names) {
879
+ this.conflictsWith = this.conflictsWith.concat(names);
880
+ return this;
881
+ }
882
+ /**
883
+ * Specify implied option values for when this option is set and the implied options are not.
884
+ *
885
+ * The custom processing (parseArg) is not called on the implied values.
886
+ *
887
+ * @example
888
+ * program
889
+ * .addOption(new Option('--log', 'write logging information to file'))
890
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
891
+ *
892
+ * @param {object} impliedOptionValues
893
+ * @return {Option}
894
+ */
895
+ implies(impliedOptionValues) {
896
+ let newImplied = impliedOptionValues;
897
+ if (typeof impliedOptionValues === "string") {
898
+ newImplied = { [impliedOptionValues]: true };
899
+ }
900
+ this.implied = Object.assign(this.implied || {}, newImplied);
901
+ return this;
902
+ }
903
+ /**
904
+ * Set environment variable to check for option value.
905
+ *
906
+ * An environment variable is only used if when processed the current option value is
907
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
908
+ *
909
+ * @param {string} name
910
+ * @return {Option}
911
+ */
912
+ env(name) {
913
+ this.envVar = name;
914
+ return this;
915
+ }
916
+ /**
917
+ * Set the custom handler for processing CLI option arguments into option values.
918
+ *
919
+ * @param {Function} [fn]
920
+ * @return {Option}
921
+ */
922
+ argParser(fn) {
923
+ this.parseArg = fn;
924
+ return this;
925
+ }
926
+ /**
927
+ * Whether the option is mandatory and must have a value after parsing.
928
+ *
929
+ * @param {boolean} [mandatory=true]
930
+ * @return {Option}
931
+ */
932
+ makeOptionMandatory(mandatory = true) {
933
+ this.mandatory = !!mandatory;
934
+ return this;
935
+ }
936
+ /**
937
+ * Hide option in help.
938
+ *
939
+ * @param {boolean} [hide=true]
940
+ * @return {Option}
941
+ */
942
+ hideHelp(hide = true) {
943
+ this.hidden = !!hide;
944
+ return this;
945
+ }
946
+ /**
947
+ * @package
948
+ */
949
+ _collectValue(value, previous) {
950
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
951
+ return [value];
952
+ }
953
+ previous.push(value);
954
+ return previous;
955
+ }
956
+ /**
957
+ * Only allow option value to be one of choices.
958
+ *
959
+ * @param {string[]} values
960
+ * @return {Option}
961
+ */
962
+ choices(values) {
963
+ this.argChoices = values.slice();
964
+ this.parseArg = (arg, previous) => {
965
+ if (!this.argChoices.includes(arg)) {
966
+ throw new InvalidArgumentError2(
967
+ `Allowed choices are ${this.argChoices.join(", ")}.`
968
+ );
969
+ }
970
+ if (this.variadic) {
971
+ return this._collectValue(arg, previous);
972
+ }
973
+ return arg;
974
+ };
975
+ return this;
976
+ }
977
+ /**
978
+ * Return option name.
979
+ *
980
+ * @return {string}
981
+ */
982
+ name() {
983
+ if (this.long) {
984
+ return this.long.replace(/^--/, "");
985
+ }
986
+ return this.short.replace(/^-/, "");
987
+ }
988
+ /**
989
+ * Return option name, in a camelcase format that can be used
990
+ * as an object attribute key.
991
+ *
992
+ * @return {string}
993
+ */
994
+ attributeName() {
995
+ if (this.negate) {
996
+ return camelcase(this.name().replace(/^no-/, ""));
997
+ }
998
+ return camelcase(this.name());
999
+ }
1000
+ /**
1001
+ * Set the help group heading.
1002
+ *
1003
+ * @param {string} heading
1004
+ * @return {Option}
1005
+ */
1006
+ helpGroup(heading) {
1007
+ this.helpGroupHeading = heading;
1008
+ return this;
1009
+ }
1010
+ /**
1011
+ * Check if `arg` matches the short or long flag.
1012
+ *
1013
+ * @param {string} arg
1014
+ * @return {boolean}
1015
+ * @package
1016
+ */
1017
+ is(arg) {
1018
+ return this.short === arg || this.long === arg;
1019
+ }
1020
+ /**
1021
+ * Return whether a boolean option.
1022
+ *
1023
+ * Options are one of boolean, negated, required argument, or optional argument.
1024
+ *
1025
+ * @return {boolean}
1026
+ * @package
1027
+ */
1028
+ isBoolean() {
1029
+ return !this.required && !this.optional && !this.negate;
1030
+ }
1031
+ };
1032
+ var DualOptions = class {
1033
+ /**
1034
+ * @param {Option[]} options
1035
+ */
1036
+ constructor(options) {
1037
+ this.positiveOptions = /* @__PURE__ */ new Map();
1038
+ this.negativeOptions = /* @__PURE__ */ new Map();
1039
+ this.dualOptions = /* @__PURE__ */ new Set();
1040
+ options.forEach((option) => {
1041
+ if (option.negate) {
1042
+ this.negativeOptions.set(option.attributeName(), option);
1043
+ } else {
1044
+ this.positiveOptions.set(option.attributeName(), option);
1045
+ }
1046
+ });
1047
+ this.negativeOptions.forEach((value, key) => {
1048
+ if (this.positiveOptions.has(key)) {
1049
+ this.dualOptions.add(key);
1050
+ }
1051
+ });
1052
+ }
1053
+ /**
1054
+ * Did the value come from the option, and not from possible matching dual option?
1055
+ *
1056
+ * @param {*} value
1057
+ * @param {Option} option
1058
+ * @returns {boolean}
1059
+ */
1060
+ valueFromOption(value, option) {
1061
+ const optionKey = option.attributeName();
1062
+ if (!this.dualOptions.has(optionKey)) return true;
1063
+ const preset = this.negativeOptions.get(optionKey).presetArg;
1064
+ const negativeValue = preset !== void 0 ? preset : false;
1065
+ return option.negate === (negativeValue === value);
1066
+ }
1067
+ };
1068
+ function camelcase(str) {
1069
+ return str.split("-").reduce((str2, word) => {
1070
+ return str2 + word[0].toUpperCase() + word.slice(1);
1071
+ });
1072
+ }
1073
+ function splitOptionFlags(flags) {
1074
+ let shortFlag;
1075
+ let longFlag;
1076
+ const shortFlagExp = /^-[^-]$/;
1077
+ const longFlagExp = /^--[^-]/;
1078
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
1079
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1080
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
1081
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
1082
+ shortFlag = flagParts.shift();
1083
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
1084
+ shortFlag = longFlag;
1085
+ longFlag = flagParts.shift();
1086
+ }
1087
+ if (flagParts[0].startsWith("-")) {
1088
+ const unsupportedFlag = flagParts[0];
1089
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
1090
+ if (/^-[^-][^-]/.test(unsupportedFlag))
1091
+ throw new Error(
1092
+ `${baseError}
1093
+ - a short flag is a single dash and a single character
1094
+ - either use a single dash and a single character (for a short flag)
1095
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`
1096
+ );
1097
+ if (shortFlagExp.test(unsupportedFlag))
1098
+ throw new Error(`${baseError}
1099
+ - too many short flags`);
1100
+ if (longFlagExp.test(unsupportedFlag))
1101
+ throw new Error(`${baseError}
1102
+ - too many long flags`);
1103
+ throw new Error(`${baseError}
1104
+ - unrecognised flag format`);
1105
+ }
1106
+ if (shortFlag === void 0 && longFlag === void 0)
1107
+ throw new Error(
1108
+ `option creation failed due to no flags found in '${flags}'.`
1109
+ );
1110
+ return { shortFlag, longFlag };
1111
+ }
1112
+ exports.Option = Option2;
1113
+ exports.DualOptions = DualOptions;
1114
+ }
1115
+ });
1116
+
1117
+ // ../../node_modules/commander/lib/suggestSimilar.js
1118
+ var require_suggestSimilar = __commonJS({
1119
+ "../../node_modules/commander/lib/suggestSimilar.js"(exports) {
1120
+ "use strict";
1121
+ var maxDistance = 3;
1122
+ function editDistance(a, b) {
1123
+ if (Math.abs(a.length - b.length) > maxDistance)
1124
+ return Math.max(a.length, b.length);
1125
+ const d = [];
1126
+ for (let i = 0; i <= a.length; i++) {
1127
+ d[i] = [i];
1128
+ }
1129
+ for (let j = 0; j <= b.length; j++) {
1130
+ d[0][j] = j;
1131
+ }
1132
+ for (let j = 1; j <= b.length; j++) {
1133
+ for (let i = 1; i <= a.length; i++) {
1134
+ let cost = 1;
1135
+ if (a[i - 1] === b[j - 1]) {
1136
+ cost = 0;
1137
+ } else {
1138
+ cost = 1;
1139
+ }
1140
+ d[i][j] = Math.min(
1141
+ d[i - 1][j] + 1,
1142
+ // deletion
1143
+ d[i][j - 1] + 1,
1144
+ // insertion
1145
+ d[i - 1][j - 1] + cost
1146
+ // substitution
1147
+ );
1148
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
1149
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1150
+ }
1151
+ }
1152
+ }
1153
+ return d[a.length][b.length];
1154
+ }
1155
+ function suggestSimilar(word, candidates) {
1156
+ if (!candidates || candidates.length === 0) return "";
1157
+ candidates = Array.from(new Set(candidates));
1158
+ const searchingOptions = word.startsWith("--");
1159
+ if (searchingOptions) {
1160
+ word = word.slice(2);
1161
+ candidates = candidates.map((candidate) => candidate.slice(2));
1162
+ }
1163
+ let similar = [];
1164
+ let bestDistance = maxDistance;
1165
+ const minSimilarity = 0.4;
1166
+ candidates.forEach((candidate) => {
1167
+ if (candidate.length <= 1) return;
1168
+ const distance = editDistance(word, candidate);
1169
+ const length = Math.max(word.length, candidate.length);
1170
+ const similarity = (length - distance) / length;
1171
+ if (similarity > minSimilarity) {
1172
+ if (distance < bestDistance) {
1173
+ bestDistance = distance;
1174
+ similar = [candidate];
1175
+ } else if (distance === bestDistance) {
1176
+ similar.push(candidate);
1177
+ }
1178
+ }
1179
+ });
1180
+ similar.sort((a, b) => a.localeCompare(b));
1181
+ if (searchingOptions) {
1182
+ similar = similar.map((candidate) => `--${candidate}`);
1183
+ }
1184
+ if (similar.length > 1) {
1185
+ return `
1186
+ (Did you mean one of ${similar.join(", ")}?)`;
1187
+ }
1188
+ if (similar.length === 1) {
1189
+ return `
1190
+ (Did you mean ${similar[0]}?)`;
1191
+ }
1192
+ return "";
1193
+ }
1194
+ exports.suggestSimilar = suggestSimilar;
1195
+ }
1196
+ });
1197
+
1198
+ // ../../node_modules/commander/lib/command.js
1199
+ var require_command = __commonJS({
1200
+ "../../node_modules/commander/lib/command.js"(exports) {
1201
+ "use strict";
1202
+ var EventEmitter = __require("events").EventEmitter;
1203
+ var childProcess = __require("child_process");
1204
+ var path2 = __require("path");
1205
+ var fs = __require("fs");
1206
+ var process2 = __require("process");
1207
+ var { Argument: Argument2, humanReadableArgName } = require_argument();
1208
+ var { CommanderError: CommanderError2 } = require_error();
1209
+ var { Help: Help2, stripColor } = require_help();
1210
+ var { Option: Option2, DualOptions } = require_option();
1211
+ var { suggestSimilar } = require_suggestSimilar();
1212
+ var Command2 = class _Command extends EventEmitter {
1213
+ /**
1214
+ * Initialize a new `Command`.
1215
+ *
1216
+ * @param {string} [name]
1217
+ */
1218
+ constructor(name) {
1219
+ super();
1220
+ this.commands = [];
1221
+ this.options = [];
1222
+ this.parent = null;
1223
+ this._allowUnknownOption = false;
1224
+ this._allowExcessArguments = false;
1225
+ this.registeredArguments = [];
1226
+ this._args = this.registeredArguments;
1227
+ this.args = [];
1228
+ this.rawArgs = [];
1229
+ this.processedArgs = [];
1230
+ this._scriptPath = null;
1231
+ this._name = name || "";
1232
+ this._optionValues = {};
1233
+ this._optionValueSources = {};
1234
+ this._storeOptionsAsProperties = false;
1235
+ this._actionHandler = null;
1236
+ this._executableHandler = false;
1237
+ this._executableFile = null;
1238
+ this._executableDir = null;
1239
+ this._defaultCommandName = null;
1240
+ this._exitCallback = null;
1241
+ this._aliases = [];
1242
+ this._combineFlagAndOptionalValue = true;
1243
+ this._description = "";
1244
+ this._summary = "";
1245
+ this._argsDescription = void 0;
1246
+ this._enablePositionalOptions = false;
1247
+ this._passThroughOptions = false;
1248
+ this._lifeCycleHooks = {};
1249
+ this._showHelpAfterError = false;
1250
+ this._showSuggestionAfterError = true;
1251
+ this._savedState = null;
1252
+ this._outputConfiguration = {
1253
+ writeOut: (str) => process2.stdout.write(str),
1254
+ writeErr: (str) => process2.stderr.write(str),
1255
+ outputError: (str, write) => write(str),
1256
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
1257
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
1258
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
1259
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
1260
+ stripColor: (str) => stripColor(str)
1261
+ };
1262
+ this._hidden = false;
1263
+ this._helpOption = void 0;
1264
+ this._addImplicitHelpCommand = void 0;
1265
+ this._helpCommand = void 0;
1266
+ this._helpConfiguration = {};
1267
+ this._helpGroupHeading = void 0;
1268
+ this._defaultCommandGroup = void 0;
1269
+ this._defaultOptionGroup = void 0;
1270
+ }
1271
+ /**
1272
+ * Copy settings that are useful to have in common across root command and subcommands.
1273
+ *
1274
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1275
+ *
1276
+ * @param {Command} sourceCommand
1277
+ * @return {Command} `this` command for chaining
1278
+ */
1279
+ copyInheritedSettings(sourceCommand) {
1280
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1281
+ this._helpOption = sourceCommand._helpOption;
1282
+ this._helpCommand = sourceCommand._helpCommand;
1283
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1284
+ this._exitCallback = sourceCommand._exitCallback;
1285
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1286
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1287
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1288
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1289
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1290
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1291
+ return this;
1292
+ }
1293
+ /**
1294
+ * @returns {Command[]}
1295
+ * @private
1296
+ */
1297
+ _getCommandAndAncestors() {
1298
+ const result = [];
1299
+ for (let command = this; command; command = command.parent) {
1300
+ result.push(command);
1301
+ }
1302
+ return result;
1303
+ }
1304
+ /**
1305
+ * Define a command.
1306
+ *
1307
+ * There are two styles of command: pay attention to where to put the description.
1308
+ *
1309
+ * @example
1310
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1311
+ * program
1312
+ * .command('clone <source> [destination]')
1313
+ * .description('clone a repository into a newly created directory')
1314
+ * .action((source, destination) => {
1315
+ * console.log('clone command called');
1316
+ * });
1317
+ *
1318
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1319
+ * program
1320
+ * .command('start <service>', 'start named service')
1321
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1322
+ *
1323
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1324
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1325
+ * @param {object} [execOpts] - configuration options (for executable)
1326
+ * @return {Command} returns new command for action handler, or `this` for executable command
1327
+ */
1328
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1329
+ let desc = actionOptsOrExecDesc;
1330
+ let opts = execOpts;
1331
+ if (typeof desc === "object" && desc !== null) {
1332
+ opts = desc;
1333
+ desc = null;
1334
+ }
1335
+ opts = opts || {};
1336
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1337
+ const cmd = this.createCommand(name);
1338
+ if (desc) {
1339
+ cmd.description(desc);
1340
+ cmd._executableHandler = true;
1341
+ }
1342
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1343
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1344
+ cmd._executableFile = opts.executableFile || null;
1345
+ if (args) cmd.arguments(args);
1346
+ this._registerCommand(cmd);
1347
+ cmd.parent = this;
1348
+ cmd.copyInheritedSettings(this);
1349
+ if (desc) return this;
1350
+ return cmd;
1351
+ }
1352
+ /**
1353
+ * Factory routine to create a new unattached command.
1354
+ *
1355
+ * See .command() for creating an attached subcommand, which uses this routine to
1356
+ * create the command. You can override createCommand to customise subcommands.
1357
+ *
1358
+ * @param {string} [name]
1359
+ * @return {Command} new command
1360
+ */
1361
+ createCommand(name) {
1362
+ return new _Command(name);
1363
+ }
1364
+ /**
1365
+ * You can customise the help with a subclass of Help by overriding createHelp,
1366
+ * or by overriding Help properties using configureHelp().
1367
+ *
1368
+ * @return {Help}
1369
+ */
1370
+ createHelp() {
1371
+ return Object.assign(new Help2(), this.configureHelp());
1372
+ }
1373
+ /**
1374
+ * You can customise the help by overriding Help properties using configureHelp(),
1375
+ * or with a subclass of Help by overriding createHelp().
1376
+ *
1377
+ * @param {object} [configuration] - configuration options
1378
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1379
+ */
1380
+ configureHelp(configuration) {
1381
+ if (configuration === void 0) return this._helpConfiguration;
1382
+ this._helpConfiguration = configuration;
1383
+ return this;
1384
+ }
1385
+ /**
1386
+ * The default output goes to stdout and stderr. You can customise this for special
1387
+ * applications. You can also customise the display of errors by overriding outputError.
1388
+ *
1389
+ * The configuration properties are all functions:
1390
+ *
1391
+ * // change how output being written, defaults to stdout and stderr
1392
+ * writeOut(str)
1393
+ * writeErr(str)
1394
+ * // change how output being written for errors, defaults to writeErr
1395
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1396
+ * // specify width for wrapping help
1397
+ * getOutHelpWidth()
1398
+ * getErrHelpWidth()
1399
+ * // color support, currently only used with Help
1400
+ * getOutHasColors()
1401
+ * getErrHasColors()
1402
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1403
+ *
1404
+ * @param {object} [configuration] - configuration options
1405
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1406
+ */
1407
+ configureOutput(configuration) {
1408
+ if (configuration === void 0) return this._outputConfiguration;
1409
+ this._outputConfiguration = {
1410
+ ...this._outputConfiguration,
1411
+ ...configuration
1412
+ };
1413
+ return this;
1414
+ }
1415
+ /**
1416
+ * Display the help or a custom message after an error occurs.
1417
+ *
1418
+ * @param {(boolean|string)} [displayHelp]
1419
+ * @return {Command} `this` command for chaining
1420
+ */
1421
+ showHelpAfterError(displayHelp = true) {
1422
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1423
+ this._showHelpAfterError = displayHelp;
1424
+ return this;
1425
+ }
1426
+ /**
1427
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1428
+ *
1429
+ * @param {boolean} [displaySuggestion]
1430
+ * @return {Command} `this` command for chaining
1431
+ */
1432
+ showSuggestionAfterError(displaySuggestion = true) {
1433
+ this._showSuggestionAfterError = !!displaySuggestion;
1434
+ return this;
1435
+ }
1436
+ /**
1437
+ * Add a prepared subcommand.
1438
+ *
1439
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1440
+ *
1441
+ * @param {Command} cmd - new subcommand
1442
+ * @param {object} [opts] - configuration options
1443
+ * @return {Command} `this` command for chaining
1444
+ */
1445
+ addCommand(cmd, opts) {
1446
+ if (!cmd._name) {
1447
+ throw new Error(`Command passed to .addCommand() must have a name
1448
+ - specify the name in Command constructor or using .name()`);
1449
+ }
1450
+ opts = opts || {};
1451
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1452
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1453
+ this._registerCommand(cmd);
1454
+ cmd.parent = this;
1455
+ cmd._checkForBrokenPassThrough();
1456
+ return this;
1457
+ }
1458
+ /**
1459
+ * Factory routine to create a new unattached argument.
1460
+ *
1461
+ * See .argument() for creating an attached argument, which uses this routine to
1462
+ * create the argument. You can override createArgument to return a custom argument.
1463
+ *
1464
+ * @param {string} name
1465
+ * @param {string} [description]
1466
+ * @return {Argument} new argument
1467
+ */
1468
+ createArgument(name, description) {
1469
+ return new Argument2(name, description);
1470
+ }
1471
+ /**
1472
+ * Define argument syntax for command.
1473
+ *
1474
+ * The default is that the argument is required, and you can explicitly
1475
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1476
+ *
1477
+ * @example
1478
+ * program.argument('<input-file>');
1479
+ * program.argument('[output-file]');
1480
+ *
1481
+ * @param {string} name
1482
+ * @param {string} [description]
1483
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1484
+ * @param {*} [defaultValue]
1485
+ * @return {Command} `this` command for chaining
1486
+ */
1487
+ argument(name, description, parseArg, defaultValue) {
1488
+ const argument = this.createArgument(name, description);
1489
+ if (typeof parseArg === "function") {
1490
+ argument.default(defaultValue).argParser(parseArg);
1491
+ } else {
1492
+ argument.default(parseArg);
1493
+ }
1494
+ this.addArgument(argument);
1495
+ return this;
1496
+ }
1497
+ /**
1498
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1499
+ *
1500
+ * See also .argument().
1501
+ *
1502
+ * @example
1503
+ * program.arguments('<cmd> [env]');
1504
+ *
1505
+ * @param {string} names
1506
+ * @return {Command} `this` command for chaining
1507
+ */
1508
+ arguments(names) {
1509
+ names.trim().split(/ +/).forEach((detail) => {
1510
+ this.argument(detail);
1511
+ });
1512
+ return this;
1513
+ }
1514
+ /**
1515
+ * Define argument syntax for command, adding a prepared argument.
1516
+ *
1517
+ * @param {Argument} argument
1518
+ * @return {Command} `this` command for chaining
1519
+ */
1520
+ addArgument(argument) {
1521
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1522
+ if (previousArgument?.variadic) {
1523
+ throw new Error(
1524
+ `only the last argument can be variadic '${previousArgument.name()}'`
1525
+ );
1526
+ }
1527
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1528
+ throw new Error(
1529
+ `a default value for a required argument is never used: '${argument.name()}'`
1530
+ );
1531
+ }
1532
+ this.registeredArguments.push(argument);
1533
+ return this;
1534
+ }
1535
+ /**
1536
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1537
+ *
1538
+ * @example
1539
+ * program.helpCommand('help [cmd]');
1540
+ * program.helpCommand('help [cmd]', 'show help');
1541
+ * program.helpCommand(false); // suppress default help command
1542
+ * program.helpCommand(true); // add help command even if no subcommands
1543
+ *
1544
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1545
+ * @param {string} [description] - custom description
1546
+ * @return {Command} `this` command for chaining
1547
+ */
1548
+ helpCommand(enableOrNameAndArgs, description) {
1549
+ if (typeof enableOrNameAndArgs === "boolean") {
1550
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1551
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
1552
+ this._initCommandGroup(this._getHelpCommand());
1553
+ }
1554
+ return this;
1555
+ }
1556
+ const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
1557
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
1558
+ const helpDescription = description ?? "display help for command";
1559
+ const helpCommand = this.createCommand(helpName);
1560
+ helpCommand.helpOption(false);
1561
+ if (helpArgs) helpCommand.arguments(helpArgs);
1562
+ if (helpDescription) helpCommand.description(helpDescription);
1563
+ this._addImplicitHelpCommand = true;
1564
+ this._helpCommand = helpCommand;
1565
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1566
+ return this;
1567
+ }
1568
+ /**
1569
+ * Add prepared custom help command.
1570
+ *
1571
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1572
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1573
+ * @return {Command} `this` command for chaining
1574
+ */
1575
+ addHelpCommand(helpCommand, deprecatedDescription) {
1576
+ if (typeof helpCommand !== "object") {
1577
+ this.helpCommand(helpCommand, deprecatedDescription);
1578
+ return this;
1579
+ }
1580
+ this._addImplicitHelpCommand = true;
1581
+ this._helpCommand = helpCommand;
1582
+ this._initCommandGroup(helpCommand);
1583
+ return this;
1584
+ }
1585
+ /**
1586
+ * Lazy create help command.
1587
+ *
1588
+ * @return {(Command|null)}
1589
+ * @package
1590
+ */
1591
+ _getHelpCommand() {
1592
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1593
+ if (hasImplicitHelpCommand) {
1594
+ if (this._helpCommand === void 0) {
1595
+ this.helpCommand(void 0, void 0);
1596
+ }
1597
+ return this._helpCommand;
1598
+ }
1599
+ return null;
1600
+ }
1601
+ /**
1602
+ * Add hook for life cycle event.
1603
+ *
1604
+ * @param {string} event
1605
+ * @param {Function} listener
1606
+ * @return {Command} `this` command for chaining
1607
+ */
1608
+ hook(event, listener) {
1609
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
1610
+ if (!allowedValues.includes(event)) {
1611
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
1612
+ Expecting one of '${allowedValues.join("', '")}'`);
1613
+ }
1614
+ if (this._lifeCycleHooks[event]) {
1615
+ this._lifeCycleHooks[event].push(listener);
1616
+ } else {
1617
+ this._lifeCycleHooks[event] = [listener];
1618
+ }
1619
+ return this;
1620
+ }
1621
+ /**
1622
+ * Register callback to use as replacement for calling process.exit.
1623
+ *
1624
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1625
+ * @return {Command} `this` command for chaining
1626
+ */
1627
+ exitOverride(fn) {
1628
+ if (fn) {
1629
+ this._exitCallback = fn;
1630
+ } else {
1631
+ this._exitCallback = (err) => {
1632
+ if (err.code !== "commander.executeSubCommandAsync") {
1633
+ throw err;
1634
+ } else {
1635
+ }
1636
+ };
1637
+ }
1638
+ return this;
1639
+ }
1640
+ /**
1641
+ * Call process.exit, and _exitCallback if defined.
1642
+ *
1643
+ * @param {number} exitCode exit code for using with process.exit
1644
+ * @param {string} code an id string representing the error
1645
+ * @param {string} message human-readable description of the error
1646
+ * @return never
1647
+ * @private
1648
+ */
1649
+ _exit(exitCode, code, message) {
1650
+ if (this._exitCallback) {
1651
+ this._exitCallback(new CommanderError2(exitCode, code, message));
1652
+ }
1653
+ process2.exit(exitCode);
1654
+ }
1655
+ /**
1656
+ * Register callback `fn` for the command.
1657
+ *
1658
+ * @example
1659
+ * program
1660
+ * .command('serve')
1661
+ * .description('start service')
1662
+ * .action(function() {
1663
+ * // do work here
1664
+ * });
1665
+ *
1666
+ * @param {Function} fn
1667
+ * @return {Command} `this` command for chaining
1668
+ */
1669
+ action(fn) {
1670
+ const listener = (args) => {
1671
+ const expectedArgsCount = this.registeredArguments.length;
1672
+ const actionArgs = args.slice(0, expectedArgsCount);
1673
+ if (this._storeOptionsAsProperties) {
1674
+ actionArgs[expectedArgsCount] = this;
1675
+ } else {
1676
+ actionArgs[expectedArgsCount] = this.opts();
1677
+ }
1678
+ actionArgs.push(this);
1679
+ return fn.apply(this, actionArgs);
1680
+ };
1681
+ this._actionHandler = listener;
1682
+ return this;
1683
+ }
1684
+ /**
1685
+ * Factory routine to create a new unattached option.
1686
+ *
1687
+ * See .option() for creating an attached option, which uses this routine to
1688
+ * create the option. You can override createOption to return a custom option.
1689
+ *
1690
+ * @param {string} flags
1691
+ * @param {string} [description]
1692
+ * @return {Option} new option
1693
+ */
1694
+ createOption(flags, description) {
1695
+ return new Option2(flags, description);
1696
+ }
1697
+ /**
1698
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1699
+ *
1700
+ * @param {(Option | Argument)} target
1701
+ * @param {string} value
1702
+ * @param {*} previous
1703
+ * @param {string} invalidArgumentMessage
1704
+ * @private
1705
+ */
1706
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1707
+ try {
1708
+ return target.parseArg(value, previous);
1709
+ } catch (err) {
1710
+ if (err.code === "commander.invalidArgument") {
1711
+ const message = `${invalidArgumentMessage} ${err.message}`;
1712
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1713
+ }
1714
+ throw err;
1715
+ }
1716
+ }
1717
+ /**
1718
+ * Check for option flag conflicts.
1719
+ * Register option if no conflicts found, or throw on conflict.
1720
+ *
1721
+ * @param {Option} option
1722
+ * @private
1723
+ */
1724
+ _registerOption(option) {
1725
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1726
+ if (matchingOption) {
1727
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1728
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1729
+ - already used by option '${matchingOption.flags}'`);
1730
+ }
1731
+ this._initOptionGroup(option);
1732
+ this.options.push(option);
1733
+ }
1734
+ /**
1735
+ * Check for command name and alias conflicts with existing commands.
1736
+ * Register command if no conflicts found, or throw on conflict.
1737
+ *
1738
+ * @param {Command} command
1739
+ * @private
1740
+ */
1741
+ _registerCommand(command) {
1742
+ const knownBy = (cmd) => {
1743
+ return [cmd.name()].concat(cmd.aliases());
1744
+ };
1745
+ const alreadyUsed = knownBy(command).find(
1746
+ (name) => this._findCommand(name)
1747
+ );
1748
+ if (alreadyUsed) {
1749
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1750
+ const newCmd = knownBy(command).join("|");
1751
+ throw new Error(
1752
+ `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1753
+ );
1754
+ }
1755
+ this._initCommandGroup(command);
1756
+ this.commands.push(command);
1757
+ }
1758
+ /**
1759
+ * Add an option.
1760
+ *
1761
+ * @param {Option} option
1762
+ * @return {Command} `this` command for chaining
1763
+ */
1764
+ addOption(option) {
1765
+ this._registerOption(option);
1766
+ const oname = option.name();
1767
+ const name = option.attributeName();
1768
+ if (option.negate) {
1769
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1770
+ if (!this._findOption(positiveLongFlag)) {
1771
+ this.setOptionValueWithSource(
1772
+ name,
1773
+ option.defaultValue === void 0 ? true : option.defaultValue,
1774
+ "default"
1775
+ );
1776
+ }
1777
+ } else if (option.defaultValue !== void 0) {
1778
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1779
+ }
1780
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1781
+ if (val == null && option.presetArg !== void 0) {
1782
+ val = option.presetArg;
1783
+ }
1784
+ const oldValue = this.getOptionValue(name);
1785
+ if (val !== null && option.parseArg) {
1786
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1787
+ } else if (val !== null && option.variadic) {
1788
+ val = option._collectValue(val, oldValue);
1789
+ }
1790
+ if (val == null) {
1791
+ if (option.negate) {
1792
+ val = false;
1793
+ } else if (option.isBoolean() || option.optional) {
1794
+ val = true;
1795
+ } else {
1796
+ val = "";
1797
+ }
1798
+ }
1799
+ this.setOptionValueWithSource(name, val, valueSource);
1800
+ };
1801
+ this.on("option:" + oname, (val) => {
1802
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1803
+ handleOptionValue(val, invalidValueMessage, "cli");
1804
+ });
1805
+ if (option.envVar) {
1806
+ this.on("optionEnv:" + oname, (val) => {
1807
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1808
+ handleOptionValue(val, invalidValueMessage, "env");
1809
+ });
1810
+ }
1811
+ return this;
1812
+ }
1813
+ /**
1814
+ * Internal implementation shared by .option() and .requiredOption()
1815
+ *
1816
+ * @return {Command} `this` command for chaining
1817
+ * @private
1818
+ */
1819
+ _optionEx(config, flags, description, fn, defaultValue) {
1820
+ if (typeof flags === "object" && flags instanceof Option2) {
1821
+ throw new Error(
1822
+ "To add an Option object use addOption() instead of option() or requiredOption()"
1823
+ );
1824
+ }
1825
+ const option = this.createOption(flags, description);
1826
+ option.makeOptionMandatory(!!config.mandatory);
1827
+ if (typeof fn === "function") {
1828
+ option.default(defaultValue).argParser(fn);
1829
+ } else if (fn instanceof RegExp) {
1830
+ const regex = fn;
1831
+ fn = (val, def) => {
1832
+ const m = regex.exec(val);
1833
+ return m ? m[0] : def;
1834
+ };
1835
+ option.default(defaultValue).argParser(fn);
1836
+ } else {
1837
+ option.default(fn);
1838
+ }
1839
+ return this.addOption(option);
1840
+ }
1841
+ /**
1842
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1843
+ *
1844
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1845
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1846
+ *
1847
+ * See the README for more details, and see also addOption() and requiredOption().
1848
+ *
1849
+ * @example
1850
+ * program
1851
+ * .option('-p, --pepper', 'add pepper')
1852
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1853
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1854
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1855
+ *
1856
+ * @param {string} flags
1857
+ * @param {string} [description]
1858
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1859
+ * @param {*} [defaultValue]
1860
+ * @return {Command} `this` command for chaining
1861
+ */
1862
+ option(flags, description, parseArg, defaultValue) {
1863
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1864
+ }
1865
+ /**
1866
+ * Add a required option which must have a value after parsing. This usually means
1867
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1868
+ *
1869
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1870
+ *
1871
+ * @param {string} flags
1872
+ * @param {string} [description]
1873
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1874
+ * @param {*} [defaultValue]
1875
+ * @return {Command} `this` command for chaining
1876
+ */
1877
+ requiredOption(flags, description, parseArg, defaultValue) {
1878
+ return this._optionEx(
1879
+ { mandatory: true },
1880
+ flags,
1881
+ description,
1882
+ parseArg,
1883
+ defaultValue
1884
+ );
1885
+ }
1886
+ /**
1887
+ * Alter parsing of short flags with optional values.
1888
+ *
1889
+ * @example
1890
+ * // for `.option('-f,--flag [value]'):
1891
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1892
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1893
+ *
1894
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1895
+ * @return {Command} `this` command for chaining
1896
+ */
1897
+ combineFlagAndOptionalValue(combine = true) {
1898
+ this._combineFlagAndOptionalValue = !!combine;
1899
+ return this;
1900
+ }
1901
+ /**
1902
+ * Allow unknown options on the command line.
1903
+ *
1904
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1905
+ * @return {Command} `this` command for chaining
1906
+ */
1907
+ allowUnknownOption(allowUnknown = true) {
1908
+ this._allowUnknownOption = !!allowUnknown;
1909
+ return this;
1910
+ }
1911
+ /**
1912
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1913
+ *
1914
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1915
+ * @return {Command} `this` command for chaining
1916
+ */
1917
+ allowExcessArguments(allowExcess = true) {
1918
+ this._allowExcessArguments = !!allowExcess;
1919
+ return this;
1920
+ }
1921
+ /**
1922
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1923
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1924
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1925
+ *
1926
+ * @param {boolean} [positional]
1927
+ * @return {Command} `this` command for chaining
1928
+ */
1929
+ enablePositionalOptions(positional = true) {
1930
+ this._enablePositionalOptions = !!positional;
1931
+ return this;
1932
+ }
1933
+ /**
1934
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1935
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1936
+ * positional options to have been enabled on the program (parent commands).
1937
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1938
+ *
1939
+ * @param {boolean} [passThrough] for unknown options.
1940
+ * @return {Command} `this` command for chaining
1941
+ */
1942
+ passThroughOptions(passThrough = true) {
1943
+ this._passThroughOptions = !!passThrough;
1944
+ this._checkForBrokenPassThrough();
1945
+ return this;
1946
+ }
1947
+ /**
1948
+ * @private
1949
+ */
1950
+ _checkForBrokenPassThrough() {
1951
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1952
+ throw new Error(
1953
+ `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
1954
+ );
1955
+ }
1956
+ }
1957
+ /**
1958
+ * Whether to store option values as properties on command object,
1959
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1960
+ *
1961
+ * @param {boolean} [storeAsProperties=true]
1962
+ * @return {Command} `this` command for chaining
1963
+ */
1964
+ storeOptionsAsProperties(storeAsProperties = true) {
1965
+ if (this.options.length) {
1966
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1967
+ }
1968
+ if (Object.keys(this._optionValues).length) {
1969
+ throw new Error(
1970
+ "call .storeOptionsAsProperties() before setting option values"
1971
+ );
1972
+ }
1973
+ this._storeOptionsAsProperties = !!storeAsProperties;
1974
+ return this;
1975
+ }
1976
+ /**
1977
+ * Retrieve option value.
1978
+ *
1979
+ * @param {string} key
1980
+ * @return {object} value
1981
+ */
1982
+ getOptionValue(key) {
1983
+ if (this._storeOptionsAsProperties) {
1984
+ return this[key];
1985
+ }
1986
+ return this._optionValues[key];
1987
+ }
1988
+ /**
1989
+ * Store option value.
1990
+ *
1991
+ * @param {string} key
1992
+ * @param {object} value
1993
+ * @return {Command} `this` command for chaining
1994
+ */
1995
+ setOptionValue(key, value) {
1996
+ return this.setOptionValueWithSource(key, value, void 0);
1997
+ }
1998
+ /**
1999
+ * Store option value and where the value came from.
2000
+ *
2001
+ * @param {string} key
2002
+ * @param {object} value
2003
+ * @param {string} source - expected values are default/config/env/cli/implied
2004
+ * @return {Command} `this` command for chaining
2005
+ */
2006
+ setOptionValueWithSource(key, value, source) {
2007
+ if (this._storeOptionsAsProperties) {
2008
+ this[key] = value;
2009
+ } else {
2010
+ this._optionValues[key] = value;
2011
+ }
2012
+ this._optionValueSources[key] = source;
2013
+ return this;
2014
+ }
2015
+ /**
2016
+ * Get source of option value.
2017
+ * Expected values are default | config | env | cli | implied
2018
+ *
2019
+ * @param {string} key
2020
+ * @return {string}
2021
+ */
2022
+ getOptionValueSource(key) {
2023
+ return this._optionValueSources[key];
2024
+ }
2025
+ /**
2026
+ * Get source of option value. See also .optsWithGlobals().
2027
+ * Expected values are default | config | env | cli | implied
2028
+ *
2029
+ * @param {string} key
2030
+ * @return {string}
2031
+ */
2032
+ getOptionValueSourceWithGlobals(key) {
2033
+ let source;
2034
+ this._getCommandAndAncestors().forEach((cmd) => {
2035
+ if (cmd.getOptionValueSource(key) !== void 0) {
2036
+ source = cmd.getOptionValueSource(key);
2037
+ }
2038
+ });
2039
+ return source;
2040
+ }
2041
+ /**
2042
+ * Get user arguments from implied or explicit arguments.
2043
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
2044
+ *
2045
+ * @private
2046
+ */
2047
+ _prepareUserArgs(argv, parseOptions) {
2048
+ if (argv !== void 0 && !Array.isArray(argv)) {
2049
+ throw new Error("first parameter to parse must be array or undefined");
2050
+ }
2051
+ parseOptions = parseOptions || {};
2052
+ if (argv === void 0 && parseOptions.from === void 0) {
2053
+ if (process2.versions?.electron) {
2054
+ parseOptions.from = "electron";
2055
+ }
2056
+ const execArgv = process2.execArgv ?? [];
2057
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
2058
+ parseOptions.from = "eval";
2059
+ }
2060
+ }
2061
+ if (argv === void 0) {
2062
+ argv = process2.argv;
2063
+ }
2064
+ this.rawArgs = argv.slice();
2065
+ let userArgs;
2066
+ switch (parseOptions.from) {
2067
+ case void 0:
2068
+ case "node":
2069
+ this._scriptPath = argv[1];
2070
+ userArgs = argv.slice(2);
2071
+ break;
2072
+ case "electron":
2073
+ if (process2.defaultApp) {
2074
+ this._scriptPath = argv[1];
2075
+ userArgs = argv.slice(2);
2076
+ } else {
2077
+ userArgs = argv.slice(1);
2078
+ }
2079
+ break;
2080
+ case "user":
2081
+ userArgs = argv.slice(0);
2082
+ break;
2083
+ case "eval":
2084
+ userArgs = argv.slice(1);
2085
+ break;
2086
+ default:
2087
+ throw new Error(
2088
+ `unexpected parse option { from: '${parseOptions.from}' }`
2089
+ );
2090
+ }
2091
+ if (!this._name && this._scriptPath)
2092
+ this.nameFromFilename(this._scriptPath);
2093
+ this._name = this._name || "program";
2094
+ return userArgs;
2095
+ }
2096
+ /**
2097
+ * Parse `argv`, setting options and invoking commands when defined.
2098
+ *
2099
+ * Use parseAsync instead of parse if any of your action handlers are async.
2100
+ *
2101
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2102
+ *
2103
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2104
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2105
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2106
+ * - `'user'`: just user arguments
2107
+ *
2108
+ * @example
2109
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
2110
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
2111
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2112
+ *
2113
+ * @param {string[]} [argv] - optional, defaults to process.argv
2114
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
2115
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2116
+ * @return {Command} `this` command for chaining
2117
+ */
2118
+ parse(argv, parseOptions) {
2119
+ this._prepareForParse();
2120
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2121
+ this._parseCommand([], userArgs);
2122
+ return this;
2123
+ }
2124
+ /**
2125
+ * Parse `argv`, setting options and invoking commands when defined.
2126
+ *
2127
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2128
+ *
2129
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2130
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2131
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2132
+ * - `'user'`: just user arguments
2133
+ *
2134
+ * @example
2135
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
2136
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
2137
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2138
+ *
2139
+ * @param {string[]} [argv]
2140
+ * @param {object} [parseOptions]
2141
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2142
+ * @return {Promise}
2143
+ */
2144
+ async parseAsync(argv, parseOptions) {
2145
+ this._prepareForParse();
2146
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
2147
+ await this._parseCommand([], userArgs);
2148
+ return this;
2149
+ }
2150
+ _prepareForParse() {
2151
+ if (this._savedState === null) {
2152
+ this.saveStateBeforeParse();
2153
+ } else {
2154
+ this.restoreStateBeforeParse();
2155
+ }
2156
+ }
2157
+ /**
2158
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
2159
+ * Not usually called directly, but available for subclasses to save their custom state.
2160
+ *
2161
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
2162
+ */
2163
+ saveStateBeforeParse() {
2164
+ this._savedState = {
2165
+ // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
2166
+ _name: this._name,
2167
+ // option values before parse have default values (including false for negated options)
2168
+ // shallow clones
2169
+ _optionValues: { ...this._optionValues },
2170
+ _optionValueSources: { ...this._optionValueSources }
2171
+ };
2172
+ }
2173
+ /**
2174
+ * Restore state before parse for calls after the first.
2175
+ * Not usually called directly, but available for subclasses to save their custom state.
2176
+ *
2177
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
2178
+ */
2179
+ restoreStateBeforeParse() {
2180
+ if (this._storeOptionsAsProperties)
2181
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
2182
+ - either make a new Command for each call to parse, or stop storing options as properties`);
2183
+ this._name = this._savedState._name;
2184
+ this._scriptPath = null;
2185
+ this.rawArgs = [];
2186
+ this._optionValues = { ...this._savedState._optionValues };
2187
+ this._optionValueSources = { ...this._savedState._optionValueSources };
2188
+ this.args = [];
2189
+ this.processedArgs = [];
2190
+ }
2191
+ /**
2192
+ * Throw if expected executable is missing. Add lots of help for author.
2193
+ *
2194
+ * @param {string} executableFile
2195
+ * @param {string} executableDir
2196
+ * @param {string} subcommandName
2197
+ */
2198
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2199
+ if (fs.existsSync(executableFile)) return;
2200
+ 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";
2201
+ const executableMissing = `'${executableFile}' does not exist
2202
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2203
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2204
+ - ${executableDirMessage}`;
2205
+ throw new Error(executableMissing);
2206
+ }
2207
+ /**
2208
+ * Execute a sub-command executable.
2209
+ *
2210
+ * @private
2211
+ */
2212
+ _executeSubCommand(subcommand, args) {
2213
+ args = args.slice();
2214
+ let launchWithNode = false;
2215
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
2216
+ function findFile(baseDir, baseName) {
2217
+ const localBin = path2.resolve(baseDir, baseName);
2218
+ if (fs.existsSync(localBin)) return localBin;
2219
+ if (sourceExt.includes(path2.extname(baseName))) return void 0;
2220
+ const foundExt = sourceExt.find(
2221
+ (ext) => fs.existsSync(`${localBin}${ext}`)
2222
+ );
2223
+ if (foundExt) return `${localBin}${foundExt}`;
2224
+ return void 0;
2225
+ }
2226
+ this._checkForMissingMandatoryOptions();
2227
+ this._checkForConflictingOptions();
2228
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
2229
+ let executableDir = this._executableDir || "";
2230
+ if (this._scriptPath) {
2231
+ let resolvedScriptPath;
2232
+ try {
2233
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
2234
+ } catch {
2235
+ resolvedScriptPath = this._scriptPath;
2236
+ }
2237
+ executableDir = path2.resolve(
2238
+ path2.dirname(resolvedScriptPath),
2239
+ executableDir
2240
+ );
2241
+ }
2242
+ if (executableDir) {
2243
+ let localFile = findFile(executableDir, executableFile);
2244
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
2245
+ const legacyName = path2.basename(
2246
+ this._scriptPath,
2247
+ path2.extname(this._scriptPath)
2248
+ );
2249
+ if (legacyName !== this._name) {
2250
+ localFile = findFile(
2251
+ executableDir,
2252
+ `${legacyName}-${subcommand._name}`
2253
+ );
2254
+ }
2255
+ }
2256
+ executableFile = localFile || executableFile;
2257
+ }
2258
+ launchWithNode = sourceExt.includes(path2.extname(executableFile));
2259
+ let proc;
2260
+ if (process2.platform !== "win32") {
2261
+ if (launchWithNode) {
2262
+ args.unshift(executableFile);
2263
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2264
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
2265
+ } else {
2266
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
2267
+ }
2268
+ } else {
2269
+ this._checkForMissingExecutable(
2270
+ executableFile,
2271
+ executableDir,
2272
+ subcommand._name
2273
+ );
2274
+ args.unshift(executableFile);
2275
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2276
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
2277
+ }
2278
+ if (!proc.killed) {
2279
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
2280
+ signals.forEach((signal) => {
2281
+ process2.on(signal, () => {
2282
+ if (proc.killed === false && proc.exitCode === null) {
2283
+ proc.kill(signal);
2284
+ }
2285
+ });
2286
+ });
2287
+ }
2288
+ const exitCallback = this._exitCallback;
2289
+ proc.on("close", (code) => {
2290
+ code = code ?? 1;
2291
+ if (!exitCallback) {
2292
+ process2.exit(code);
2293
+ } else {
2294
+ exitCallback(
2295
+ new CommanderError2(
2296
+ code,
2297
+ "commander.executeSubCommandAsync",
2298
+ "(close)"
2299
+ )
2300
+ );
2301
+ }
2302
+ });
2303
+ proc.on("error", (err) => {
2304
+ if (err.code === "ENOENT") {
2305
+ this._checkForMissingExecutable(
2306
+ executableFile,
2307
+ executableDir,
2308
+ subcommand._name
2309
+ );
2310
+ } else if (err.code === "EACCES") {
2311
+ throw new Error(`'${executableFile}' not executable`);
2312
+ }
2313
+ if (!exitCallback) {
2314
+ process2.exit(1);
2315
+ } else {
2316
+ const wrappedError = new CommanderError2(
2317
+ 1,
2318
+ "commander.executeSubCommandAsync",
2319
+ "(error)"
2320
+ );
2321
+ wrappedError.nestedError = err;
2322
+ exitCallback(wrappedError);
2323
+ }
2324
+ });
2325
+ this.runningCommand = proc;
2326
+ }
2327
+ /**
2328
+ * @private
2329
+ */
2330
+ _dispatchSubcommand(commandName, operands, unknown) {
2331
+ const subCommand = this._findCommand(commandName);
2332
+ if (!subCommand) this.help({ error: true });
2333
+ subCommand._prepareForParse();
2334
+ let promiseChain;
2335
+ promiseChain = this._chainOrCallSubCommandHook(
2336
+ promiseChain,
2337
+ subCommand,
2338
+ "preSubcommand"
2339
+ );
2340
+ promiseChain = this._chainOrCall(promiseChain, () => {
2341
+ if (subCommand._executableHandler) {
2342
+ this._executeSubCommand(subCommand, operands.concat(unknown));
2343
+ } else {
2344
+ return subCommand._parseCommand(operands, unknown);
2345
+ }
2346
+ });
2347
+ return promiseChain;
2348
+ }
2349
+ /**
2350
+ * Invoke help directly if possible, or dispatch if necessary.
2351
+ * e.g. help foo
2352
+ *
2353
+ * @private
2354
+ */
2355
+ _dispatchHelpCommand(subcommandName) {
2356
+ if (!subcommandName) {
2357
+ this.help();
2358
+ }
2359
+ const subCommand = this._findCommand(subcommandName);
2360
+ if (subCommand && !subCommand._executableHandler) {
2361
+ subCommand.help();
2362
+ }
2363
+ return this._dispatchSubcommand(
2364
+ subcommandName,
2365
+ [],
2366
+ [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2367
+ );
2368
+ }
2369
+ /**
2370
+ * Check this.args against expected this.registeredArguments.
2371
+ *
2372
+ * @private
2373
+ */
2374
+ _checkNumberOfArguments() {
2375
+ this.registeredArguments.forEach((arg, i) => {
2376
+ if (arg.required && this.args[i] == null) {
2377
+ this.missingArgument(arg.name());
2378
+ }
2379
+ });
2380
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2381
+ return;
2382
+ }
2383
+ if (this.args.length > this.registeredArguments.length) {
2384
+ this._excessArguments(this.args);
2385
+ }
2386
+ }
2387
+ /**
2388
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2389
+ *
2390
+ * @private
2391
+ */
2392
+ _processArguments() {
2393
+ const myParseArg = (argument, value, previous) => {
2394
+ let parsedValue = value;
2395
+ if (value !== null && argument.parseArg) {
2396
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2397
+ parsedValue = this._callParseArg(
2398
+ argument,
2399
+ value,
2400
+ previous,
2401
+ invalidValueMessage
2402
+ );
2403
+ }
2404
+ return parsedValue;
2405
+ };
2406
+ this._checkNumberOfArguments();
2407
+ const processedArgs = [];
2408
+ this.registeredArguments.forEach((declaredArg, index) => {
2409
+ let value = declaredArg.defaultValue;
2410
+ if (declaredArg.variadic) {
2411
+ if (index < this.args.length) {
2412
+ value = this.args.slice(index);
2413
+ if (declaredArg.parseArg) {
2414
+ value = value.reduce((processed, v) => {
2415
+ return myParseArg(declaredArg, v, processed);
2416
+ }, declaredArg.defaultValue);
2417
+ }
2418
+ } else if (value === void 0) {
2419
+ value = [];
2420
+ }
2421
+ } else if (index < this.args.length) {
2422
+ value = this.args[index];
2423
+ if (declaredArg.parseArg) {
2424
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2425
+ }
2426
+ }
2427
+ processedArgs[index] = value;
2428
+ });
2429
+ this.processedArgs = processedArgs;
2430
+ }
2431
+ /**
2432
+ * Once we have a promise we chain, but call synchronously until then.
2433
+ *
2434
+ * @param {(Promise|undefined)} promise
2435
+ * @param {Function} fn
2436
+ * @return {(Promise|undefined)}
2437
+ * @private
2438
+ */
2439
+ _chainOrCall(promise, fn) {
2440
+ if (promise?.then && typeof promise.then === "function") {
2441
+ return promise.then(() => fn());
2442
+ }
2443
+ return fn();
2444
+ }
2445
+ /**
2446
+ *
2447
+ * @param {(Promise|undefined)} promise
2448
+ * @param {string} event
2449
+ * @return {(Promise|undefined)}
2450
+ * @private
2451
+ */
2452
+ _chainOrCallHooks(promise, event) {
2453
+ let result = promise;
2454
+ const hooks = [];
2455
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2456
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2457
+ hooks.push({ hookedCommand, callback });
2458
+ });
2459
+ });
2460
+ if (event === "postAction") {
2461
+ hooks.reverse();
2462
+ }
2463
+ hooks.forEach((hookDetail) => {
2464
+ result = this._chainOrCall(result, () => {
2465
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2466
+ });
2467
+ });
2468
+ return result;
2469
+ }
2470
+ /**
2471
+ *
2472
+ * @param {(Promise|undefined)} promise
2473
+ * @param {Command} subCommand
2474
+ * @param {string} event
2475
+ * @return {(Promise|undefined)}
2476
+ * @private
2477
+ */
2478
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2479
+ let result = promise;
2480
+ if (this._lifeCycleHooks[event] !== void 0) {
2481
+ this._lifeCycleHooks[event].forEach((hook) => {
2482
+ result = this._chainOrCall(result, () => {
2483
+ return hook(this, subCommand);
2484
+ });
2485
+ });
2486
+ }
2487
+ return result;
2488
+ }
2489
+ /**
2490
+ * Process arguments in context of this command.
2491
+ * Returns action result, in case it is a promise.
2492
+ *
2493
+ * @private
2494
+ */
2495
+ _parseCommand(operands, unknown) {
2496
+ const parsed = this.parseOptions(unknown);
2497
+ this._parseOptionsEnv();
2498
+ this._parseOptionsImplied();
2499
+ operands = operands.concat(parsed.operands);
2500
+ unknown = parsed.unknown;
2501
+ this.args = operands.concat(unknown);
2502
+ if (operands && this._findCommand(operands[0])) {
2503
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2504
+ }
2505
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2506
+ return this._dispatchHelpCommand(operands[1]);
2507
+ }
2508
+ if (this._defaultCommandName) {
2509
+ this._outputHelpIfRequested(unknown);
2510
+ return this._dispatchSubcommand(
2511
+ this._defaultCommandName,
2512
+ operands,
2513
+ unknown
2514
+ );
2515
+ }
2516
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2517
+ this.help({ error: true });
2518
+ }
2519
+ this._outputHelpIfRequested(parsed.unknown);
2520
+ this._checkForMissingMandatoryOptions();
2521
+ this._checkForConflictingOptions();
2522
+ const checkForUnknownOptions = () => {
2523
+ if (parsed.unknown.length > 0) {
2524
+ this.unknownOption(parsed.unknown[0]);
2525
+ }
2526
+ };
2527
+ const commandEvent = `command:${this.name()}`;
2528
+ if (this._actionHandler) {
2529
+ checkForUnknownOptions();
2530
+ this._processArguments();
2531
+ let promiseChain;
2532
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2533
+ promiseChain = this._chainOrCall(
2534
+ promiseChain,
2535
+ () => this._actionHandler(this.processedArgs)
2536
+ );
2537
+ if (this.parent) {
2538
+ promiseChain = this._chainOrCall(promiseChain, () => {
2539
+ this.parent.emit(commandEvent, operands, unknown);
2540
+ });
2541
+ }
2542
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2543
+ return promiseChain;
2544
+ }
2545
+ if (this.parent?.listenerCount(commandEvent)) {
2546
+ checkForUnknownOptions();
2547
+ this._processArguments();
2548
+ this.parent.emit(commandEvent, operands, unknown);
2549
+ } else if (operands.length) {
2550
+ if (this._findCommand("*")) {
2551
+ return this._dispatchSubcommand("*", operands, unknown);
2552
+ }
2553
+ if (this.listenerCount("command:*")) {
2554
+ this.emit("command:*", operands, unknown);
2555
+ } else if (this.commands.length) {
2556
+ this.unknownCommand();
2557
+ } else {
2558
+ checkForUnknownOptions();
2559
+ this._processArguments();
2560
+ }
2561
+ } else if (this.commands.length) {
2562
+ checkForUnknownOptions();
2563
+ this.help({ error: true });
2564
+ } else {
2565
+ checkForUnknownOptions();
2566
+ this._processArguments();
2567
+ }
2568
+ }
2569
+ /**
2570
+ * Find matching command.
2571
+ *
2572
+ * @private
2573
+ * @return {Command | undefined}
2574
+ */
2575
+ _findCommand(name) {
2576
+ if (!name) return void 0;
2577
+ return this.commands.find(
2578
+ (cmd) => cmd._name === name || cmd._aliases.includes(name)
2579
+ );
2580
+ }
2581
+ /**
2582
+ * Return an option matching `arg` if any.
2583
+ *
2584
+ * @param {string} arg
2585
+ * @return {Option}
2586
+ * @package
2587
+ */
2588
+ _findOption(arg) {
2589
+ return this.options.find((option) => option.is(arg));
2590
+ }
2591
+ /**
2592
+ * Display an error message if a mandatory option does not have a value.
2593
+ * Called after checking for help flags in leaf subcommand.
2594
+ *
2595
+ * @private
2596
+ */
2597
+ _checkForMissingMandatoryOptions() {
2598
+ this._getCommandAndAncestors().forEach((cmd) => {
2599
+ cmd.options.forEach((anOption) => {
2600
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2601
+ cmd.missingMandatoryOptionValue(anOption);
2602
+ }
2603
+ });
2604
+ });
2605
+ }
2606
+ /**
2607
+ * Display an error message if conflicting options are used together in this.
2608
+ *
2609
+ * @private
2610
+ */
2611
+ _checkForConflictingLocalOptions() {
2612
+ const definedNonDefaultOptions = this.options.filter((option) => {
2613
+ const optionKey = option.attributeName();
2614
+ if (this.getOptionValue(optionKey) === void 0) {
2615
+ return false;
2616
+ }
2617
+ return this.getOptionValueSource(optionKey) !== "default";
2618
+ });
2619
+ const optionsWithConflicting = definedNonDefaultOptions.filter(
2620
+ (option) => option.conflictsWith.length > 0
2621
+ );
2622
+ optionsWithConflicting.forEach((option) => {
2623
+ const conflictingAndDefined = definedNonDefaultOptions.find(
2624
+ (defined) => option.conflictsWith.includes(defined.attributeName())
2625
+ );
2626
+ if (conflictingAndDefined) {
2627
+ this._conflictingOption(option, conflictingAndDefined);
2628
+ }
2629
+ });
2630
+ }
2631
+ /**
2632
+ * Display an error message if conflicting options are used together.
2633
+ * Called after checking for help flags in leaf subcommand.
2634
+ *
2635
+ * @private
2636
+ */
2637
+ _checkForConflictingOptions() {
2638
+ this._getCommandAndAncestors().forEach((cmd) => {
2639
+ cmd._checkForConflictingLocalOptions();
2640
+ });
2641
+ }
2642
+ /**
2643
+ * Parse options from `argv` removing known options,
2644
+ * and return argv split into operands and unknown arguments.
2645
+ *
2646
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2647
+ *
2648
+ * Examples:
2649
+ *
2650
+ * argv => operands, unknown
2651
+ * --known kkk op => [op], []
2652
+ * op --known kkk => [op], []
2653
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2654
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2655
+ *
2656
+ * @param {string[]} args
2657
+ * @return {{operands: string[], unknown: string[]}}
2658
+ */
2659
+ parseOptions(args) {
2660
+ const operands = [];
2661
+ const unknown = [];
2662
+ let dest = operands;
2663
+ function maybeOption(arg) {
2664
+ return arg.length > 1 && arg[0] === "-";
2665
+ }
2666
+ const negativeNumberArg = (arg) => {
2667
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
2668
+ return !this._getCommandAndAncestors().some(
2669
+ (cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short))
2670
+ );
2671
+ };
2672
+ let activeVariadicOption = null;
2673
+ let activeGroup = null;
2674
+ let i = 0;
2675
+ while (i < args.length || activeGroup) {
2676
+ const arg = activeGroup ?? args[i++];
2677
+ activeGroup = null;
2678
+ if (arg === "--") {
2679
+ if (dest === unknown) dest.push(arg);
2680
+ dest.push(...args.slice(i));
2681
+ break;
2682
+ }
2683
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
2684
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2685
+ continue;
2686
+ }
2687
+ activeVariadicOption = null;
2688
+ if (maybeOption(arg)) {
2689
+ const option = this._findOption(arg);
2690
+ if (option) {
2691
+ if (option.required) {
2692
+ const value = args[i++];
2693
+ if (value === void 0) this.optionMissingArgument(option);
2694
+ this.emit(`option:${option.name()}`, value);
2695
+ } else if (option.optional) {
2696
+ let value = null;
2697
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
2698
+ value = args[i++];
2699
+ }
2700
+ this.emit(`option:${option.name()}`, value);
2701
+ } else {
2702
+ this.emit(`option:${option.name()}`);
2703
+ }
2704
+ activeVariadicOption = option.variadic ? option : null;
2705
+ continue;
2706
+ }
2707
+ }
2708
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2709
+ const option = this._findOption(`-${arg[1]}`);
2710
+ if (option) {
2711
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2712
+ this.emit(`option:${option.name()}`, arg.slice(2));
2713
+ } else {
2714
+ this.emit(`option:${option.name()}`);
2715
+ activeGroup = `-${arg.slice(2)}`;
2716
+ }
2717
+ continue;
2718
+ }
2719
+ }
2720
+ if (/^--[^=]+=/.test(arg)) {
2721
+ const index = arg.indexOf("=");
2722
+ const option = this._findOption(arg.slice(0, index));
2723
+ if (option && (option.required || option.optional)) {
2724
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2725
+ continue;
2726
+ }
2727
+ }
2728
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
2729
+ dest = unknown;
2730
+ }
2731
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2732
+ if (this._findCommand(arg)) {
2733
+ operands.push(arg);
2734
+ unknown.push(...args.slice(i));
2735
+ break;
2736
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2737
+ operands.push(arg, ...args.slice(i));
2738
+ break;
2739
+ } else if (this._defaultCommandName) {
2740
+ unknown.push(arg, ...args.slice(i));
2741
+ break;
2742
+ }
2743
+ }
2744
+ if (this._passThroughOptions) {
2745
+ dest.push(arg, ...args.slice(i));
2746
+ break;
2747
+ }
2748
+ dest.push(arg);
2749
+ }
2750
+ return { operands, unknown };
2751
+ }
2752
+ /**
2753
+ * Return an object containing local option values as key-value pairs.
2754
+ *
2755
+ * @return {object}
2756
+ */
2757
+ opts() {
2758
+ if (this._storeOptionsAsProperties) {
2759
+ const result = {};
2760
+ const len = this.options.length;
2761
+ for (let i = 0; i < len; i++) {
2762
+ const key = this.options[i].attributeName();
2763
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2764
+ }
2765
+ return result;
2766
+ }
2767
+ return this._optionValues;
2768
+ }
2769
+ /**
2770
+ * Return an object containing merged local and global option values as key-value pairs.
2771
+ *
2772
+ * @return {object}
2773
+ */
2774
+ optsWithGlobals() {
2775
+ return this._getCommandAndAncestors().reduce(
2776
+ (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2777
+ {}
2778
+ );
2779
+ }
2780
+ /**
2781
+ * Display error message and exit (or call exitOverride).
2782
+ *
2783
+ * @param {string} message
2784
+ * @param {object} [errorOptions]
2785
+ * @param {string} [errorOptions.code] - an id string representing the error
2786
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2787
+ */
2788
+ error(message, errorOptions) {
2789
+ this._outputConfiguration.outputError(
2790
+ `${message}
2791
+ `,
2792
+ this._outputConfiguration.writeErr
2793
+ );
2794
+ if (typeof this._showHelpAfterError === "string") {
2795
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2796
+ `);
2797
+ } else if (this._showHelpAfterError) {
2798
+ this._outputConfiguration.writeErr("\n");
2799
+ this.outputHelp({ error: true });
2800
+ }
2801
+ const config = errorOptions || {};
2802
+ const exitCode = config.exitCode || 1;
2803
+ const code = config.code || "commander.error";
2804
+ this._exit(exitCode, code, message);
2805
+ }
2806
+ /**
2807
+ * Apply any option related environment variables, if option does
2808
+ * not have a value from cli or client code.
2809
+ *
2810
+ * @private
2811
+ */
2812
+ _parseOptionsEnv() {
2813
+ this.options.forEach((option) => {
2814
+ if (option.envVar && option.envVar in process2.env) {
2815
+ const optionKey = option.attributeName();
2816
+ if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
2817
+ this.getOptionValueSource(optionKey)
2818
+ )) {
2819
+ if (option.required || option.optional) {
2820
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2821
+ } else {
2822
+ this.emit(`optionEnv:${option.name()}`);
2823
+ }
2824
+ }
2825
+ }
2826
+ });
2827
+ }
2828
+ /**
2829
+ * Apply any implied option values, if option is undefined or default value.
2830
+ *
2831
+ * @private
2832
+ */
2833
+ _parseOptionsImplied() {
2834
+ const dualHelper = new DualOptions(this.options);
2835
+ const hasCustomOptionValue = (optionKey) => {
2836
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2837
+ };
2838
+ this.options.filter(
2839
+ (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
2840
+ this.getOptionValue(option.attributeName()),
2841
+ option
2842
+ )
2843
+ ).forEach((option) => {
2844
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2845
+ this.setOptionValueWithSource(
2846
+ impliedKey,
2847
+ option.implied[impliedKey],
2848
+ "implied"
2849
+ );
2850
+ });
2851
+ });
2852
+ }
2853
+ /**
2854
+ * Argument `name` is missing.
2855
+ *
2856
+ * @param {string} name
2857
+ * @private
2858
+ */
2859
+ missingArgument(name) {
2860
+ const message = `error: missing required argument '${name}'`;
2861
+ this.error(message, { code: "commander.missingArgument" });
2862
+ }
2863
+ /**
2864
+ * `Option` is missing an argument.
2865
+ *
2866
+ * @param {Option} option
2867
+ * @private
2868
+ */
2869
+ optionMissingArgument(option) {
2870
+ const message = `error: option '${option.flags}' argument missing`;
2871
+ this.error(message, { code: "commander.optionMissingArgument" });
2872
+ }
2873
+ /**
2874
+ * `Option` does not have a value, and is a mandatory option.
2875
+ *
2876
+ * @param {Option} option
2877
+ * @private
2878
+ */
2879
+ missingMandatoryOptionValue(option) {
2880
+ const message = `error: required option '${option.flags}' not specified`;
2881
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2882
+ }
2883
+ /**
2884
+ * `Option` conflicts with another option.
2885
+ *
2886
+ * @param {Option} option
2887
+ * @param {Option} conflictingOption
2888
+ * @private
2889
+ */
2890
+ _conflictingOption(option, conflictingOption) {
2891
+ const findBestOptionFromValue = (option2) => {
2892
+ const optionKey = option2.attributeName();
2893
+ const optionValue = this.getOptionValue(optionKey);
2894
+ const negativeOption = this.options.find(
2895
+ (target) => target.negate && optionKey === target.attributeName()
2896
+ );
2897
+ const positiveOption = this.options.find(
2898
+ (target) => !target.negate && optionKey === target.attributeName()
2899
+ );
2900
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2901
+ return negativeOption;
2902
+ }
2903
+ return positiveOption || option2;
2904
+ };
2905
+ const getErrorMessage = (option2) => {
2906
+ const bestOption = findBestOptionFromValue(option2);
2907
+ const optionKey = bestOption.attributeName();
2908
+ const source = this.getOptionValueSource(optionKey);
2909
+ if (source === "env") {
2910
+ return `environment variable '${bestOption.envVar}'`;
2911
+ }
2912
+ return `option '${bestOption.flags}'`;
2913
+ };
2914
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2915
+ this.error(message, { code: "commander.conflictingOption" });
2916
+ }
2917
+ /**
2918
+ * Unknown option `flag`.
2919
+ *
2920
+ * @param {string} flag
2921
+ * @private
2922
+ */
2923
+ unknownOption(flag) {
2924
+ if (this._allowUnknownOption) return;
2925
+ let suggestion = "";
2926
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2927
+ let candidateFlags = [];
2928
+ let command = this;
2929
+ do {
2930
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2931
+ candidateFlags = candidateFlags.concat(moreFlags);
2932
+ command = command.parent;
2933
+ } while (command && !command._enablePositionalOptions);
2934
+ suggestion = suggestSimilar(flag, candidateFlags);
2935
+ }
2936
+ const message = `error: unknown option '${flag}'${suggestion}`;
2937
+ this.error(message, { code: "commander.unknownOption" });
2938
+ }
2939
+ /**
2940
+ * Excess arguments, more than expected.
2941
+ *
2942
+ * @param {string[]} receivedArgs
2943
+ * @private
2944
+ */
2945
+ _excessArguments(receivedArgs) {
2946
+ if (this._allowExcessArguments) return;
2947
+ const expected = this.registeredArguments.length;
2948
+ const s = expected === 1 ? "" : "s";
2949
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2950
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2951
+ this.error(message, { code: "commander.excessArguments" });
2952
+ }
2953
+ /**
2954
+ * Unknown command.
2955
+ *
2956
+ * @private
2957
+ */
2958
+ unknownCommand() {
2959
+ const unknownName = this.args[0];
2960
+ let suggestion = "";
2961
+ if (this._showSuggestionAfterError) {
2962
+ const candidateNames = [];
2963
+ this.createHelp().visibleCommands(this).forEach((command) => {
2964
+ candidateNames.push(command.name());
2965
+ if (command.alias()) candidateNames.push(command.alias());
2966
+ });
2967
+ suggestion = suggestSimilar(unknownName, candidateNames);
2968
+ }
2969
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2970
+ this.error(message, { code: "commander.unknownCommand" });
2971
+ }
2972
+ /**
2973
+ * Get or set the program version.
2974
+ *
2975
+ * This method auto-registers the "-V, --version" option which will print the version number.
2976
+ *
2977
+ * You can optionally supply the flags and description to override the defaults.
2978
+ *
2979
+ * @param {string} [str]
2980
+ * @param {string} [flags]
2981
+ * @param {string} [description]
2982
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2983
+ */
2984
+ version(str, flags, description) {
2985
+ if (str === void 0) return this._version;
2986
+ this._version = str;
2987
+ flags = flags || "-V, --version";
2988
+ description = description || "output the version number";
2989
+ const versionOption = this.createOption(flags, description);
2990
+ this._versionOptionName = versionOption.attributeName();
2991
+ this._registerOption(versionOption);
2992
+ this.on("option:" + versionOption.name(), () => {
2993
+ this._outputConfiguration.writeOut(`${str}
2994
+ `);
2995
+ this._exit(0, "commander.version", str);
2996
+ });
2997
+ return this;
2998
+ }
2999
+ /**
3000
+ * Set the description.
3001
+ *
3002
+ * @param {string} [str]
3003
+ * @param {object} [argsDescription]
3004
+ * @return {(string|Command)}
3005
+ */
3006
+ description(str, argsDescription) {
3007
+ if (str === void 0 && argsDescription === void 0)
3008
+ return this._description;
3009
+ this._description = str;
3010
+ if (argsDescription) {
3011
+ this._argsDescription = argsDescription;
3012
+ }
3013
+ return this;
3014
+ }
3015
+ /**
3016
+ * Set the summary. Used when listed as subcommand of parent.
3017
+ *
3018
+ * @param {string} [str]
3019
+ * @return {(string|Command)}
3020
+ */
3021
+ summary(str) {
3022
+ if (str === void 0) return this._summary;
3023
+ this._summary = str;
3024
+ return this;
3025
+ }
3026
+ /**
3027
+ * Set an alias for the command.
3028
+ *
3029
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
3030
+ *
3031
+ * @param {string} [alias]
3032
+ * @return {(string|Command)}
3033
+ */
3034
+ alias(alias) {
3035
+ if (alias === void 0) return this._aliases[0];
3036
+ let command = this;
3037
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
3038
+ command = this.commands[this.commands.length - 1];
3039
+ }
3040
+ if (alias === command._name)
3041
+ throw new Error("Command alias can't be the same as its name");
3042
+ const matchingCommand = this.parent?._findCommand(alias);
3043
+ if (matchingCommand) {
3044
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
3045
+ throw new Error(
3046
+ `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
3047
+ );
3048
+ }
3049
+ command._aliases.push(alias);
3050
+ return this;
3051
+ }
3052
+ /**
3053
+ * Set aliases for the command.
3054
+ *
3055
+ * Only the first alias is shown in the auto-generated help.
3056
+ *
3057
+ * @param {string[]} [aliases]
3058
+ * @return {(string[]|Command)}
3059
+ */
3060
+ aliases(aliases) {
3061
+ if (aliases === void 0) return this._aliases;
3062
+ aliases.forEach((alias) => this.alias(alias));
3063
+ return this;
3064
+ }
3065
+ /**
3066
+ * Set / get the command usage `str`.
3067
+ *
3068
+ * @param {string} [str]
3069
+ * @return {(string|Command)}
3070
+ */
3071
+ usage(str) {
3072
+ if (str === void 0) {
3073
+ if (this._usage) return this._usage;
3074
+ const args = this.registeredArguments.map((arg) => {
3075
+ return humanReadableArgName(arg);
3076
+ });
3077
+ return [].concat(
3078
+ this.options.length || this._helpOption !== null ? "[options]" : [],
3079
+ this.commands.length ? "[command]" : [],
3080
+ this.registeredArguments.length ? args : []
3081
+ ).join(" ");
3082
+ }
3083
+ this._usage = str;
3084
+ return this;
3085
+ }
3086
+ /**
3087
+ * Get or set the name of the command.
3088
+ *
3089
+ * @param {string} [str]
3090
+ * @return {(string|Command)}
3091
+ */
3092
+ name(str) {
3093
+ if (str === void 0) return this._name;
3094
+ this._name = str;
3095
+ return this;
3096
+ }
3097
+ /**
3098
+ * Set/get the help group heading for this subcommand in parent command's help.
3099
+ *
3100
+ * @param {string} [heading]
3101
+ * @return {Command | string}
3102
+ */
3103
+ helpGroup(heading) {
3104
+ if (heading === void 0) return this._helpGroupHeading ?? "";
3105
+ this._helpGroupHeading = heading;
3106
+ return this;
3107
+ }
3108
+ /**
3109
+ * Set/get the default help group heading for subcommands added to this command.
3110
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
3111
+ *
3112
+ * @example
3113
+ * program.commandsGroup('Development Commands:);
3114
+ * program.command('watch')...
3115
+ * program.command('lint')...
3116
+ * ...
3117
+ *
3118
+ * @param {string} [heading]
3119
+ * @returns {Command | string}
3120
+ */
3121
+ commandsGroup(heading) {
3122
+ if (heading === void 0) return this._defaultCommandGroup ?? "";
3123
+ this._defaultCommandGroup = heading;
3124
+ return this;
3125
+ }
3126
+ /**
3127
+ * Set/get the default help group heading for options added to this command.
3128
+ * (This does not override a group set directly on the option using .helpGroup().)
3129
+ *
3130
+ * @example
3131
+ * program
3132
+ * .optionsGroup('Development Options:')
3133
+ * .option('-d, --debug', 'output extra debugging')
3134
+ * .option('-p, --profile', 'output profiling information')
3135
+ *
3136
+ * @param {string} [heading]
3137
+ * @returns {Command | string}
3138
+ */
3139
+ optionsGroup(heading) {
3140
+ if (heading === void 0) return this._defaultOptionGroup ?? "";
3141
+ this._defaultOptionGroup = heading;
3142
+ return this;
3143
+ }
3144
+ /**
3145
+ * @param {Option} option
3146
+ * @private
3147
+ */
3148
+ _initOptionGroup(option) {
3149
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
3150
+ option.helpGroup(this._defaultOptionGroup);
3151
+ }
3152
+ /**
3153
+ * @param {Command} cmd
3154
+ * @private
3155
+ */
3156
+ _initCommandGroup(cmd) {
3157
+ if (this._defaultCommandGroup && !cmd.helpGroup())
3158
+ cmd.helpGroup(this._defaultCommandGroup);
3159
+ }
3160
+ /**
3161
+ * Set the name of the command from script filename, such as process.argv[1],
3162
+ * or require.main.filename, or __filename.
3163
+ *
3164
+ * (Used internally and public although not documented in README.)
3165
+ *
3166
+ * @example
3167
+ * program.nameFromFilename(require.main.filename);
3168
+ *
3169
+ * @param {string} filename
3170
+ * @return {Command}
3171
+ */
3172
+ nameFromFilename(filename) {
3173
+ this._name = path2.basename(filename, path2.extname(filename));
3174
+ return this;
3175
+ }
3176
+ /**
3177
+ * Get or set the directory for searching for executable subcommands of this command.
3178
+ *
3179
+ * @example
3180
+ * program.executableDir(__dirname);
3181
+ * // or
3182
+ * program.executableDir('subcommands');
3183
+ *
3184
+ * @param {string} [path]
3185
+ * @return {(string|null|Command)}
3186
+ */
3187
+ executableDir(path3) {
3188
+ if (path3 === void 0) return this._executableDir;
3189
+ this._executableDir = path3;
3190
+ return this;
3191
+ }
3192
+ /**
3193
+ * Return program help documentation.
3194
+ *
3195
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
3196
+ * @return {string}
3197
+ */
3198
+ helpInformation(contextOptions) {
3199
+ const helper = this.createHelp();
3200
+ const context = this._getOutputContext(contextOptions);
3201
+ helper.prepareContext({
3202
+ error: context.error,
3203
+ helpWidth: context.helpWidth,
3204
+ outputHasColors: context.hasColors
3205
+ });
3206
+ const text = helper.formatHelp(this, helper);
3207
+ if (context.hasColors) return text;
3208
+ return this._outputConfiguration.stripColor(text);
3209
+ }
3210
+ /**
3211
+ * @typedef HelpContext
3212
+ * @type {object}
3213
+ * @property {boolean} error
3214
+ * @property {number} helpWidth
3215
+ * @property {boolean} hasColors
3216
+ * @property {function} write - includes stripColor if needed
3217
+ *
3218
+ * @returns {HelpContext}
3219
+ * @private
3220
+ */
3221
+ _getOutputContext(contextOptions) {
3222
+ contextOptions = contextOptions || {};
3223
+ const error = !!contextOptions.error;
3224
+ let baseWrite;
3225
+ let hasColors;
3226
+ let helpWidth;
3227
+ if (error) {
3228
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
3229
+ hasColors = this._outputConfiguration.getErrHasColors();
3230
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
3231
+ } else {
3232
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
3233
+ hasColors = this._outputConfiguration.getOutHasColors();
3234
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
3235
+ }
3236
+ const write = (str) => {
3237
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
3238
+ return baseWrite(str);
3239
+ };
3240
+ return { error, write, hasColors, helpWidth };
3241
+ }
3242
+ /**
3243
+ * Output help information for this command.
3244
+ *
3245
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3246
+ *
3247
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3248
+ */
3249
+ outputHelp(contextOptions) {
3250
+ let deprecatedCallback;
3251
+ if (typeof contextOptions === "function") {
3252
+ deprecatedCallback = contextOptions;
3253
+ contextOptions = void 0;
3254
+ }
3255
+ const outputContext = this._getOutputContext(contextOptions);
3256
+ const eventContext = {
3257
+ error: outputContext.error,
3258
+ write: outputContext.write,
3259
+ command: this
3260
+ };
3261
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
3262
+ this.emit("beforeHelp", eventContext);
3263
+ let helpInformation = this.helpInformation({ error: outputContext.error });
3264
+ if (deprecatedCallback) {
3265
+ helpInformation = deprecatedCallback(helpInformation);
3266
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
3267
+ throw new Error("outputHelp callback must return a string or a Buffer");
3268
+ }
3269
+ }
3270
+ outputContext.write(helpInformation);
3271
+ if (this._getHelpOption()?.long) {
3272
+ this.emit(this._getHelpOption().long);
3273
+ }
3274
+ this.emit("afterHelp", eventContext);
3275
+ this._getCommandAndAncestors().forEach(
3276
+ (command) => command.emit("afterAllHelp", eventContext)
3277
+ );
3278
+ }
3279
+ /**
3280
+ * You can pass in flags and a description to customise the built-in help option.
3281
+ * Pass in false to disable the built-in help option.
3282
+ *
3283
+ * @example
3284
+ * program.helpOption('-?, --help' 'show help'); // customise
3285
+ * program.helpOption(false); // disable
3286
+ *
3287
+ * @param {(string | boolean)} flags
3288
+ * @param {string} [description]
3289
+ * @return {Command} `this` command for chaining
3290
+ */
3291
+ helpOption(flags, description) {
3292
+ if (typeof flags === "boolean") {
3293
+ if (flags) {
3294
+ if (this._helpOption === null) this._helpOption = void 0;
3295
+ if (this._defaultOptionGroup) {
3296
+ this._initOptionGroup(this._getHelpOption());
3297
+ }
3298
+ } else {
3299
+ this._helpOption = null;
3300
+ }
3301
+ return this;
3302
+ }
3303
+ this._helpOption = this.createOption(
3304
+ flags ?? "-h, --help",
3305
+ description ?? "display help for command"
3306
+ );
3307
+ if (flags || description) this._initOptionGroup(this._helpOption);
3308
+ return this;
3309
+ }
3310
+ /**
3311
+ * Lazy create help option.
3312
+ * Returns null if has been disabled with .helpOption(false).
3313
+ *
3314
+ * @returns {(Option | null)} the help option
3315
+ * @package
3316
+ */
3317
+ _getHelpOption() {
3318
+ if (this._helpOption === void 0) {
3319
+ this.helpOption(void 0, void 0);
3320
+ }
3321
+ return this._helpOption;
3322
+ }
3323
+ /**
3324
+ * Supply your own option to use for the built-in help option.
3325
+ * This is an alternative to using helpOption() to customise the flags and description etc.
3326
+ *
3327
+ * @param {Option} option
3328
+ * @return {Command} `this` command for chaining
3329
+ */
3330
+ addHelpOption(option) {
3331
+ this._helpOption = option;
3332
+ this._initOptionGroup(option);
3333
+ return this;
3334
+ }
3335
+ /**
3336
+ * Output help information and exit.
3337
+ *
3338
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
3339
+ *
3340
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3341
+ */
3342
+ help(contextOptions) {
3343
+ this.outputHelp(contextOptions);
3344
+ let exitCode = Number(process2.exitCode ?? 0);
3345
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
3346
+ exitCode = 1;
3347
+ }
3348
+ this._exit(exitCode, "commander.help", "(outputHelp)");
3349
+ }
3350
+ /**
3351
+ * // Do a little typing to coordinate emit and listener for the help text events.
3352
+ * @typedef HelpTextEventContext
3353
+ * @type {object}
3354
+ * @property {boolean} error
3355
+ * @property {Command} command
3356
+ * @property {function} write
3357
+ */
3358
+ /**
3359
+ * Add additional text to be displayed with the built-in help.
3360
+ *
3361
+ * Position is 'before' or 'after' to affect just this command,
3362
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
3363
+ *
3364
+ * @param {string} position - before or after built-in help
3365
+ * @param {(string | Function)} text - string to add, or a function returning a string
3366
+ * @return {Command} `this` command for chaining
3367
+ */
3368
+ addHelpText(position, text) {
3369
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
3370
+ if (!allowedValues.includes(position)) {
3371
+ throw new Error(`Unexpected value for position to addHelpText.
3372
+ Expecting one of '${allowedValues.join("', '")}'`);
3373
+ }
3374
+ const helpEvent = `${position}Help`;
3375
+ this.on(helpEvent, (context) => {
3376
+ let helpStr;
3377
+ if (typeof text === "function") {
3378
+ helpStr = text({ error: context.error, command: context.command });
3379
+ } else {
3380
+ helpStr = text;
3381
+ }
3382
+ if (helpStr) {
3383
+ context.write(`${helpStr}
3384
+ `);
3385
+ }
3386
+ });
3387
+ return this;
3388
+ }
3389
+ /**
3390
+ * Output help information if help flags specified
3391
+ *
3392
+ * @param {Array} args - array of options to search for help flags
3393
+ * @private
3394
+ */
3395
+ _outputHelpIfRequested(args) {
3396
+ const helpOption = this._getHelpOption();
3397
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
3398
+ if (helpRequested) {
3399
+ this.outputHelp();
3400
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
3401
+ }
3402
+ }
3403
+ };
3404
+ function incrementNodeInspectorPort(args) {
3405
+ return args.map((arg) => {
3406
+ if (!arg.startsWith("--inspect")) {
3407
+ return arg;
3408
+ }
3409
+ let debugOption;
3410
+ let debugHost = "127.0.0.1";
3411
+ let debugPort = "9229";
3412
+ let match;
3413
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
3414
+ debugOption = match[1];
3415
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3416
+ debugOption = match[1];
3417
+ if (/^\d+$/.test(match[3])) {
3418
+ debugPort = match[3];
3419
+ } else {
3420
+ debugHost = match[3];
3421
+ }
3422
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3423
+ debugOption = match[1];
3424
+ debugHost = match[3];
3425
+ debugPort = match[4];
3426
+ }
3427
+ if (debugOption && debugPort !== "0") {
3428
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3429
+ }
3430
+ return arg;
3431
+ });
3432
+ }
3433
+ function useColor() {
3434
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
3435
+ return false;
3436
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
3437
+ return true;
3438
+ return void 0;
3439
+ }
3440
+ exports.Command = Command2;
3441
+ exports.useColor = useColor;
3442
+ }
3443
+ });
3444
+
3445
+ // ../../node_modules/commander/index.js
3446
+ var require_commander = __commonJS({
3447
+ "../../node_modules/commander/index.js"(exports) {
3448
+ "use strict";
3449
+ var { Argument: Argument2 } = require_argument();
3450
+ var { Command: Command2 } = require_command();
3451
+ var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
3452
+ var { Help: Help2 } = require_help();
3453
+ var { Option: Option2 } = require_option();
3454
+ exports.program = new Command2();
3455
+ exports.createCommand = (name) => new Command2(name);
3456
+ exports.createOption = (flags, description) => new Option2(flags, description);
3457
+ exports.createArgument = (name, description) => new Argument2(name, description);
3458
+ exports.Command = Command2;
3459
+ exports.Option = Option2;
3460
+ exports.Argument = Argument2;
3461
+ exports.Help = Help2;
3462
+ exports.CommanderError = CommanderError2;
3463
+ exports.InvalidArgumentError = InvalidArgumentError2;
3464
+ exports.InvalidOptionArgumentError = InvalidArgumentError2;
3465
+ }
3466
+ });
3467
+
3468
+ // src/index.ts
3469
+ import { chmod, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from "fs/promises";
3470
+ import { createRequire } from "module";
3471
+ import { homedir } from "os";
3472
+ import path from "path";
3473
+ import { fileURLToPath, pathToFileURL } from "url";
3474
+ import process from "process";
3475
+ import { zipSync } from "fflate";
3476
+ import * as parser from "@babel/parser";
3477
+ import * as t from "@babel/types";
3478
+
3479
+ // ../../node_modules/commander/esm.mjs
3480
+ var import_index = __toESM(require_commander(), 1);
3481
+ var {
3482
+ program,
3483
+ createCommand,
3484
+ createArgument,
3485
+ createOption,
3486
+ CommanderError,
3487
+ InvalidArgumentError,
3488
+ InvalidOptionArgumentError,
3489
+ // deprecated old name
3490
+ Command,
3491
+ Argument,
3492
+ Option,
3493
+ Help
3494
+ } = import_index.default;
3495
+
3496
+ // src/index.ts
3497
+ import { gt, valid } from "semver";
3498
+ import tailwindcss from "@tailwindcss/vite";
3499
+ import react from "@vitejs/plugin-react";
3500
+ import { build } from "vite";
3501
+ var nodeRequire = createRequire(import.meta.url);
3502
+ var packageJson = nodeRequire("../package.json");
3503
+ var builtDefaultApiUrl = "https://p11-api.rarexlabs.com";
3504
+ var defaultApiUrl = process.env.P11_API_URL || builtDefaultApiUrl;
3505
+ var generate = nodeRequire("@babel/generator").default;
3506
+ var traverse = nodeRequire("@babel/traverse").default;
3507
+ var updateCheckIntervalMs = 30 * 60 * 1e3;
3508
+ var updateCheckTimeoutMs = 800;
3509
+ var P11_HISTORY_FILE = "history.json";
3510
+ var P11_HISTORY_DIR_MODE = 448;
3511
+ var P11_HISTORY_FILE_MODE = 384;
3512
+ var P11_HISTORY_LOCK_STALE_MS = 3e4;
3513
+ var P11_HISTORY_LOCK_TIMEOUT_MS = 5e3;
3514
+ var P11_HISTORY_DEFAULT_LIMIT = 20;
3515
+ var P11_RUNTIME_VERSION = "0.0.1";
3516
+ var P11_MANIFEST_FILE = "p11-manifest.json";
3517
+ var cliPackageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
3518
+ var docsTopics = /* @__PURE__ */ new Map([
3519
+ ["index", "docs/index.md"],
3520
+ ["components", "docs/components.md"],
3521
+ ["publishing", "docs/publishing.md"]
3522
+ ]);
3523
+ var exampleFiles = /* @__PURE__ */ new Map([["all-components", "examples/all-components.tsx"]]);
3524
+ var allowedDocumentComponents = /* @__PURE__ */ new Set([
3525
+ "Document",
3526
+ "Page",
3527
+ "Section",
3528
+ "Heading",
3529
+ "Text",
3530
+ "List",
3531
+ "ListItem",
3532
+ "DefinitionList",
3533
+ "DefinitionTerm",
3534
+ "DefinitionDescription",
3535
+ "Quote",
3536
+ "Strikethrough",
3537
+ "CodeBlock",
3538
+ "Table",
3539
+ "TableHeader",
3540
+ "TableBody",
3541
+ "TableRow",
3542
+ "TableHead",
3543
+ "TableCell",
3544
+ "Figure",
3545
+ "Caption",
3546
+ "Divider",
3547
+ "PageBreak"
3548
+ ]);
3549
+ var allowedP11Imports = /* @__PURE__ */ new Set([...allowedDocumentComponents, "code"]);
3550
+ var unsupportedP11Components = /* @__PURE__ */ new Set([
3551
+ "Alert",
3552
+ "Badge",
3553
+ "Button",
3554
+ "Card",
3555
+ "CardHeader",
3556
+ "CardTitle",
3557
+ "CardDescription",
3558
+ "CardContent",
3559
+ "Separator",
3560
+ "Stack",
3561
+ "Tabs",
3562
+ "TabsContent",
3563
+ "TabsList",
3564
+ "TabsTrigger",
3565
+ "Accordion",
3566
+ "AccordionContent",
3567
+ "AccordionItem",
3568
+ "AccordionTrigger"
3569
+ ]);
3570
+ var interactiveNativeTags = /* @__PURE__ */ new Set(["button", "input", "select", "textarea", "form", "nav"]);
3571
+ var commentableComponentNames = /* @__PURE__ */ new Set([
3572
+ "Heading",
3573
+ "Text",
3574
+ "ListItem",
3575
+ "DefinitionTerm",
3576
+ "DefinitionDescription",
3577
+ "Quote",
3578
+ "CodeBlock",
3579
+ "TableHead",
3580
+ "TableCell",
3581
+ "Caption"
3582
+ ]);
3583
+ var commentableNativeTags = /* @__PURE__ */ new Set([
3584
+ "h1",
3585
+ "h2",
3586
+ "h3",
3587
+ "h4",
3588
+ "h5",
3589
+ "h6",
3590
+ "p",
3591
+ "li",
3592
+ "dt",
3593
+ "dd",
3594
+ "blockquote",
3595
+ "pre",
3596
+ "code",
3597
+ "td",
3598
+ "th",
3599
+ "caption",
3600
+ "figcaption"
3601
+ ]);
3602
+ var P11_CODE_SOURCE_LINE_ATTRIBUTE = "data-p11-code-source-line";
3603
+ var P11_SOURCE_FILE_ATTRIBUTE = "data-p11-source-file";
3604
+ var P11_SOURCE_LINE_ATTRIBUTE = "data-p11-source-line";
3605
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
3606
+ main().catch((error) => {
3607
+ console.error(error instanceof Error ? error.message : String(error));
3608
+ process.exit(1);
3609
+ });
3610
+ }
3611
+ async function main() {
3612
+ const program2 = createCliProgram();
3613
+ if (process.argv.length <= 2) {
3614
+ program2.outputHelp();
3615
+ return;
3616
+ }
3617
+ const command = process.argv[2];
3618
+ if (!isKnownTopLevelCommand(program2, command)) throw new Error(`Unknown command: ${command}`);
3619
+ await program2.parseAsync(process.argv);
3620
+ }
3621
+ function createCliProgram() {
3622
+ const program2 = new Command();
3623
+ program2.name("p11").description("Publish and inspect P11 document pages.");
3624
+ program2.addHelpText(
3625
+ "after",
3626
+ `
3627
+
3628
+ Environment:
3629
+ P11_API_URL Defaults to ${builtDefaultApiUrl}`
3630
+ );
3631
+ const publishCommand = program2.command("publish").description("Publish a page module.").argument("[page.tsx]").option("--json", "Print the API response as JSON.").option("--edit-url [url]", "Update an existing page using an edit URL or edit id.").option("--api-url [url]", "Override the P11 API URL.").action(async (input, options) => {
3632
+ await warnIfUpdateAvailable();
3633
+ await publish(input, normalizePublishOptions(options));
3634
+ });
3635
+ allowLegacyParserBehavior(publishCommand);
3636
+ const commentsCommand = program2.command("comments").description("Fetch exported comments for a read/edit URL or id.").argument("[readUrl|editUrl|readId|editId]").option("--json", "Print comments as JSON.").option("--output [file]", "Write comments JSON to a file.").option("--version [n]", "Fetch comments for a specific page version.").option("--api-url [url]", "Override the P11 API URL.").action(async (target, options) => {
3637
+ await warnIfUpdateAvailable();
3638
+ await comments(target, normalizeCommentsOptions(options));
3639
+ });
3640
+ allowLegacyParserBehavior(commentsCommand);
3641
+ program2.command("history").description("List saved publish read/edit URLs.").option("--json", "Print saved history as JSON.").action(async (options) => {
3642
+ await history(normalizeHistoryOptions(options));
3643
+ });
3644
+ const docsCommand = program2.command("docs").description("Print P11 authoring docs.").argument("[topic]", "Docs topic: components or publishing.").action(async (topic) => {
3645
+ await docs(topic);
3646
+ });
3647
+ allowLegacyParserBehavior(docsCommand);
3648
+ const exampleCommand = program2.command("example").description("Print or write a P11 example document.").argument("[name]", "Example name: all-components.").option("--output [file]", "Write the example to a file.").action(async (name, options) => {
3649
+ await example(name, normalizeExampleOptions(options));
3650
+ });
3651
+ allowLegacyParserBehavior(exampleCommand);
3652
+ return program2;
3653
+ }
3654
+ function isKnownTopLevelCommand(program2, command) {
3655
+ return command === "--help" || command === "-h" || command === "help" || program2.commands.some((subcommand) => subcommand.name() === command);
3656
+ }
3657
+ function allowLegacyParserBehavior(command) {
3658
+ return command.allowUnknownOption().allowExcessArguments();
3659
+ }
3660
+ function normalizePublishOptions(options) {
3661
+ return {
3662
+ json: options.json,
3663
+ editUrl: optionString(options.editUrl, "--edit-url requires a URL or edit id."),
3664
+ apiUrl: optionString(options.apiUrl, "--api-url requires a URL.")
3665
+ };
3666
+ }
3667
+ function normalizeCommentsOptions(options) {
3668
+ return {
3669
+ json: options.json,
3670
+ output: optionString(options.output, "--output requires a file path."),
3671
+ version: optionString(options.version, "--version requires a positive integer."),
3672
+ apiUrl: optionString(options.apiUrl, "--api-url requires a URL.")
3673
+ };
3674
+ }
3675
+ function normalizeHistoryOptions(options) {
3676
+ return {
3677
+ json: options.json
3678
+ };
3679
+ }
3680
+ function normalizeExampleOptions(options) {
3681
+ return {
3682
+ output: optionString(options.output, "--output requires a file path.")
3683
+ };
3684
+ }
3685
+ function optionString(value, missingValueMessage) {
3686
+ if (value === true) throw new Error(missingValueMessage);
3687
+ return typeof value === "string" ? value : void 0;
3688
+ }
3689
+ async function publish(input, options) {
3690
+ if (!input) throw new Error("Usage: p11 publish <page.tsx> [--json] [--edit-url URL]");
3691
+ const resolvedInput = path.resolve(input);
3692
+ const inputStat = await stat(resolvedInput).catch(() => null);
3693
+ if (!inputStat) throw new Error(`Path does not exist: ${input}`);
3694
+ if (!inputStat.isFile()) {
3695
+ throw new Error("Input must be a .tsx, .jsx, .ts, or .js page module.");
3696
+ }
3697
+ if (!/\.[cm]?[tj]sx?$/.test(resolvedInput)) {
3698
+ throw new Error("File input must be a .tsx, .jsx, .ts, or .js page module.");
3699
+ }
3700
+ const cleanupDir = await mkdtemp(path.join(process.cwd(), ".p11-build-"));
3701
+ const distDir = path.join(cleanupDir, "dist");
3702
+ await buildPageModule(resolvedInput, distDir);
3703
+ try {
3704
+ await ensureIndexHtml(distDir);
3705
+ const zipBytes = await zipDirectory(distDir);
3706
+ const editUrl = options.editUrl ?? "";
3707
+ const editTarget = editUrl ? parseEditTarget(editUrl) : null;
3708
+ const apiUrl = normalizeApiUrl(String(options.apiUrl ?? editTarget?.apiUrl ?? defaultApiUrl));
3709
+ const url = editTarget ? new URL(`/api/edit/${encodeURIComponent(editTarget.editId)}/page`, apiUrl) : new URL("/api/pages", apiUrl);
3710
+ const uploadBody = new ArrayBuffer(zipBytes.byteLength);
3711
+ new Uint8Array(uploadBody).set(zipBytes);
3712
+ const response = await fetch(url, {
3713
+ method: "POST",
3714
+ headers: {
3715
+ "content-type": "application/zip"
3716
+ },
3717
+ body: uploadBody
3718
+ });
3719
+ const text = await response.text();
3720
+ if (!response.ok) {
3721
+ throw new Error(`Publish failed (${response.status}): ${responseErrorMessage(text)}`);
3722
+ }
3723
+ const data = JSON.parse(text);
3724
+ await appendPublishHistory(data, {
3725
+ apiUrl,
3726
+ source: resolvedInput
3727
+ }).catch((error) => {
3728
+ console.error(`Warning: published, but could not save history: ${errorMessage(error)}`);
3729
+ });
3730
+ if (options.json) {
3731
+ console.log(JSON.stringify(data, null, 2));
3732
+ } else {
3733
+ console.log(data.readUrl ?? data.url);
3734
+ if (data.editUrl) console.log(`editUrl: ${data.editUrl}`);
3735
+ if (data.docId) console.log(`docId: ${data.docId}`);
3736
+ if (data.readId) console.log(`readId: ${data.readId}`);
3737
+ if (data.editId) console.log(`editId: ${data.editId}`);
3738
+ if (data.version) console.log(`version: ${data.version}`);
3739
+ if (data.latestVersion) console.log(`latestVersion: ${data.latestVersion}`);
3740
+ if (data.createdAt) console.log(`createdAt: ${data.createdAt}`);
3741
+ }
3742
+ } finally {
3743
+ if (cleanupDir) await rm(cleanupDir, { recursive: true, force: true });
3744
+ }
3745
+ }
3746
+ async function history(options) {
3747
+ const entries = await readHistoryEntries();
3748
+ if (options.json) {
3749
+ console.log(JSON.stringify({ entries }, null, 2));
3750
+ return;
3751
+ }
3752
+ printHistory(entries, P11_HISTORY_DEFAULT_LIMIT);
3753
+ }
3754
+ async function docs(topic) {
3755
+ const normalizedTopic = topic ?? "index";
3756
+ const relativePath = docsTopics.get(normalizedTopic);
3757
+ if (!relativePath) {
3758
+ throw new Error(`Unknown docs topic: ${normalizedTopic}. Available topics: components, publishing`);
3759
+ }
3760
+ process.stdout.write(await readCliAsset(relativePath));
3761
+ }
3762
+ async function example(name, options) {
3763
+ if (!name) {
3764
+ console.log("Available examples:");
3765
+ for (const exampleName of exampleFiles.keys()) console.log(` ${exampleName}`);
3766
+ console.log("");
3767
+ console.log("Usage: p11 example all-components [--output FILE]");
3768
+ return;
3769
+ }
3770
+ const relativePath = exampleFiles.get(name);
3771
+ if (!relativePath) {
3772
+ throw new Error(`Unknown example: ${name}. Available examples: ${Array.from(exampleFiles.keys()).join(", ")}`);
3773
+ }
3774
+ const contents = await readCliAsset(relativePath);
3775
+ if (options.output) {
3776
+ await writeFile(path.resolve(options.output), contents);
3777
+ return;
3778
+ }
3779
+ process.stdout.write(contents);
3780
+ }
3781
+ async function comments(target, options) {
3782
+ if (!target) {
3783
+ throw new Error("Usage: p11 comments <readUrl|editUrl|readId|editId> [--json] [--output FILE] [--version N]");
3784
+ }
3785
+ const version = options.version === void 0 ? void 0 : parseVersionFlag(String(options.version));
3786
+ const url = commentsApiUrlForTarget(target, {
3787
+ apiUrl: options.apiUrl,
3788
+ version
3789
+ });
3790
+ const response = await fetch(url);
3791
+ const text = await response.text();
3792
+ if (!response.ok) {
3793
+ throw new Error(`Fetch comments failed (${response.status}): ${text}`);
3794
+ }
3795
+ const data = commentExportData(JSON.parse(text));
3796
+ const output = JSON.stringify(data, null, 2);
3797
+ if (options.output !== void 0) {
3798
+ await writeFile(path.resolve(options.output), `${output}
3799
+ `);
3800
+ } else if (options.json) {
3801
+ console.log(output);
3802
+ } else {
3803
+ printComments(data);
3804
+ }
3805
+ }
3806
+ async function appendPublishHistory(data, metadata = {}, filePath = historyFilePath()) {
3807
+ const entry = publishHistoryEntry(data, metadata);
3808
+ if (!entry.readUrl && !entry.editUrl) return;
3809
+ await withHistoryLock(filePath, async () => {
3810
+ const historyFile = await readHistoryFile(filePath);
3811
+ historyFile.entries.push(entry);
3812
+ await writeHistoryFile(filePath, historyFile);
3813
+ });
3814
+ }
3815
+ function publishHistoryEntry(data, metadata) {
3816
+ const readUrl = data.readUrl ?? data.url;
3817
+ return compactObject({
3818
+ savedAt: (/* @__PURE__ */ new Date()).toISOString(),
3819
+ source: metadata.source,
3820
+ apiUrl: metadata.apiUrl,
3821
+ url: data.url,
3822
+ readUrl,
3823
+ editUrl: data.editUrl,
3824
+ docId: data.docId,
3825
+ readId: data.readId,
3826
+ editId: data.editId,
3827
+ version: data.version,
3828
+ latestVersion: data.latestVersion,
3829
+ createdAt: data.createdAt
3830
+ });
3831
+ }
3832
+ async function readHistoryEntries(filePath = historyFilePath()) {
3833
+ return (await readHistoryFile(filePath)).entries;
3834
+ }
3835
+ async function readHistoryFile(filePath) {
3836
+ const raw = await readFile(filePath, "utf8").catch(() => null);
3837
+ if (!raw) return { entries: [] };
3838
+ const parsed = JSON.parse(raw);
3839
+ const entries = Array.isArray(parsed.entries) ? parsed.entries.map(historyEntryFromUnknown).filter((entry) => entry !== null) : [];
3840
+ return { entries };
3841
+ }
3842
+ async function writeHistoryFile(filePath, historyFile) {
3843
+ const historyDir = path.dirname(filePath);
3844
+ await ensurePrivateHistoryDir(historyDir);
3845
+ const tempDir = await mkdtemp(path.join(historyDir, ".history-"));
3846
+ const tempPath = path.join(tempDir, P11_HISTORY_FILE);
3847
+ try {
3848
+ await chmod(tempDir, P11_HISTORY_DIR_MODE);
3849
+ await writeFile(tempPath, `${JSON.stringify(historyFile, null, 2)}
3850
+ `, { mode: P11_HISTORY_FILE_MODE });
3851
+ await chmod(tempPath, P11_HISTORY_FILE_MODE);
3852
+ await rename(tempPath, filePath);
3853
+ await chmod(filePath, P11_HISTORY_FILE_MODE);
3854
+ } finally {
3855
+ await rm(tempDir, { recursive: true, force: true });
3856
+ }
3857
+ }
3858
+ async function ensurePrivateHistoryDir(historyDir) {
3859
+ await mkdir(historyDir, { recursive: true, mode: P11_HISTORY_DIR_MODE });
3860
+ await chmod(historyDir, P11_HISTORY_DIR_MODE);
3861
+ }
3862
+ async function withHistoryLock(filePath, fn) {
3863
+ const release = await acquireHistoryLock(filePath);
3864
+ try {
3865
+ return await fn();
3866
+ } finally {
3867
+ await release();
3868
+ }
3869
+ }
3870
+ async function acquireHistoryLock(filePath) {
3871
+ const historyDir = path.dirname(filePath);
3872
+ await ensurePrivateHistoryDir(historyDir);
3873
+ const lockDir = `${filePath}.lock`;
3874
+ const deadline = Date.now() + P11_HISTORY_LOCK_TIMEOUT_MS;
3875
+ while (true) {
3876
+ try {
3877
+ await mkdir(lockDir, { mode: P11_HISTORY_DIR_MODE });
3878
+ await chmod(lockDir, P11_HISTORY_DIR_MODE);
3879
+ return () => rm(lockDir, { recursive: true, force: true });
3880
+ } catch (error) {
3881
+ if (errorCode(error) !== "EEXIST") throw error;
3882
+ await removeStaleHistoryLock(lockDir);
3883
+ if (Date.now() >= deadline) throw new Error(`Timed out waiting for history lock: ${lockDir}`);
3884
+ await delay(50);
3885
+ }
3886
+ }
3887
+ }
3888
+ async function removeStaleHistoryLock(lockDir) {
3889
+ const lockStat = await stat(lockDir).catch(() => null);
3890
+ if (lockStat && Date.now() - lockStat.mtimeMs > P11_HISTORY_LOCK_STALE_MS) {
3891
+ await rm(lockDir, { recursive: true, force: true });
3892
+ }
3893
+ }
3894
+ function printHistory(entries, limit) {
3895
+ if (entries.length === 0) {
3896
+ console.log(`No history yet. Publish a document to create ${historyFilePath()}.`);
3897
+ return;
3898
+ }
3899
+ const displayEntries = entries.slice(-limit).reverse();
3900
+ for (const [index, entry] of displayEntries.entries()) {
3901
+ const number = entries.length - index;
3902
+ const details = [
3903
+ entry.version ? `version ${entry.version}` : null,
3904
+ entry.docId ? `docId ${entry.docId}` : null,
3905
+ entry.savedAt ? `saved ${entry.savedAt}` : null
3906
+ ].filter(Boolean);
3907
+ console.log(`${number}. ${details.join(" | ")}`);
3908
+ if (entry.source) console.log(` source: ${entry.source}`);
3909
+ if (entry.readUrl) console.log(` readUrl: ${entry.readUrl}`);
3910
+ if (entry.editUrl) console.log(` editUrl: ${entry.editUrl}`);
3911
+ if (!entry.readUrl && entry.url) console.log(` url: ${entry.url}`);
3912
+ if (entry.readId) console.log(` readId: ${entry.readId}`);
3913
+ if (entry.editId) console.log(` editId: ${entry.editId}`);
3914
+ }
3915
+ if (entries.length > displayEntries.length) {
3916
+ console.log(`Showing ${displayEntries.length} of ${entries.length} entries. Use --json for full history.`);
3917
+ }
3918
+ }
3919
+ function historyEntryFromUnknown(value) {
3920
+ if (!value || typeof value !== "object") return null;
3921
+ const entry = value;
3922
+ if (typeof entry.savedAt !== "string") return null;
3923
+ if (typeof entry.readUrl !== "string" && typeof entry.editUrl !== "string") return null;
3924
+ return compactObject({
3925
+ savedAt: entry.savedAt,
3926
+ source: optionalString(entry.source),
3927
+ apiUrl: optionalString(entry.apiUrl),
3928
+ url: optionalString(entry.url),
3929
+ readUrl: optionalString(entry.readUrl),
3930
+ editUrl: optionalString(entry.editUrl),
3931
+ docId: optionalString(entry.docId),
3932
+ readId: optionalString(entry.readId),
3933
+ editId: optionalString(entry.editId),
3934
+ version: optionalNumber(entry.version),
3935
+ latestVersion: optionalNumber(entry.latestVersion),
3936
+ createdAt: optionalString(entry.createdAt)
3937
+ });
3938
+ }
3939
+ function compactObject(value) {
3940
+ return Object.fromEntries(Object.entries(value).filter((entry) => entry[1] !== void 0));
3941
+ }
3942
+ function optionalString(value) {
3943
+ return typeof value === "string" ? value : void 0;
3944
+ }
3945
+ function optionalNumber(value) {
3946
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
3947
+ }
3948
+ function errorCode(error) {
3949
+ return typeof error === "object" && error !== null && "code" in error ? String(error.code) : null;
3950
+ }
3951
+ function delay(ms) {
3952
+ return new Promise((resolve) => setTimeout(resolve, ms));
3953
+ }
3954
+ function historyFilePath() {
3955
+ return path.join(homedir(), ".p11", P11_HISTORY_FILE);
3956
+ }
3957
+ function commentsExportJson(data) {
3958
+ return JSON.stringify(commentExportData(data), null, 2);
3959
+ }
3960
+ function commentExportData(data) {
3961
+ return {
3962
+ ...data,
3963
+ comments: commentThreads(data.comments).map(({ comment, replies }) => ({
3964
+ ...comment,
3965
+ replies
3966
+ }))
3967
+ };
3968
+ }
3969
+ function printComments(data) {
3970
+ if (data.comments.length === 0) {
3971
+ console.log("No comments yet.");
3972
+ return;
3973
+ }
3974
+ for (const comment of data.comments) {
3975
+ const target = comment.endLineNumber ? ` lines ${comment.lineNumber}-${comment.endLineNumber}` : comment.lineNumber ? ` line ${comment.lineNumber}` : "";
3976
+ const resolved = comment.resolvedAt ? " [resolved]" : "";
3977
+ console.log(`[${comment.createdAt}]${target}${resolved} ${comment.name}`);
3978
+ if (comment.quote) console.log(`> ${comment.quote}`);
3979
+ console.log(comment.body);
3980
+ for (const reply of comment.replies ?? []) {
3981
+ const replyResolved = reply.resolvedAt ? " [resolved]" : "";
3982
+ console.log(` [${reply.createdAt}] reply${replyResolved} ${reply.name}`);
3983
+ console.log(` ${reply.body}`);
3984
+ }
3985
+ console.log("");
3986
+ }
3987
+ }
3988
+ function commentThreads(comments2) {
3989
+ const repliesByParent = /* @__PURE__ */ new Map();
3990
+ for (const comment of comments2) {
3991
+ if (!comment.parentId) continue;
3992
+ const replies = repliesByParent.get(comment.parentId) ?? [];
3993
+ replies.push(comment);
3994
+ repliesByParent.set(comment.parentId, replies);
3995
+ }
3996
+ return comments2.filter((comment) => !comment.parentId).map((comment) => ({ comment, replies: repliesByParent.get(comment.id) ?? [] }));
3997
+ }
3998
+ function responseErrorMessage(text) {
3999
+ try {
4000
+ const payload = JSON.parse(text);
4001
+ if (typeof payload.error === "string" && payload.error.trim()) return payload.error;
4002
+ } catch (_error) {
4003
+ }
4004
+ return text;
4005
+ }
4006
+ function errorMessage(error) {
4007
+ return error instanceof Error ? error.message : String(error);
4008
+ }
4009
+ async function readCliAsset(relativePath) {
4010
+ return readFile(path.join(cliPackageRoot, relativePath), "utf8");
4011
+ }
4012
+ async function buildPageModule(inputFile, outDir) {
4013
+ const tempDir = path.dirname(outDir);
4014
+ const entryPath = path.join(tempDir, "main.tsx");
4015
+ const htmlPath = path.join(tempDir, "index.html");
4016
+ const pagePath = path.join(tempDir, "Page.tsx");
4017
+ const componentEntry = nodeRequire.resolve("@p11-core/components");
4018
+ const componentStyles = nodeRequire.resolve("@p11-core/components/styles.css");
4019
+ const pageSource = await readFile(inputFile, "utf8");
4020
+ const pageAst = parsePageSource(pageSource);
4021
+ validatePageAst(pageAst, inputFile);
4022
+ await writeFile(pagePath, addSourceLineAttributes(pageAst, inputFile));
4023
+ await writeFile(
4024
+ entryPath,
4025
+ [
4026
+ 'import * as React from "react";',
4027
+ 'import { createRoot } from "react-dom/client";',
4028
+ 'import "@p11-core/components/styles.css";',
4029
+ 'import { createTextAnnotator, rangeToSelector } from "@recogito/text-annotator";',
4030
+ 'import "@recogito/text-annotator/text-annotator.css";',
4031
+ "",
4032
+ "Object.assign(window, {",
4033
+ " __P11_CREATE_TEXT_ANNOTATOR__: createTextAnnotator,",
4034
+ " __P11_RANGE_TO_SELECTOR__: rangeToSelector",
4035
+ "});",
4036
+ 'import Page from "./Page";',
4037
+ "",
4038
+ 'createRoot(document.getElementById("root")!).render(',
4039
+ " <React.StrictMode>",
4040
+ " <Page />",
4041
+ " </React.StrictMode>",
4042
+ ");"
4043
+ ].join("\n")
4044
+ );
4045
+ await writeFile(
4046
+ htmlPath,
4047
+ [
4048
+ "<!doctype html>",
4049
+ '<html lang="en">',
4050
+ " <head>",
4051
+ ' <meta charset="UTF-8" />',
4052
+ ' <meta name="viewport" content="width=device-width, initial-scale=1.0" />',
4053
+ " <title>Document</title>",
4054
+ " </head>",
4055
+ " <body>",
4056
+ ' <div id="root"></div>',
4057
+ ' <script type="module" src="/main.tsx"></script>',
4058
+ " </body>",
4059
+ "</html>"
4060
+ ].join("\n")
4061
+ );
4062
+ await build({
4063
+ root: tempDir,
4064
+ base: "./",
4065
+ configFile: false,
4066
+ logLevel: "warn",
4067
+ plugins: [react(), tailwindcss()],
4068
+ resolve: {
4069
+ alias: {
4070
+ "@p11-core/components/styles.css": componentStyles,
4071
+ "@p11-core/components": componentEntry,
4072
+ "react/jsx-runtime": nodeRequire.resolve("react/jsx-runtime"),
4073
+ "react/jsx-dev-runtime": nodeRequire.resolve("react/jsx-dev-runtime"),
4074
+ "react-dom/client": nodeRequire.resolve("react-dom/client"),
4075
+ "react-dom": nodeRequire.resolve("react-dom"),
4076
+ react: nodeRequire.resolve("react")
4077
+ },
4078
+ dedupe: ["react", "react-dom"]
4079
+ },
4080
+ build: {
4081
+ outDir: path.relative(tempDir, outDir),
4082
+ emptyOutDir: true,
4083
+ assetsDir: "assets"
4084
+ }
4085
+ });
4086
+ await writeFile(path.join(outDir, P11_MANIFEST_FILE), JSON.stringify({ runtimeVersion: P11_RUNTIME_VERSION }, null, 2));
4087
+ }
4088
+ function validatePageSource(code, inputFile = "page.tsx") {
4089
+ validatePageAst(parsePageSource(code), inputFile);
4090
+ }
4091
+ function parsePageSource(code) {
4092
+ return parser.parse(code, {
4093
+ sourceType: "module",
4094
+ plugins: ["jsx", "typescript"]
4095
+ });
4096
+ }
4097
+ function validatePageAst(ast, inputFile) {
4098
+ const errors = [];
4099
+ const p11NamespaceImports = /* @__PURE__ */ new Set();
4100
+ const p11NamedImports = /* @__PURE__ */ new Map();
4101
+ traverse(ast, {
4102
+ ImportDeclaration(importPath) {
4103
+ if (importPath.node.source.value !== "@p11-core/components") return;
4104
+ for (const specifier of importPath.node.specifiers) {
4105
+ if (specifier.type === "ImportNamespaceSpecifier") {
4106
+ p11NamespaceImports.add(specifier.local.name);
4107
+ continue;
4108
+ }
4109
+ if (specifier.type === "ImportDefaultSpecifier") {
4110
+ errors.push(validationMessage(inputFile, specifier.loc?.start.line, "default import", "Use named document components from @p11-core/components."));
4111
+ continue;
4112
+ }
4113
+ const importedName = importedSpecifierName(specifier.imported);
4114
+ p11NamedImports.set(specifier.local.name, importedName);
4115
+ if (!allowedP11Imports.has(importedName)) {
4116
+ errors.push(validationMessage(inputFile, specifier.loc?.start.line, importedName, recommendationForComponent(importedName)));
4117
+ }
4118
+ }
4119
+ },
4120
+ JSXOpeningElement(jsxPath) {
4121
+ const name = jsxPath.node.name;
4122
+ const line = jsxPath.node.loc?.start.line;
4123
+ if (name.type === "JSXIdentifier") {
4124
+ const tagName = name.name;
4125
+ if (interactiveNativeTags.has(tagName)) {
4126
+ errors.push(validationMessage(inputFile, line, `<${tagName}>`, "Use document-safe markup such as Text, List, Table, links, or figures instead."));
4127
+ return;
4128
+ }
4129
+ if (/^[a-z]/.test(tagName)) {
4130
+ return;
4131
+ }
4132
+ const importedName = p11NamedImports.get(tagName);
4133
+ if (importedName && !allowedDocumentComponents.has(importedName)) {
4134
+ errors.push(validationMessage(inputFile, line, `<${tagName}>`, recommendationForComponent(importedName)));
4135
+ return;
4136
+ }
4137
+ if (unsupportedP11Components.has(tagName)) {
4138
+ errors.push(validationMessage(inputFile, line, `<${tagName}>`, recommendationForComponent(tagName)));
4139
+ }
4140
+ return;
4141
+ }
4142
+ const memberName = jsxMemberName(name);
4143
+ if (!memberName) return;
4144
+ const [namespace, componentName] = memberName.split(".", 2);
4145
+ if (p11NamespaceImports.has(namespace) && !allowedDocumentComponents.has(componentName)) {
4146
+ errors.push(validationMessage(inputFile, line, `<${memberName}>`, recommendationForComponent(componentName)));
4147
+ }
4148
+ }
4149
+ });
4150
+ if (errors.length > 0) {
4151
+ throw new Error(["Document validation failed:", ...errors].join("\n"));
4152
+ }
4153
+ }
4154
+ function addSourceLineAttributes(ast, inputFile) {
4155
+ const sourceFileName = path.basename(inputFile);
4156
+ const codeTemplateTagNames = p11CodeTemplateTagNames(ast);
4157
+ traverse(ast, {
4158
+ JSXOpeningElement(jsxPath) {
4159
+ if (jsxPath.node.name.type === "JSXNamespacedName") return;
4160
+ if (jsxPath.node.name.type === "JSXIdentifier" && jsxPath.node.name.name === "Fragment") return;
4161
+ if (!isCommentAnchorName(jsxPath.node.name)) return;
4162
+ if (!jsxPath.node.loc) return;
4163
+ if (hasJsxAttribute(jsxPath.node, P11_SOURCE_LINE_ATTRIBUTE)) {
4164
+ return;
4165
+ }
4166
+ jsxPath.node.attributes.push(
4167
+ jsxStringAttribute(P11_SOURCE_LINE_ATTRIBUTE, String(jsxPath.node.loc.start.line)),
4168
+ jsxStringAttribute(P11_SOURCE_FILE_ATTRIBUTE, sourceFileName)
4169
+ );
4170
+ const codeSourceLine = codeTemplateSourceLineFor(jsxPath, codeTemplateTagNames);
4171
+ if (codeSourceLine && !hasJsxAttribute(jsxPath.node, P11_CODE_SOURCE_LINE_ATTRIBUTE)) {
4172
+ jsxPath.node.attributes.push(jsxStringAttribute(P11_CODE_SOURCE_LINE_ATTRIBUTE, String(codeSourceLine)));
4173
+ }
4174
+ }
4175
+ });
4176
+ return generate(ast, {
4177
+ retainLines: true,
4178
+ sourceMaps: false
4179
+ }).code;
4180
+ }
4181
+ function p11CodeTemplateTagNames(ast) {
4182
+ const names = /* @__PURE__ */ new Set(["code"]);
4183
+ for (const statement of ast.program.body) {
4184
+ if (statement.type !== "ImportDeclaration" || statement.source.value !== "@p11-core/components") continue;
4185
+ for (const specifier of statement.specifiers) {
4186
+ if (specifier.type !== "ImportSpecifier" || importedSpecifierName(specifier.imported) !== "code") continue;
4187
+ names.add(specifier.local.name);
4188
+ }
4189
+ }
4190
+ return names;
4191
+ }
4192
+ function hasJsxAttribute(node, name) {
4193
+ return node.attributes.some((attribute) => attribute.type === "JSXAttribute" && attribute.name.name === name);
4194
+ }
4195
+ function jsxStringAttribute(name, value) {
4196
+ return t.jsxAttribute(t.jsxIdentifier(name), t.stringLiteral(value));
4197
+ }
4198
+ function codeTemplateSourceLineFor(jsxPath, codeTemplateTagNames) {
4199
+ if (!isCodeBlockName(jsxPath.node.name)) return null;
4200
+ for (const attribute of jsxPath.node.attributes) {
4201
+ if (attribute.type !== "JSXAttribute" || attribute.name.name !== "source") continue;
4202
+ const expression = attribute.value?.type === "JSXExpressionContainer" ? attribute.value.expression : null;
4203
+ const line = codeTemplateExpressionSourceLine(expression, codeTemplateTagNames);
4204
+ if (line) return line;
4205
+ }
4206
+ const parent = jsxPath.parent;
4207
+ if (!parent || parent.type !== "JSXElement") return null;
4208
+ for (const child of parent.children) {
4209
+ if (child.type !== "JSXExpressionContainer") continue;
4210
+ const line = codeTemplateExpressionSourceLine(child.expression, codeTemplateTagNames);
4211
+ if (line) return line;
4212
+ }
4213
+ return null;
4214
+ }
4215
+ function isCodeBlockName(name) {
4216
+ return name.type === "JSXIdentifier" ? name.name === "CodeBlock" : name.type === "JSXMemberExpression" && name.property.name === "CodeBlock";
4217
+ }
4218
+ function codeTemplateExpressionSourceLine(expression, codeTemplateTagNames) {
4219
+ if (!expression || expression.type !== "TaggedTemplateExpression") return null;
4220
+ if (!isCodeTemplateTag(expression.tag, codeTemplateTagNames)) return null;
4221
+ const firstQuasi = expression.quasi.quasis[0];
4222
+ const startLine = firstQuasi?.loc?.start.line;
4223
+ if (!startLine) return null;
4224
+ return startLine + (/^(?:\r\n|\r|\n)/.test(firstQuasi.value.raw) ? 1 : 0);
4225
+ }
4226
+ function isCodeTemplateTag(tag, codeTemplateTagNames) {
4227
+ if (tag.type === "Identifier") return codeTemplateTagNames.has(tag.name);
4228
+ return tag.type === "MemberExpression" && tag.property.type === "Identifier" && tag.property.name === "code";
4229
+ }
4230
+ function importedSpecifierName(imported) {
4231
+ return imported.type === "StringLiteral" ? imported.value : imported.name;
4232
+ }
4233
+ function jsxMemberName(name) {
4234
+ if (name.type !== "JSXMemberExpression") return null;
4235
+ const parts = [name.property.name];
4236
+ let current = name.object;
4237
+ while (current.type === "JSXMemberExpression") {
4238
+ parts.push(current.property.name);
4239
+ current = current.object;
4240
+ }
4241
+ if (current.type !== "JSXIdentifier") return null;
4242
+ parts.push(current.name);
4243
+ return parts.reverse().join(".");
4244
+ }
4245
+ function isCommentAnchorName(name) {
4246
+ const tagName = name.type === "JSXIdentifier" ? name.name : name.type === "JSXMemberExpression" ? name.property.name : "";
4247
+ return commentableNativeTags.has(tagName) || commentableComponentNames.has(tagName);
4248
+ }
4249
+ function validationMessage(inputFile, line, item, recommendation) {
4250
+ const location = line ? `${path.basename(inputFile)}:${line}` : path.basename(inputFile);
4251
+ return `${location}: unsupported document content ${item}. ${recommendation}`;
4252
+ }
4253
+ function recommendationForComponent(name) {
4254
+ if (name === "Button") return "Use a link or document text instead of an interactive button.";
4255
+ if (name === "Tabs" || name.startsWith("Tabs")) return "Use Heading, Section, List, or Table to show all document content at once.";
4256
+ if (name === "Accordion" || name.startsWith("Accordion")) return "Use Heading and Section so the document remains fully printable.";
4257
+ if (name === "Card" || name.startsWith("Card") || name === "Alert" || name === "Badge") {
4258
+ return "Use Section, Heading, Text, Quote, Table, Figure, or Divider for brandless document layout.";
4259
+ }
4260
+ return "Use only document-safe components from @p11-core/components.";
4261
+ }
4262
+ async function ensureIndexHtml(dir) {
4263
+ const indexPath = path.join(dir, "index.html");
4264
+ const result = await stat(indexPath).catch(() => null);
4265
+ if (!result?.isFile()) throw new Error(`Missing index.html at root: ${dir}`);
4266
+ }
4267
+ async function zipDirectory(dir) {
4268
+ const entries = {};
4269
+ await collectFiles(dir, dir, entries);
4270
+ return zipSync(entries, { level: 6 });
4271
+ }
4272
+ async function collectFiles(root, current, entries) {
4273
+ const items = await readdir(current, { withFileTypes: true });
4274
+ for (const item of items) {
4275
+ const absolutePath = path.join(current, item.name);
4276
+ const relativePath = path.relative(root, absolutePath).split(path.sep).join("/");
4277
+ if (item.isDirectory()) {
4278
+ await collectFiles(root, absolutePath, entries);
4279
+ } else if (item.isFile()) {
4280
+ entries[relativePath] = new Uint8Array(await readFile(absolutePath));
4281
+ }
4282
+ }
4283
+ }
4284
+ function parseEditId(value) {
4285
+ return parseEditTarget(value).editId;
4286
+ }
4287
+ function parseReadId(value) {
4288
+ return parseAccessTarget(value, ["read"], "a read URL with /r/<readId> or a read id").id;
4289
+ }
4290
+ function parseEditTarget(value) {
4291
+ const target = parseAccessTarget(value, ["edit"], "an edit URL with /e/<editId> or an edit id");
4292
+ return {
4293
+ editId: target.id,
4294
+ apiUrl: target.apiUrl
4295
+ };
4296
+ }
4297
+ function parseCommentsTarget(value) {
4298
+ return parseAccessTarget(value, ["read", "edit"], "a read/edit URL or id", { parseVersion: true });
4299
+ }
4300
+ function commentsApiUrlForTarget(value, options = {}) {
4301
+ const commentsTarget = parseCommentsTarget(value);
4302
+ const apiUrl = normalizeApiUrl(String(options.apiUrl ?? commentsTarget.apiUrl ?? defaultApiUrl));
4303
+ const endpoint = commentsTarget.kind === "read" ? `/api/read/${encodeURIComponent(commentsTarget.id)}/comments/export` : `/api/edit/${encodeURIComponent(commentsTarget.id)}/comments`;
4304
+ const url = new URL(endpoint, apiUrl);
4305
+ const version = options.version ?? commentsTarget.version;
4306
+ if (version !== void 0) url.searchParams.set("v", String(version));
4307
+ return url;
4308
+ }
4309
+ function parseAccessTarget(value, allowedKinds, expected, options = {}) {
4310
+ const trimmed = value.trim();
4311
+ if (!trimmed) throw new Error(`Missing ${expected}.`);
4312
+ try {
4313
+ const parsed = new URL(trimmed);
4314
+ const match = parsed.pathname.match(/^\/([re])\/([^/]+)\/?$/);
4315
+ if (!match) throw new Error(`Expected ${expected}.`);
4316
+ const kind = match[1] === "r" ? "read" : "edit";
4317
+ if (!allowedKinds.includes(kind)) throw new Error(`Expected ${expected}.`);
4318
+ const target = {
4319
+ kind,
4320
+ id: decodeURIComponent(match[2]),
4321
+ apiUrl: parsed.origin,
4322
+ ...options.parseVersion && parsed.searchParams.has("v") ? { version: parseUrlVersion(parsed.searchParams.get("v")) } : {}
4323
+ };
4324
+ validateAccessTarget(target, expected);
4325
+ return target;
4326
+ } catch (error) {
4327
+ if (error instanceof TypeError) {
4328
+ const kind = trimmed.startsWith("edit_") ? "edit" : trimmed.startsWith("read_") ? "read" : null;
4329
+ if (!kind || !allowedKinds.includes(kind)) throw new Error(`Invalid ${allowedKinds[0]} id.`);
4330
+ const target = {
4331
+ kind,
4332
+ id: trimmed
4333
+ };
4334
+ validateAccessTarget(target, expected);
4335
+ return target;
4336
+ }
4337
+ throw error;
4338
+ }
4339
+ }
4340
+ function validateAccessTarget(target, expected) {
4341
+ const prefix = target.kind === "read" ? "read" : "edit";
4342
+ if (!new RegExp(`^${prefix}_[A-Za-z0-9_-]{6,80}$`).test(target.id)) throw new Error(`Invalid ${expected}.`);
4343
+ }
4344
+ function normalizeApiUrl(value) {
4345
+ return value.endsWith("/") ? value.slice(0, -1) : value;
4346
+ }
4347
+ async function warnIfUpdateAvailable() {
4348
+ if (process.env.P11_DISABLE_UPDATE_CHECK) return;
4349
+ try {
4350
+ const cachePath = updateCheckCachePath();
4351
+ const checkedAt = await readUpdateCheckTime(cachePath);
4352
+ if (checkedAt && Date.now() - checkedAt.getTime() < updateCheckIntervalMs) return;
4353
+ await writeUpdateCheckTime(cachePath);
4354
+ const latestVersion = await fetchLatestVersion();
4355
+ if (!latestVersion || !isNewerVersion(latestVersion, packageJson.version)) return;
4356
+ console.error(`p11 ${latestVersion} is available. Current: ${packageJson.version}`);
4357
+ console.error("Run: npm install -g @p11-core/cli@latest");
4358
+ console.error("Or: npx @p11-core/cli@latest ...");
4359
+ } catch {
4360
+ }
4361
+ }
4362
+ async function fetchLatestVersion() {
4363
+ const controller = new AbortController();
4364
+ const timeout = setTimeout(() => controller.abort(), updateCheckTimeoutMs);
4365
+ try {
4366
+ const response = await fetch(`https://registry.npmjs.org/${encodeURIComponent(packageJson.name)}/latest`, {
4367
+ signal: controller.signal,
4368
+ headers: {
4369
+ accept: "application/json"
4370
+ }
4371
+ });
4372
+ if (!response.ok) return null;
4373
+ const data = await response.json();
4374
+ return typeof data.version === "string" ? data.version : null;
4375
+ } finally {
4376
+ clearTimeout(timeout);
4377
+ }
4378
+ }
4379
+ async function readUpdateCheckTime(cachePath) {
4380
+ const raw = await readFile(cachePath, "utf8").catch(() => null);
4381
+ if (!raw) return null;
4382
+ const parsed = JSON.parse(raw);
4383
+ if (!parsed.checkedAt) return null;
4384
+ const checkedAt = new Date(parsed.checkedAt);
4385
+ return Number.isNaN(checkedAt.getTime()) ? null : checkedAt;
4386
+ }
4387
+ async function writeUpdateCheckTime(cachePath) {
4388
+ await mkdir(path.dirname(cachePath), { recursive: true });
4389
+ const data = {
4390
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString()
4391
+ };
4392
+ await writeFile(cachePath, `${JSON.stringify(data, null, 2)}
4393
+ `);
4394
+ }
4395
+ function updateCheckCachePath() {
4396
+ const cacheRoot = process.env.XDG_CACHE_HOME || path.join(homedir(), ".cache");
4397
+ return path.join(cacheRoot, "p11", "update-check.json");
4398
+ }
4399
+ function isNewerVersion(latestVersion, currentVersion) {
4400
+ return Boolean(valid(latestVersion) && valid(currentVersion) && gt(latestVersion, currentVersion));
4401
+ }
4402
+ function parseVersionFlag(value) {
4403
+ if (!/^[1-9]\d*$/.test(value)) throw new Error("--version requires a positive integer.");
4404
+ const version = Number(value);
4405
+ if (!Number.isSafeInteger(version)) throw new Error("--version is too large.");
4406
+ return version;
4407
+ }
4408
+ function parseUrlVersion(value) {
4409
+ try {
4410
+ return parseVersionFlag(String(value ?? ""));
4411
+ } catch (_error) {
4412
+ throw new Error("URL version must be a positive integer.");
4413
+ }
4414
+ }
4415
+ export {
4416
+ addSourceLineAttributes,
4417
+ appendPublishHistory,
4418
+ buildPageModule,
4419
+ commentsApiUrlForTarget,
4420
+ commentsExportJson,
4421
+ isNewerVersion,
4422
+ parseCommentsTarget,
4423
+ parseEditId,
4424
+ parseReadId,
4425
+ readHistoryEntries,
4426
+ validatePageSource
4427
+ };