@tiledev/tile-push-cli 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4462 @@
1
+ #!/usr/bin/env node
2
+ import { i as loadCredentials, n as TilePushClient, o as saveCredentials, r as credentialsDiagnostic, t as TilePushApiError } from "../apiClient-Dxz7PXQr.mjs";
3
+ import { createRequire } from "node:module";
4
+ import fs, { existsSync, readFileSync, statSync } from "node:fs";
5
+ import fs$1, { constants, readFile, writeFile } from "node:fs/promises";
6
+ import path, { join, relative } from "node:path";
7
+ import os, { homedir } from "node:os";
8
+ import childProcess, { execFile } from "node:child_process";
9
+ import process$1 from "node:process";
10
+ import { deploy, handleBundleDelete, handleBundleList, handleBundleSetEnabled, handleBundleShow, handleBundleUpdate, handleChannel, handleCreateFingerprint, handleFingerprint, handlePromote, handleRollback, handleSetChannel, normalizeRolloutPercentage } from "hot-updater/internal/commands";
11
+ import fs$2 from "fs";
12
+ import path$1 from "path";
13
+ import { Buffer as Buffer$1 } from "node:buffer";
14
+ import { fileURLToPath } from "node:url";
15
+ import { promisify } from "node:util";
16
+ import { createInterface } from "node:readline";
17
+ //#region \0rolldown/runtime.js
18
+ var __create = Object.create;
19
+ var __defProp = Object.defineProperty;
20
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
21
+ var __getOwnPropNames = Object.getOwnPropertyNames;
22
+ var __getProtoOf = Object.getPrototypeOf;
23
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
24
+ var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
25
+ var __copyProps = (to, from, except, desc) => {
26
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
27
+ key = keys[i];
28
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
29
+ get: ((k) => from[k]).bind(null, key),
30
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
31
+ });
32
+ }
33
+ return to;
34
+ };
35
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
36
+ value: mod,
37
+ enumerable: true
38
+ }) : target, mod));
39
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
40
+ //#endregion
41
+ //#region ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/error.js
42
+ var require_error = /* @__PURE__ */ __commonJSMin(((exports) => {
43
+ /**
44
+ * CommanderError class
45
+ */
46
+ var CommanderError = class extends Error {
47
+ /**
48
+ * Constructs the CommanderError class
49
+ * @param {number} exitCode suggested exit code which could be used with process.exit
50
+ * @param {string} code an id string representing the error
51
+ * @param {string} message human-readable description of the error
52
+ */
53
+ constructor(exitCode, code, message) {
54
+ super(message);
55
+ Error.captureStackTrace(this, this.constructor);
56
+ this.name = this.constructor.name;
57
+ this.code = code;
58
+ this.exitCode = exitCode;
59
+ this.nestedError = void 0;
60
+ }
61
+ };
62
+ /**
63
+ * InvalidArgumentError class
64
+ */
65
+ var InvalidArgumentError = class extends CommanderError {
66
+ /**
67
+ * Constructs the InvalidArgumentError class
68
+ * @param {string} [message] explanation of why argument is invalid
69
+ */
70
+ constructor(message) {
71
+ super(1, "commander.invalidArgument", message);
72
+ Error.captureStackTrace(this, this.constructor);
73
+ this.name = this.constructor.name;
74
+ }
75
+ };
76
+ exports.CommanderError = CommanderError;
77
+ exports.InvalidArgumentError = InvalidArgumentError;
78
+ }));
79
+ //#endregion
80
+ //#region ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/argument.js
81
+ var require_argument = /* @__PURE__ */ __commonJSMin(((exports) => {
82
+ const { InvalidArgumentError } = require_error();
83
+ var Argument = class {
84
+ /**
85
+ * Initialize a new command argument with the given name and description.
86
+ * The default is that the argument is required, and you can explicitly
87
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
88
+ *
89
+ * @param {string} name
90
+ * @param {string} [description]
91
+ */
92
+ constructor(name, description) {
93
+ this.description = description || "";
94
+ this.variadic = false;
95
+ this.parseArg = void 0;
96
+ this.defaultValue = void 0;
97
+ this.defaultValueDescription = void 0;
98
+ this.argChoices = void 0;
99
+ switch (name[0]) {
100
+ case "<":
101
+ this.required = true;
102
+ this._name = name.slice(1, -1);
103
+ break;
104
+ case "[":
105
+ this.required = false;
106
+ this._name = name.slice(1, -1);
107
+ break;
108
+ default:
109
+ this.required = true;
110
+ this._name = name;
111
+ break;
112
+ }
113
+ if (this._name.endsWith("...")) {
114
+ this.variadic = true;
115
+ this._name = this._name.slice(0, -3);
116
+ }
117
+ }
118
+ /**
119
+ * Return argument name.
120
+ *
121
+ * @return {string}
122
+ */
123
+ name() {
124
+ return this._name;
125
+ }
126
+ /**
127
+ * @package
128
+ */
129
+ _collectValue(value, previous) {
130
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
131
+ previous.push(value);
132
+ return previous;
133
+ }
134
+ /**
135
+ * Set the default value, and optionally supply the description to be displayed in the help.
136
+ *
137
+ * @param {*} value
138
+ * @param {string} [description]
139
+ * @return {Argument}
140
+ */
141
+ default(value, description) {
142
+ this.defaultValue = value;
143
+ this.defaultValueDescription = description;
144
+ return this;
145
+ }
146
+ /**
147
+ * Set the custom handler for processing CLI command arguments into argument values.
148
+ *
149
+ * @param {Function} [fn]
150
+ * @return {Argument}
151
+ */
152
+ argParser(fn) {
153
+ this.parseArg = fn;
154
+ return this;
155
+ }
156
+ /**
157
+ * Only allow argument value to be one of choices.
158
+ *
159
+ * @param {string[]} values
160
+ * @return {Argument}
161
+ */
162
+ choices(values) {
163
+ this.argChoices = values.slice();
164
+ this.parseArg = (arg, previous) => {
165
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
166
+ if (this.variadic) return this._collectValue(arg, previous);
167
+ return arg;
168
+ };
169
+ return this;
170
+ }
171
+ /**
172
+ * Make argument required.
173
+ *
174
+ * @returns {Argument}
175
+ */
176
+ argRequired() {
177
+ this.required = true;
178
+ return this;
179
+ }
180
+ /**
181
+ * Make argument optional.
182
+ *
183
+ * @returns {Argument}
184
+ */
185
+ argOptional() {
186
+ this.required = false;
187
+ return this;
188
+ }
189
+ };
190
+ /**
191
+ * Takes an argument and returns its human readable equivalent for help usage.
192
+ *
193
+ * @param {Argument} arg
194
+ * @return {string}
195
+ * @private
196
+ */
197
+ function humanReadableArgName(arg) {
198
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
199
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
200
+ }
201
+ exports.Argument = Argument;
202
+ exports.humanReadableArgName = humanReadableArgName;
203
+ }));
204
+ //#endregion
205
+ //#region ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/help.js
206
+ var require_help = /* @__PURE__ */ __commonJSMin(((exports) => {
207
+ const { humanReadableArgName } = require_argument();
208
+ /**
209
+ * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
210
+ * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
211
+ * @typedef { import("./argument.js").Argument } Argument
212
+ * @typedef { import("./command.js").Command } Command
213
+ * @typedef { import("./option.js").Option } Option
214
+ */
215
+ var Help = class {
216
+ constructor() {
217
+ this.helpWidth = void 0;
218
+ this.minWidthToWrap = 40;
219
+ this.sortSubcommands = false;
220
+ this.sortOptions = false;
221
+ this.showGlobalOptions = false;
222
+ }
223
+ /**
224
+ * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
225
+ * and just before calling `formatHelp()`.
226
+ *
227
+ * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
228
+ *
229
+ * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
230
+ */
231
+ prepareContext(contextOptions) {
232
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
233
+ }
234
+ /**
235
+ * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
236
+ *
237
+ * @param {Command} cmd
238
+ * @returns {Command[]}
239
+ */
240
+ visibleCommands(cmd) {
241
+ const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
242
+ const helpCommand = cmd._getHelpCommand();
243
+ if (helpCommand && !helpCommand._hidden) visibleCommands.push(helpCommand);
244
+ if (this.sortSubcommands) visibleCommands.sort((a, b) => {
245
+ return a.name().localeCompare(b.name());
246
+ });
247
+ return visibleCommands;
248
+ }
249
+ /**
250
+ * Compare options for sort.
251
+ *
252
+ * @param {Option} a
253
+ * @param {Option} b
254
+ * @returns {number}
255
+ */
256
+ compareOptions(a, b) {
257
+ const getSortKey = (option) => {
258
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
259
+ };
260
+ return getSortKey(a).localeCompare(getSortKey(b));
261
+ }
262
+ /**
263
+ * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
264
+ *
265
+ * @param {Command} cmd
266
+ * @returns {Option[]}
267
+ */
268
+ visibleOptions(cmd) {
269
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
270
+ const helpOption = cmd._getHelpOption();
271
+ if (helpOption && !helpOption.hidden) {
272
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
273
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
274
+ if (!removeShort && !removeLong) visibleOptions.push(helpOption);
275
+ else if (helpOption.long && !removeLong) visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
276
+ else if (helpOption.short && !removeShort) visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
277
+ }
278
+ if (this.sortOptions) visibleOptions.sort(this.compareOptions);
279
+ return visibleOptions;
280
+ }
281
+ /**
282
+ * Get an array of the visible global options. (Not including help.)
283
+ *
284
+ * @param {Command} cmd
285
+ * @returns {Option[]}
286
+ */
287
+ visibleGlobalOptions(cmd) {
288
+ if (!this.showGlobalOptions) return [];
289
+ const globalOptions = [];
290
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
291
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
292
+ globalOptions.push(...visibleOptions);
293
+ }
294
+ if (this.sortOptions) globalOptions.sort(this.compareOptions);
295
+ return globalOptions;
296
+ }
297
+ /**
298
+ * Get an array of the arguments if any have a description.
299
+ *
300
+ * @param {Command} cmd
301
+ * @returns {Argument[]}
302
+ */
303
+ visibleArguments(cmd) {
304
+ if (cmd._argsDescription) cmd.registeredArguments.forEach((argument) => {
305
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
306
+ });
307
+ if (cmd.registeredArguments.find((argument) => argument.description)) return cmd.registeredArguments;
308
+ return [];
309
+ }
310
+ /**
311
+ * Get the command term to show in the list of subcommands.
312
+ *
313
+ * @param {Command} cmd
314
+ * @returns {string}
315
+ */
316
+ subcommandTerm(cmd) {
317
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
318
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
319
+ }
320
+ /**
321
+ * Get the option term to show in the list of options.
322
+ *
323
+ * @param {Option} option
324
+ * @returns {string}
325
+ */
326
+ optionTerm(option) {
327
+ return option.flags;
328
+ }
329
+ /**
330
+ * Get the argument term to show in the list of arguments.
331
+ *
332
+ * @param {Argument} argument
333
+ * @returns {string}
334
+ */
335
+ argumentTerm(argument) {
336
+ return argument.name();
337
+ }
338
+ /**
339
+ * Get the longest command term length.
340
+ *
341
+ * @param {Command} cmd
342
+ * @param {Help} helper
343
+ * @returns {number}
344
+ */
345
+ longestSubcommandTermLength(cmd, helper) {
346
+ return helper.visibleCommands(cmd).reduce((max, command) => {
347
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
348
+ }, 0);
349
+ }
350
+ /**
351
+ * Get the longest option term length.
352
+ *
353
+ * @param {Command} cmd
354
+ * @param {Help} helper
355
+ * @returns {number}
356
+ */
357
+ longestOptionTermLength(cmd, helper) {
358
+ return helper.visibleOptions(cmd).reduce((max, option) => {
359
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
360
+ }, 0);
361
+ }
362
+ /**
363
+ * Get the longest global option term length.
364
+ *
365
+ * @param {Command} cmd
366
+ * @param {Help} helper
367
+ * @returns {number}
368
+ */
369
+ longestGlobalOptionTermLength(cmd, helper) {
370
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
371
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
372
+ }, 0);
373
+ }
374
+ /**
375
+ * Get the longest argument term length.
376
+ *
377
+ * @param {Command} cmd
378
+ * @param {Help} helper
379
+ * @returns {number}
380
+ */
381
+ longestArgumentTermLength(cmd, helper) {
382
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
383
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
384
+ }, 0);
385
+ }
386
+ /**
387
+ * Get the command usage to be displayed at the top of the built-in help.
388
+ *
389
+ * @param {Command} cmd
390
+ * @returns {string}
391
+ */
392
+ commandUsage(cmd) {
393
+ let cmdName = cmd._name;
394
+ if (cmd._aliases[0]) cmdName = cmdName + "|" + cmd._aliases[0];
395
+ let ancestorCmdNames = "";
396
+ for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
397
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
398
+ }
399
+ /**
400
+ * Get the description for the command.
401
+ *
402
+ * @param {Command} cmd
403
+ * @returns {string}
404
+ */
405
+ commandDescription(cmd) {
406
+ return cmd.description();
407
+ }
408
+ /**
409
+ * Get the subcommand summary to show in the list of subcommands.
410
+ * (Fallback to description for backwards compatibility.)
411
+ *
412
+ * @param {Command} cmd
413
+ * @returns {string}
414
+ */
415
+ subcommandDescription(cmd) {
416
+ return cmd.summary() || cmd.description();
417
+ }
418
+ /**
419
+ * Get the option description to show in the list of options.
420
+ *
421
+ * @param {Option} option
422
+ * @return {string}
423
+ */
424
+ optionDescription(option) {
425
+ const extraInfo = [];
426
+ if (option.argChoices) extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
427
+ if (option.defaultValue !== void 0) {
428
+ if (option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean") extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
429
+ }
430
+ if (option.presetArg !== void 0 && option.optional) extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
431
+ if (option.envVar !== void 0) extraInfo.push(`env: ${option.envVar}`);
432
+ if (extraInfo.length > 0) {
433
+ const extraDescription = `(${extraInfo.join(", ")})`;
434
+ if (option.description) return `${option.description} ${extraDescription}`;
435
+ return extraDescription;
436
+ }
437
+ return option.description;
438
+ }
439
+ /**
440
+ * Get the argument description to show in the list of arguments.
441
+ *
442
+ * @param {Argument} argument
443
+ * @return {string}
444
+ */
445
+ argumentDescription(argument) {
446
+ const extraInfo = [];
447
+ if (argument.argChoices) extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
448
+ if (argument.defaultValue !== void 0) extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
449
+ if (extraInfo.length > 0) {
450
+ const extraDescription = `(${extraInfo.join(", ")})`;
451
+ if (argument.description) return `${argument.description} ${extraDescription}`;
452
+ return extraDescription;
453
+ }
454
+ return argument.description;
455
+ }
456
+ /**
457
+ * Format a list of items, given a heading and an array of formatted items.
458
+ *
459
+ * @param {string} heading
460
+ * @param {string[]} items
461
+ * @param {Help} helper
462
+ * @returns string[]
463
+ */
464
+ formatItemList(heading, items, helper) {
465
+ if (items.length === 0) return [];
466
+ return [
467
+ helper.styleTitle(heading),
468
+ ...items,
469
+ ""
470
+ ];
471
+ }
472
+ /**
473
+ * Group items by their help group heading.
474
+ *
475
+ * @param {Command[] | Option[]} unsortedItems
476
+ * @param {Command[] | Option[]} visibleItems
477
+ * @param {Function} getGroup
478
+ * @returns {Map<string, Command[] | Option[]>}
479
+ */
480
+ groupItems(unsortedItems, visibleItems, getGroup) {
481
+ const result = /* @__PURE__ */ new Map();
482
+ unsortedItems.forEach((item) => {
483
+ const group = getGroup(item);
484
+ if (!result.has(group)) result.set(group, []);
485
+ });
486
+ visibleItems.forEach((item) => {
487
+ const group = getGroup(item);
488
+ if (!result.has(group)) result.set(group, []);
489
+ result.get(group).push(item);
490
+ });
491
+ return result;
492
+ }
493
+ /**
494
+ * Generate the built-in help text.
495
+ *
496
+ * @param {Command} cmd
497
+ * @param {Help} helper
498
+ * @returns {string}
499
+ */
500
+ formatHelp(cmd, helper) {
501
+ const termWidth = helper.padWidth(cmd, helper);
502
+ const helpWidth = helper.helpWidth ?? 80;
503
+ function callFormatItem(term, description) {
504
+ return helper.formatItem(term, termWidth, description, helper);
505
+ }
506
+ let output = [`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`, ""];
507
+ const commandDescription = helper.commandDescription(cmd);
508
+ if (commandDescription.length > 0) output = output.concat([helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth), ""]);
509
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
510
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
511
+ });
512
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
513
+ this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:").forEach((options, group) => {
514
+ const optionList = options.map((option) => {
515
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
516
+ });
517
+ output = output.concat(this.formatItemList(group, optionList, helper));
518
+ });
519
+ if (helper.showGlobalOptions) {
520
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
521
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
522
+ });
523
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
524
+ }
525
+ this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:").forEach((commands, group) => {
526
+ const commandList = commands.map((sub) => {
527
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
528
+ });
529
+ output = output.concat(this.formatItemList(group, commandList, helper));
530
+ });
531
+ return output.join("\n");
532
+ }
533
+ /**
534
+ * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
535
+ *
536
+ * @param {string} str
537
+ * @returns {number}
538
+ */
539
+ displayWidth(str) {
540
+ return stripColor(str).length;
541
+ }
542
+ /**
543
+ * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
544
+ *
545
+ * @param {string} str
546
+ * @returns {string}
547
+ */
548
+ styleTitle(str) {
549
+ return str;
550
+ }
551
+ styleUsage(str) {
552
+ return str.split(" ").map((word) => {
553
+ if (word === "[options]") return this.styleOptionText(word);
554
+ if (word === "[command]") return this.styleSubcommandText(word);
555
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
556
+ return this.styleCommandText(word);
557
+ }).join(" ");
558
+ }
559
+ styleCommandDescription(str) {
560
+ return this.styleDescriptionText(str);
561
+ }
562
+ styleOptionDescription(str) {
563
+ return this.styleDescriptionText(str);
564
+ }
565
+ styleSubcommandDescription(str) {
566
+ return this.styleDescriptionText(str);
567
+ }
568
+ styleArgumentDescription(str) {
569
+ return this.styleDescriptionText(str);
570
+ }
571
+ styleDescriptionText(str) {
572
+ return str;
573
+ }
574
+ styleOptionTerm(str) {
575
+ return this.styleOptionText(str);
576
+ }
577
+ styleSubcommandTerm(str) {
578
+ return str.split(" ").map((word) => {
579
+ if (word === "[options]") return this.styleOptionText(word);
580
+ if (word[0] === "[" || word[0] === "<") return this.styleArgumentText(word);
581
+ return this.styleSubcommandText(word);
582
+ }).join(" ");
583
+ }
584
+ styleArgumentTerm(str) {
585
+ return this.styleArgumentText(str);
586
+ }
587
+ styleOptionText(str) {
588
+ return str;
589
+ }
590
+ styleArgumentText(str) {
591
+ return str;
592
+ }
593
+ styleSubcommandText(str) {
594
+ return str;
595
+ }
596
+ styleCommandText(str) {
597
+ return str;
598
+ }
599
+ /**
600
+ * Calculate the pad width from the maximum term length.
601
+ *
602
+ * @param {Command} cmd
603
+ * @param {Help} helper
604
+ * @returns {number}
605
+ */
606
+ padWidth(cmd, helper) {
607
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
608
+ }
609
+ /**
610
+ * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
611
+ *
612
+ * @param {string} str
613
+ * @returns {boolean}
614
+ */
615
+ preformatted(str) {
616
+ return /\n[^\S\r\n]/.test(str);
617
+ }
618
+ /**
619
+ * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
620
+ *
621
+ * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
622
+ * TTT DDD DDDD
623
+ * DD DDD
624
+ *
625
+ * @param {string} term
626
+ * @param {number} termWidth
627
+ * @param {string} description
628
+ * @param {Help} helper
629
+ * @returns {string}
630
+ */
631
+ formatItem(term, termWidth, description, helper) {
632
+ const itemIndent = 2;
633
+ const itemIndentStr = " ".repeat(itemIndent);
634
+ if (!description) return itemIndentStr + term;
635
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
636
+ const spacerWidth = 2;
637
+ const remainingWidth = (this.helpWidth ?? 80) - termWidth - spacerWidth - itemIndent;
638
+ let formattedDescription;
639
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) formattedDescription = description;
640
+ else formattedDescription = helper.boxWrap(description, remainingWidth).replace(/\n/g, "\n" + " ".repeat(termWidth + spacerWidth));
641
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `\n${itemIndentStr}`);
642
+ }
643
+ /**
644
+ * Wrap a string at whitespace, preserving existing line breaks.
645
+ * Wrapping is skipped if the width is less than `minWidthToWrap`.
646
+ *
647
+ * @param {string} str
648
+ * @param {number} width
649
+ * @returns {string}
650
+ */
651
+ boxWrap(str, width) {
652
+ if (width < this.minWidthToWrap) return str;
653
+ const rawLines = str.split(/\r\n|\n/);
654
+ const chunkPattern = /[\s]*[^\s]+/g;
655
+ const wrappedLines = [];
656
+ rawLines.forEach((line) => {
657
+ const chunks = line.match(chunkPattern);
658
+ if (chunks === null) {
659
+ wrappedLines.push("");
660
+ return;
661
+ }
662
+ let sumChunks = [chunks.shift()];
663
+ let sumWidth = this.displayWidth(sumChunks[0]);
664
+ chunks.forEach((chunk) => {
665
+ const visibleWidth = this.displayWidth(chunk);
666
+ if (sumWidth + visibleWidth <= width) {
667
+ sumChunks.push(chunk);
668
+ sumWidth += visibleWidth;
669
+ return;
670
+ }
671
+ wrappedLines.push(sumChunks.join(""));
672
+ const nextChunk = chunk.trimStart();
673
+ sumChunks = [nextChunk];
674
+ sumWidth = this.displayWidth(nextChunk);
675
+ });
676
+ wrappedLines.push(sumChunks.join(""));
677
+ });
678
+ return wrappedLines.join("\n");
679
+ }
680
+ };
681
+ /**
682
+ * Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.
683
+ *
684
+ * @param {string} str
685
+ * @returns {string}
686
+ * @package
687
+ */
688
+ function stripColor(str) {
689
+ return str.replace(/\x1b\[\d*(;\d*)*m/g, "");
690
+ }
691
+ exports.Help = Help;
692
+ exports.stripColor = stripColor;
693
+ }));
694
+ //#endregion
695
+ //#region ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/option.js
696
+ var require_option = /* @__PURE__ */ __commonJSMin(((exports) => {
697
+ const { InvalidArgumentError } = require_error();
698
+ var Option = class {
699
+ /**
700
+ * Initialize a new `Option` with the given `flags` and `description`.
701
+ *
702
+ * @param {string} flags
703
+ * @param {string} [description]
704
+ */
705
+ constructor(flags, description) {
706
+ this.flags = flags;
707
+ this.description = description || "";
708
+ this.required = flags.includes("<");
709
+ this.optional = flags.includes("[");
710
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
711
+ this.mandatory = false;
712
+ const optionFlags = splitOptionFlags(flags);
713
+ this.short = optionFlags.shortFlag;
714
+ this.long = optionFlags.longFlag;
715
+ this.negate = false;
716
+ if (this.long) this.negate = this.long.startsWith("--no-");
717
+ this.defaultValue = void 0;
718
+ this.defaultValueDescription = void 0;
719
+ this.presetArg = void 0;
720
+ this.envVar = void 0;
721
+ this.parseArg = void 0;
722
+ this.hidden = false;
723
+ this.argChoices = void 0;
724
+ this.conflictsWith = [];
725
+ this.implied = void 0;
726
+ this.helpGroupHeading = void 0;
727
+ }
728
+ /**
729
+ * Set the default value, and optionally supply the description to be displayed in the help.
730
+ *
731
+ * @param {*} value
732
+ * @param {string} [description]
733
+ * @return {Option}
734
+ */
735
+ default(value, description) {
736
+ this.defaultValue = value;
737
+ this.defaultValueDescription = description;
738
+ return this;
739
+ }
740
+ /**
741
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
742
+ * The custom processing (parseArg) is called.
743
+ *
744
+ * @example
745
+ * new Option('--color').default('GREYSCALE').preset('RGB');
746
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
747
+ *
748
+ * @param {*} arg
749
+ * @return {Option}
750
+ */
751
+ preset(arg) {
752
+ this.presetArg = arg;
753
+ return this;
754
+ }
755
+ /**
756
+ * Add option name(s) that conflict with this option.
757
+ * An error will be displayed if conflicting options are found during parsing.
758
+ *
759
+ * @example
760
+ * new Option('--rgb').conflicts('cmyk');
761
+ * new Option('--js').conflicts(['ts', 'jsx']);
762
+ *
763
+ * @param {(string | string[])} names
764
+ * @return {Option}
765
+ */
766
+ conflicts(names) {
767
+ this.conflictsWith = this.conflictsWith.concat(names);
768
+ return this;
769
+ }
770
+ /**
771
+ * Specify implied option values for when this option is set and the implied options are not.
772
+ *
773
+ * The custom processing (parseArg) is not called on the implied values.
774
+ *
775
+ * @example
776
+ * program
777
+ * .addOption(new Option('--log', 'write logging information to file'))
778
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
779
+ *
780
+ * @param {object} impliedOptionValues
781
+ * @return {Option}
782
+ */
783
+ implies(impliedOptionValues) {
784
+ let newImplied = impliedOptionValues;
785
+ if (typeof impliedOptionValues === "string") newImplied = { [impliedOptionValues]: true };
786
+ this.implied = Object.assign(this.implied || {}, newImplied);
787
+ return this;
788
+ }
789
+ /**
790
+ * Set environment variable to check for option value.
791
+ *
792
+ * An environment variable is only used if when processed the current option value is
793
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
794
+ *
795
+ * @param {string} name
796
+ * @return {Option}
797
+ */
798
+ env(name) {
799
+ this.envVar = name;
800
+ return this;
801
+ }
802
+ /**
803
+ * Set the custom handler for processing CLI option arguments into option values.
804
+ *
805
+ * @param {Function} [fn]
806
+ * @return {Option}
807
+ */
808
+ argParser(fn) {
809
+ this.parseArg = fn;
810
+ return this;
811
+ }
812
+ /**
813
+ * Whether the option is mandatory and must have a value after parsing.
814
+ *
815
+ * @param {boolean} [mandatory=true]
816
+ * @return {Option}
817
+ */
818
+ makeOptionMandatory(mandatory = true) {
819
+ this.mandatory = !!mandatory;
820
+ return this;
821
+ }
822
+ /**
823
+ * Hide option in help.
824
+ *
825
+ * @param {boolean} [hide=true]
826
+ * @return {Option}
827
+ */
828
+ hideHelp(hide = true) {
829
+ this.hidden = !!hide;
830
+ return this;
831
+ }
832
+ /**
833
+ * @package
834
+ */
835
+ _collectValue(value, previous) {
836
+ if (previous === this.defaultValue || !Array.isArray(previous)) return [value];
837
+ previous.push(value);
838
+ return previous;
839
+ }
840
+ /**
841
+ * Only allow option value to be one of choices.
842
+ *
843
+ * @param {string[]} values
844
+ * @return {Option}
845
+ */
846
+ choices(values) {
847
+ this.argChoices = values.slice();
848
+ this.parseArg = (arg, previous) => {
849
+ if (!this.argChoices.includes(arg)) throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
850
+ if (this.variadic) return this._collectValue(arg, previous);
851
+ return arg;
852
+ };
853
+ return this;
854
+ }
855
+ /**
856
+ * Return option name.
857
+ *
858
+ * @return {string}
859
+ */
860
+ name() {
861
+ if (this.long) return this.long.replace(/^--/, "");
862
+ return this.short.replace(/^-/, "");
863
+ }
864
+ /**
865
+ * Return option name, in a camelcase format that can be used
866
+ * as an object attribute key.
867
+ *
868
+ * @return {string}
869
+ */
870
+ attributeName() {
871
+ if (this.negate) return camelcase(this.name().replace(/^no-/, ""));
872
+ return camelcase(this.name());
873
+ }
874
+ /**
875
+ * Set the help group heading.
876
+ *
877
+ * @param {string} heading
878
+ * @return {Option}
879
+ */
880
+ helpGroup(heading) {
881
+ this.helpGroupHeading = heading;
882
+ return this;
883
+ }
884
+ /**
885
+ * Check if `arg` matches the short or long flag.
886
+ *
887
+ * @param {string} arg
888
+ * @return {boolean}
889
+ * @package
890
+ */
891
+ is(arg) {
892
+ return this.short === arg || this.long === arg;
893
+ }
894
+ /**
895
+ * Return whether a boolean option.
896
+ *
897
+ * Options are one of boolean, negated, required argument, or optional argument.
898
+ *
899
+ * @return {boolean}
900
+ * @package
901
+ */
902
+ isBoolean() {
903
+ return !this.required && !this.optional && !this.negate;
904
+ }
905
+ };
906
+ /**
907
+ * This class is to make it easier to work with dual options, without changing the existing
908
+ * implementation. We support separate dual options for separate positive and negative options,
909
+ * like `--build` and `--no-build`, which share a single option value. This works nicely for some
910
+ * use cases, but is tricky for others where we want separate behaviours despite
911
+ * the single shared option value.
912
+ */
913
+ var DualOptions = class {
914
+ /**
915
+ * @param {Option[]} options
916
+ */
917
+ constructor(options) {
918
+ this.positiveOptions = /* @__PURE__ */ new Map();
919
+ this.negativeOptions = /* @__PURE__ */ new Map();
920
+ this.dualOptions = /* @__PURE__ */ new Set();
921
+ options.forEach((option) => {
922
+ if (option.negate) this.negativeOptions.set(option.attributeName(), option);
923
+ else this.positiveOptions.set(option.attributeName(), option);
924
+ });
925
+ this.negativeOptions.forEach((value, key) => {
926
+ if (this.positiveOptions.has(key)) this.dualOptions.add(key);
927
+ });
928
+ }
929
+ /**
930
+ * Did the value come from the option, and not from possible matching dual option?
931
+ *
932
+ * @param {*} value
933
+ * @param {Option} option
934
+ * @returns {boolean}
935
+ */
936
+ valueFromOption(value, option) {
937
+ const optionKey = option.attributeName();
938
+ if (!this.dualOptions.has(optionKey)) return true;
939
+ const preset = this.negativeOptions.get(optionKey).presetArg;
940
+ const negativeValue = preset !== void 0 ? preset : false;
941
+ return option.negate === (negativeValue === value);
942
+ }
943
+ };
944
+ /**
945
+ * Convert string from kebab-case to camelCase.
946
+ *
947
+ * @param {string} str
948
+ * @return {string}
949
+ * @private
950
+ */
951
+ function camelcase(str) {
952
+ return str.split("-").reduce((str, word) => {
953
+ return str + word[0].toUpperCase() + word.slice(1);
954
+ });
955
+ }
956
+ /**
957
+ * Split the short and long flag out of something like '-m,--mixed <value>'
958
+ *
959
+ * @private
960
+ */
961
+ function splitOptionFlags(flags) {
962
+ let shortFlag;
963
+ let longFlag;
964
+ const shortFlagExp = /^-[^-]$/;
965
+ const longFlagExp = /^--[^-]/;
966
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
967
+ if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
968
+ if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
969
+ if (!shortFlag && shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
970
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
971
+ shortFlag = longFlag;
972
+ longFlag = flagParts.shift();
973
+ }
974
+ if (flagParts[0].startsWith("-")) {
975
+ const unsupportedFlag = flagParts[0];
976
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
977
+ if (/^-[^-][^-]/.test(unsupportedFlag)) throw new Error(`${baseError}
978
+ - a short flag is a single dash and a single character
979
+ - either use a single dash and a single character (for a short flag)
980
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
981
+ if (shortFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
982
+ - too many short flags`);
983
+ if (longFlagExp.test(unsupportedFlag)) throw new Error(`${baseError}
984
+ - too many long flags`);
985
+ throw new Error(`${baseError}
986
+ - unrecognised flag format`);
987
+ }
988
+ if (shortFlag === void 0 && longFlag === void 0) throw new Error(`option creation failed due to no flags found in '${flags}'.`);
989
+ return {
990
+ shortFlag,
991
+ longFlag
992
+ };
993
+ }
994
+ exports.Option = Option;
995
+ exports.DualOptions = DualOptions;
996
+ }));
997
+ //#endregion
998
+ //#region ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/suggestSimilar.js
999
+ var require_suggestSimilar = /* @__PURE__ */ __commonJSMin(((exports) => {
1000
+ const maxDistance = 3;
1001
+ function editDistance(a, b) {
1002
+ if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
1003
+ const d = [];
1004
+ for (let i = 0; i <= a.length; i++) d[i] = [i];
1005
+ for (let j = 0; j <= b.length; j++) d[0][j] = j;
1006
+ for (let j = 1; j <= b.length; j++) for (let i = 1; i <= a.length; i++) {
1007
+ let cost = 1;
1008
+ if (a[i - 1] === b[j - 1]) cost = 0;
1009
+ else cost = 1;
1010
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
1011
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1012
+ }
1013
+ return d[a.length][b.length];
1014
+ }
1015
+ /**
1016
+ * Find close matches, restricted to same number of edits.
1017
+ *
1018
+ * @param {string} word
1019
+ * @param {string[]} candidates
1020
+ * @returns {string}
1021
+ */
1022
+ function suggestSimilar(word, candidates) {
1023
+ if (!candidates || candidates.length === 0) return "";
1024
+ candidates = Array.from(new Set(candidates));
1025
+ const searchingOptions = word.startsWith("--");
1026
+ if (searchingOptions) {
1027
+ word = word.slice(2);
1028
+ candidates = candidates.map((candidate) => candidate.slice(2));
1029
+ }
1030
+ let similar = [];
1031
+ let bestDistance = maxDistance;
1032
+ const minSimilarity = .4;
1033
+ candidates.forEach((candidate) => {
1034
+ if (candidate.length <= 1) return;
1035
+ const distance = editDistance(word, candidate);
1036
+ const length = Math.max(word.length, candidate.length);
1037
+ if ((length - distance) / length > minSimilarity) {
1038
+ if (distance < bestDistance) {
1039
+ bestDistance = distance;
1040
+ similar = [candidate];
1041
+ } else if (distance === bestDistance) similar.push(candidate);
1042
+ }
1043
+ });
1044
+ similar.sort((a, b) => a.localeCompare(b));
1045
+ if (searchingOptions) similar = similar.map((candidate) => `--${candidate}`);
1046
+ if (similar.length > 1) return `\n(Did you mean one of ${similar.join(", ")}?)`;
1047
+ if (similar.length === 1) return `\n(Did you mean ${similar[0]}?)`;
1048
+ return "";
1049
+ }
1050
+ exports.suggestSimilar = suggestSimilar;
1051
+ }));
1052
+ //#endregion
1053
+ //#region ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/command.js
1054
+ var require_command = /* @__PURE__ */ __commonJSMin(((exports) => {
1055
+ const EventEmitter = __require("node:events").EventEmitter;
1056
+ const childProcess$1 = __require("node:child_process");
1057
+ const path$2 = __require("node:path");
1058
+ const fs$3 = __require("node:fs");
1059
+ const process$2 = __require("node:process");
1060
+ const { Argument, humanReadableArgName } = require_argument();
1061
+ const { CommanderError } = require_error();
1062
+ const { Help, stripColor } = require_help();
1063
+ const { Option, DualOptions } = require_option();
1064
+ const { suggestSimilar } = require_suggestSimilar();
1065
+ var Command = class Command extends EventEmitter {
1066
+ /**
1067
+ * Initialize a new `Command`.
1068
+ *
1069
+ * @param {string} [name]
1070
+ */
1071
+ constructor(name) {
1072
+ super();
1073
+ /** @type {Command[]} */
1074
+ this.commands = [];
1075
+ /** @type {Option[]} */
1076
+ this.options = [];
1077
+ this.parent = null;
1078
+ this._allowUnknownOption = false;
1079
+ this._allowExcessArguments = false;
1080
+ /** @type {Argument[]} */
1081
+ this.registeredArguments = [];
1082
+ this._args = this.registeredArguments;
1083
+ /** @type {string[]} */
1084
+ this.args = [];
1085
+ this.rawArgs = [];
1086
+ this.processedArgs = [];
1087
+ this._scriptPath = null;
1088
+ this._name = name || "";
1089
+ this._optionValues = {};
1090
+ this._optionValueSources = {};
1091
+ this._storeOptionsAsProperties = false;
1092
+ this._actionHandler = null;
1093
+ this._executableHandler = false;
1094
+ this._executableFile = null;
1095
+ this._executableDir = null;
1096
+ this._defaultCommandName = null;
1097
+ this._exitCallback = null;
1098
+ this._aliases = [];
1099
+ this._combineFlagAndOptionalValue = true;
1100
+ this._description = "";
1101
+ this._summary = "";
1102
+ this._argsDescription = void 0;
1103
+ this._enablePositionalOptions = false;
1104
+ this._passThroughOptions = false;
1105
+ this._lifeCycleHooks = {};
1106
+ /** @type {(boolean | string)} */
1107
+ this._showHelpAfterError = false;
1108
+ this._showSuggestionAfterError = true;
1109
+ this._savedState = null;
1110
+ this._outputConfiguration = {
1111
+ writeOut: (str) => process$2.stdout.write(str),
1112
+ writeErr: (str) => process$2.stderr.write(str),
1113
+ outputError: (str, write) => write(str),
1114
+ getOutHelpWidth: () => process$2.stdout.isTTY ? process$2.stdout.columns : void 0,
1115
+ getErrHelpWidth: () => process$2.stderr.isTTY ? process$2.stderr.columns : void 0,
1116
+ getOutHasColors: () => useColor() ?? (process$2.stdout.isTTY && process$2.stdout.hasColors?.()),
1117
+ getErrHasColors: () => useColor() ?? (process$2.stderr.isTTY && process$2.stderr.hasColors?.()),
1118
+ stripColor: (str) => stripColor(str)
1119
+ };
1120
+ this._hidden = false;
1121
+ /** @type {(Option | null | undefined)} */
1122
+ this._helpOption = void 0;
1123
+ this._addImplicitHelpCommand = void 0;
1124
+ /** @type {Command} */
1125
+ this._helpCommand = void 0;
1126
+ this._helpConfiguration = {};
1127
+ /** @type {string | undefined} */
1128
+ this._helpGroupHeading = void 0;
1129
+ /** @type {string | undefined} */
1130
+ this._defaultCommandGroup = void 0;
1131
+ /** @type {string | undefined} */
1132
+ this._defaultOptionGroup = void 0;
1133
+ }
1134
+ /**
1135
+ * Copy settings that are useful to have in common across root command and subcommands.
1136
+ *
1137
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1138
+ *
1139
+ * @param {Command} sourceCommand
1140
+ * @return {Command} `this` command for chaining
1141
+ */
1142
+ copyInheritedSettings(sourceCommand) {
1143
+ this._outputConfiguration = sourceCommand._outputConfiguration;
1144
+ this._helpOption = sourceCommand._helpOption;
1145
+ this._helpCommand = sourceCommand._helpCommand;
1146
+ this._helpConfiguration = sourceCommand._helpConfiguration;
1147
+ this._exitCallback = sourceCommand._exitCallback;
1148
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1149
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1150
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
1151
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1152
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
1153
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1154
+ return this;
1155
+ }
1156
+ /**
1157
+ * @returns {Command[]}
1158
+ * @private
1159
+ */
1160
+ _getCommandAndAncestors() {
1161
+ const result = [];
1162
+ for (let command = this; command; command = command.parent) result.push(command);
1163
+ return result;
1164
+ }
1165
+ /**
1166
+ * Define a command.
1167
+ *
1168
+ * There are two styles of command: pay attention to where to put the description.
1169
+ *
1170
+ * @example
1171
+ * // Command implemented using action handler (description is supplied separately to `.command`)
1172
+ * program
1173
+ * .command('clone <source> [destination]')
1174
+ * .description('clone a repository into a newly created directory')
1175
+ * .action((source, destination) => {
1176
+ * console.log('clone command called');
1177
+ * });
1178
+ *
1179
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
1180
+ * program
1181
+ * .command('start <service>', 'start named service')
1182
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
1183
+ *
1184
+ * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1185
+ * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1186
+ * @param {object} [execOpts] - configuration options (for executable)
1187
+ * @return {Command} returns new command for action handler, or `this` for executable command
1188
+ */
1189
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1190
+ let desc = actionOptsOrExecDesc;
1191
+ let opts = execOpts;
1192
+ if (typeof desc === "object" && desc !== null) {
1193
+ opts = desc;
1194
+ desc = null;
1195
+ }
1196
+ opts = opts || {};
1197
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1198
+ const cmd = this.createCommand(name);
1199
+ if (desc) {
1200
+ cmd.description(desc);
1201
+ cmd._executableHandler = true;
1202
+ }
1203
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1204
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
1205
+ cmd._executableFile = opts.executableFile || null;
1206
+ if (args) cmd.arguments(args);
1207
+ this._registerCommand(cmd);
1208
+ cmd.parent = this;
1209
+ cmd.copyInheritedSettings(this);
1210
+ if (desc) return this;
1211
+ return cmd;
1212
+ }
1213
+ /**
1214
+ * Factory routine to create a new unattached command.
1215
+ *
1216
+ * See .command() for creating an attached subcommand, which uses this routine to
1217
+ * create the command. You can override createCommand to customise subcommands.
1218
+ *
1219
+ * @param {string} [name]
1220
+ * @return {Command} new command
1221
+ */
1222
+ createCommand(name) {
1223
+ return new Command(name);
1224
+ }
1225
+ /**
1226
+ * You can customise the help with a subclass of Help by overriding createHelp,
1227
+ * or by overriding Help properties using configureHelp().
1228
+ *
1229
+ * @return {Help}
1230
+ */
1231
+ createHelp() {
1232
+ return Object.assign(new Help(), this.configureHelp());
1233
+ }
1234
+ /**
1235
+ * You can customise the help by overriding Help properties using configureHelp(),
1236
+ * or with a subclass of Help by overriding createHelp().
1237
+ *
1238
+ * @param {object} [configuration] - configuration options
1239
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1240
+ */
1241
+ configureHelp(configuration) {
1242
+ if (configuration === void 0) return this._helpConfiguration;
1243
+ this._helpConfiguration = configuration;
1244
+ return this;
1245
+ }
1246
+ /**
1247
+ * The default output goes to stdout and stderr. You can customise this for special
1248
+ * applications. You can also customise the display of errors by overriding outputError.
1249
+ *
1250
+ * The configuration properties are all functions:
1251
+ *
1252
+ * // change how output being written, defaults to stdout and stderr
1253
+ * writeOut(str)
1254
+ * writeErr(str)
1255
+ * // change how output being written for errors, defaults to writeErr
1256
+ * outputError(str, write) // used for displaying errors and not used for displaying help
1257
+ * // specify width for wrapping help
1258
+ * getOutHelpWidth()
1259
+ * getErrHelpWidth()
1260
+ * // color support, currently only used with Help
1261
+ * getOutHasColors()
1262
+ * getErrHasColors()
1263
+ * stripColor() // used to remove ANSI escape codes if output does not have colors
1264
+ *
1265
+ * @param {object} [configuration] - configuration options
1266
+ * @return {(Command | object)} `this` command for chaining, or stored configuration
1267
+ */
1268
+ configureOutput(configuration) {
1269
+ if (configuration === void 0) return this._outputConfiguration;
1270
+ this._outputConfiguration = {
1271
+ ...this._outputConfiguration,
1272
+ ...configuration
1273
+ };
1274
+ return this;
1275
+ }
1276
+ /**
1277
+ * Display the help or a custom message after an error occurs.
1278
+ *
1279
+ * @param {(boolean|string)} [displayHelp]
1280
+ * @return {Command} `this` command for chaining
1281
+ */
1282
+ showHelpAfterError(displayHelp = true) {
1283
+ if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1284
+ this._showHelpAfterError = displayHelp;
1285
+ return this;
1286
+ }
1287
+ /**
1288
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
1289
+ *
1290
+ * @param {boolean} [displaySuggestion]
1291
+ * @return {Command} `this` command for chaining
1292
+ */
1293
+ showSuggestionAfterError(displaySuggestion = true) {
1294
+ this._showSuggestionAfterError = !!displaySuggestion;
1295
+ return this;
1296
+ }
1297
+ /**
1298
+ * Add a prepared subcommand.
1299
+ *
1300
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
1301
+ *
1302
+ * @param {Command} cmd - new subcommand
1303
+ * @param {object} [opts] - configuration options
1304
+ * @return {Command} `this` command for chaining
1305
+ */
1306
+ addCommand(cmd, opts) {
1307
+ if (!cmd._name) throw new Error(`Command passed to .addCommand() must have a name
1308
+ - specify the name in Command constructor or using .name()`);
1309
+ opts = opts || {};
1310
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
1311
+ if (opts.noHelp || opts.hidden) cmd._hidden = true;
1312
+ this._registerCommand(cmd);
1313
+ cmd.parent = this;
1314
+ cmd._checkForBrokenPassThrough();
1315
+ return this;
1316
+ }
1317
+ /**
1318
+ * Factory routine to create a new unattached argument.
1319
+ *
1320
+ * See .argument() for creating an attached argument, which uses this routine to
1321
+ * create the argument. You can override createArgument to return a custom argument.
1322
+ *
1323
+ * @param {string} name
1324
+ * @param {string} [description]
1325
+ * @return {Argument} new argument
1326
+ */
1327
+ createArgument(name, description) {
1328
+ return new Argument(name, description);
1329
+ }
1330
+ /**
1331
+ * Define argument syntax for command.
1332
+ *
1333
+ * The default is that the argument is required, and you can explicitly
1334
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
1335
+ *
1336
+ * @example
1337
+ * program.argument('<input-file>');
1338
+ * program.argument('[output-file]');
1339
+ *
1340
+ * @param {string} name
1341
+ * @param {string} [description]
1342
+ * @param {(Function|*)} [parseArg] - custom argument processing function or default value
1343
+ * @param {*} [defaultValue]
1344
+ * @return {Command} `this` command for chaining
1345
+ */
1346
+ argument(name, description, parseArg, defaultValue) {
1347
+ const argument = this.createArgument(name, description);
1348
+ if (typeof parseArg === "function") argument.default(defaultValue).argParser(parseArg);
1349
+ else argument.default(parseArg);
1350
+ this.addArgument(argument);
1351
+ return this;
1352
+ }
1353
+ /**
1354
+ * Define argument syntax for command, adding multiple at once (without descriptions).
1355
+ *
1356
+ * See also .argument().
1357
+ *
1358
+ * @example
1359
+ * program.arguments('<cmd> [env]');
1360
+ *
1361
+ * @param {string} names
1362
+ * @return {Command} `this` command for chaining
1363
+ */
1364
+ arguments(names) {
1365
+ names.trim().split(/ +/).forEach((detail) => {
1366
+ this.argument(detail);
1367
+ });
1368
+ return this;
1369
+ }
1370
+ /**
1371
+ * Define argument syntax for command, adding a prepared argument.
1372
+ *
1373
+ * @param {Argument} argument
1374
+ * @return {Command} `this` command for chaining
1375
+ */
1376
+ addArgument(argument) {
1377
+ const previousArgument = this.registeredArguments.slice(-1)[0];
1378
+ if (previousArgument?.variadic) throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
1379
+ if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
1380
+ this.registeredArguments.push(argument);
1381
+ return this;
1382
+ }
1383
+ /**
1384
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1385
+ *
1386
+ * @example
1387
+ * program.helpCommand('help [cmd]');
1388
+ * program.helpCommand('help [cmd]', 'show help');
1389
+ * program.helpCommand(false); // suppress default help command
1390
+ * program.helpCommand(true); // add help command even if no subcommands
1391
+ *
1392
+ * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1393
+ * @param {string} [description] - custom description
1394
+ * @return {Command} `this` command for chaining
1395
+ */
1396
+ helpCommand(enableOrNameAndArgs, description) {
1397
+ if (typeof enableOrNameAndArgs === "boolean") {
1398
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
1399
+ if (enableOrNameAndArgs && this._defaultCommandGroup) this._initCommandGroup(this._getHelpCommand());
1400
+ return this;
1401
+ }
1402
+ const [, helpName, helpArgs] = (enableOrNameAndArgs ?? "help [command]").match(/([^ ]+) *(.*)/);
1403
+ const helpDescription = description ?? "display help for command";
1404
+ const helpCommand = this.createCommand(helpName);
1405
+ helpCommand.helpOption(false);
1406
+ if (helpArgs) helpCommand.arguments(helpArgs);
1407
+ if (helpDescription) helpCommand.description(helpDescription);
1408
+ this._addImplicitHelpCommand = true;
1409
+ this._helpCommand = helpCommand;
1410
+ if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
1411
+ return this;
1412
+ }
1413
+ /**
1414
+ * Add prepared custom help command.
1415
+ *
1416
+ * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1417
+ * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1418
+ * @return {Command} `this` command for chaining
1419
+ */
1420
+ addHelpCommand(helpCommand, deprecatedDescription) {
1421
+ if (typeof helpCommand !== "object") {
1422
+ this.helpCommand(helpCommand, deprecatedDescription);
1423
+ return this;
1424
+ }
1425
+ this._addImplicitHelpCommand = true;
1426
+ this._helpCommand = helpCommand;
1427
+ this._initCommandGroup(helpCommand);
1428
+ return this;
1429
+ }
1430
+ /**
1431
+ * Lazy create help command.
1432
+ *
1433
+ * @return {(Command|null)}
1434
+ * @package
1435
+ */
1436
+ _getHelpCommand() {
1437
+ if (this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"))) {
1438
+ if (this._helpCommand === void 0) this.helpCommand(void 0, void 0);
1439
+ return this._helpCommand;
1440
+ }
1441
+ return null;
1442
+ }
1443
+ /**
1444
+ * Add hook for life cycle event.
1445
+ *
1446
+ * @param {string} event
1447
+ * @param {Function} listener
1448
+ * @return {Command} `this` command for chaining
1449
+ */
1450
+ hook(event, listener) {
1451
+ const allowedValues = [
1452
+ "preSubcommand",
1453
+ "preAction",
1454
+ "postAction"
1455
+ ];
1456
+ if (!allowedValues.includes(event)) throw new Error(`Unexpected value for event passed to hook : '${event}'.
1457
+ Expecting one of '${allowedValues.join("', '")}'`);
1458
+ if (this._lifeCycleHooks[event]) this._lifeCycleHooks[event].push(listener);
1459
+ else this._lifeCycleHooks[event] = [listener];
1460
+ return this;
1461
+ }
1462
+ /**
1463
+ * Register callback to use as replacement for calling process.exit.
1464
+ *
1465
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1466
+ * @return {Command} `this` command for chaining
1467
+ */
1468
+ exitOverride(fn) {
1469
+ if (fn) this._exitCallback = fn;
1470
+ else this._exitCallback = (err) => {
1471
+ if (err.code !== "commander.executeSubCommandAsync") throw err;
1472
+ };
1473
+ return this;
1474
+ }
1475
+ /**
1476
+ * Call process.exit, and _exitCallback if defined.
1477
+ *
1478
+ * @param {number} exitCode exit code for using with process.exit
1479
+ * @param {string} code an id string representing the error
1480
+ * @param {string} message human-readable description of the error
1481
+ * @return never
1482
+ * @private
1483
+ */
1484
+ _exit(exitCode, code, message) {
1485
+ if (this._exitCallback) this._exitCallback(new CommanderError(exitCode, code, message));
1486
+ process$2.exit(exitCode);
1487
+ }
1488
+ /**
1489
+ * Register callback `fn` for the command.
1490
+ *
1491
+ * @example
1492
+ * program
1493
+ * .command('serve')
1494
+ * .description('start service')
1495
+ * .action(function() {
1496
+ * // do work here
1497
+ * });
1498
+ *
1499
+ * @param {Function} fn
1500
+ * @return {Command} `this` command for chaining
1501
+ */
1502
+ action(fn) {
1503
+ const listener = (args) => {
1504
+ const expectedArgsCount = this.registeredArguments.length;
1505
+ const actionArgs = args.slice(0, expectedArgsCount);
1506
+ if (this._storeOptionsAsProperties) actionArgs[expectedArgsCount] = this;
1507
+ else actionArgs[expectedArgsCount] = this.opts();
1508
+ actionArgs.push(this);
1509
+ return fn.apply(this, actionArgs);
1510
+ };
1511
+ this._actionHandler = listener;
1512
+ return this;
1513
+ }
1514
+ /**
1515
+ * Factory routine to create a new unattached option.
1516
+ *
1517
+ * See .option() for creating an attached option, which uses this routine to
1518
+ * create the option. You can override createOption to return a custom option.
1519
+ *
1520
+ * @param {string} flags
1521
+ * @param {string} [description]
1522
+ * @return {Option} new option
1523
+ */
1524
+ createOption(flags, description) {
1525
+ return new Option(flags, description);
1526
+ }
1527
+ /**
1528
+ * Wrap parseArgs to catch 'commander.invalidArgument'.
1529
+ *
1530
+ * @param {(Option | Argument)} target
1531
+ * @param {string} value
1532
+ * @param {*} previous
1533
+ * @param {string} invalidArgumentMessage
1534
+ * @private
1535
+ */
1536
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1537
+ try {
1538
+ return target.parseArg(value, previous);
1539
+ } catch (err) {
1540
+ if (err.code === "commander.invalidArgument") {
1541
+ const message = `${invalidArgumentMessage} ${err.message}`;
1542
+ this.error(message, {
1543
+ exitCode: err.exitCode,
1544
+ code: err.code
1545
+ });
1546
+ }
1547
+ throw err;
1548
+ }
1549
+ }
1550
+ /**
1551
+ * Check for option flag conflicts.
1552
+ * Register option if no conflicts found, or throw on conflict.
1553
+ *
1554
+ * @param {Option} option
1555
+ * @private
1556
+ */
1557
+ _registerOption(option) {
1558
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1559
+ if (matchingOption) {
1560
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1561
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1562
+ - already used by option '${matchingOption.flags}'`);
1563
+ }
1564
+ this._initOptionGroup(option);
1565
+ this.options.push(option);
1566
+ }
1567
+ /**
1568
+ * Check for command name and alias conflicts with existing commands.
1569
+ * Register command if no conflicts found, or throw on conflict.
1570
+ *
1571
+ * @param {Command} command
1572
+ * @private
1573
+ */
1574
+ _registerCommand(command) {
1575
+ const knownBy = (cmd) => {
1576
+ return [cmd.name()].concat(cmd.aliases());
1577
+ };
1578
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1579
+ if (alreadyUsed) {
1580
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1581
+ const newCmd = knownBy(command).join("|");
1582
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1583
+ }
1584
+ this._initCommandGroup(command);
1585
+ this.commands.push(command);
1586
+ }
1587
+ /**
1588
+ * Add an option.
1589
+ *
1590
+ * @param {Option} option
1591
+ * @return {Command} `this` command for chaining
1592
+ */
1593
+ addOption(option) {
1594
+ this._registerOption(option);
1595
+ const oname = option.name();
1596
+ const name = option.attributeName();
1597
+ if (option.negate) {
1598
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1599
+ if (!this._findOption(positiveLongFlag)) this.setOptionValueWithSource(name, option.defaultValue === void 0 ? true : option.defaultValue, "default");
1600
+ } else if (option.defaultValue !== void 0) this.setOptionValueWithSource(name, option.defaultValue, "default");
1601
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1602
+ if (val == null && option.presetArg !== void 0) val = option.presetArg;
1603
+ const oldValue = this.getOptionValue(name);
1604
+ if (val !== null && option.parseArg) val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1605
+ else if (val !== null && option.variadic) val = option._collectValue(val, oldValue);
1606
+ if (val == null) if (option.negate) val = false;
1607
+ else if (option.isBoolean() || option.optional) val = true;
1608
+ else val = "";
1609
+ this.setOptionValueWithSource(name, val, valueSource);
1610
+ };
1611
+ this.on("option:" + oname, (val) => {
1612
+ handleOptionValue(val, `error: option '${option.flags}' argument '${val}' is invalid.`, "cli");
1613
+ });
1614
+ if (option.envVar) this.on("optionEnv:" + oname, (val) => {
1615
+ handleOptionValue(val, `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`, "env");
1616
+ });
1617
+ return this;
1618
+ }
1619
+ /**
1620
+ * Internal implementation shared by .option() and .requiredOption()
1621
+ *
1622
+ * @return {Command} `this` command for chaining
1623
+ * @private
1624
+ */
1625
+ _optionEx(config, flags, description, fn, defaultValue) {
1626
+ if (typeof flags === "object" && flags instanceof Option) throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1627
+ const option = this.createOption(flags, description);
1628
+ option.makeOptionMandatory(!!config.mandatory);
1629
+ if (typeof fn === "function") option.default(defaultValue).argParser(fn);
1630
+ else if (fn instanceof RegExp) {
1631
+ const regex = fn;
1632
+ fn = (val, def) => {
1633
+ const m = regex.exec(val);
1634
+ return m ? m[0] : def;
1635
+ };
1636
+ option.default(defaultValue).argParser(fn);
1637
+ } else option.default(fn);
1638
+ return this.addOption(option);
1639
+ }
1640
+ /**
1641
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1642
+ *
1643
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1644
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1645
+ *
1646
+ * See the README for more details, and see also addOption() and requiredOption().
1647
+ *
1648
+ * @example
1649
+ * program
1650
+ * .option('-p, --pepper', 'add pepper')
1651
+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1652
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1653
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1654
+ *
1655
+ * @param {string} flags
1656
+ * @param {string} [description]
1657
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1658
+ * @param {*} [defaultValue]
1659
+ * @return {Command} `this` command for chaining
1660
+ */
1661
+ option(flags, description, parseArg, defaultValue) {
1662
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1663
+ }
1664
+ /**
1665
+ * Add a required option which must have a value after parsing. This usually means
1666
+ * the option must be specified on the command line. (Otherwise the same as .option().)
1667
+ *
1668
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1669
+ *
1670
+ * @param {string} flags
1671
+ * @param {string} [description]
1672
+ * @param {(Function|*)} [parseArg] - custom option processing function or default value
1673
+ * @param {*} [defaultValue]
1674
+ * @return {Command} `this` command for chaining
1675
+ */
1676
+ requiredOption(flags, description, parseArg, defaultValue) {
1677
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1678
+ }
1679
+ /**
1680
+ * Alter parsing of short flags with optional values.
1681
+ *
1682
+ * @example
1683
+ * // for `.option('-f,--flag [value]'):
1684
+ * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1685
+ * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1686
+ *
1687
+ * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1688
+ * @return {Command} `this` command for chaining
1689
+ */
1690
+ combineFlagAndOptionalValue(combine = true) {
1691
+ this._combineFlagAndOptionalValue = !!combine;
1692
+ return this;
1693
+ }
1694
+ /**
1695
+ * Allow unknown options on the command line.
1696
+ *
1697
+ * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1698
+ * @return {Command} `this` command for chaining
1699
+ */
1700
+ allowUnknownOption(allowUnknown = true) {
1701
+ this._allowUnknownOption = !!allowUnknown;
1702
+ return this;
1703
+ }
1704
+ /**
1705
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1706
+ *
1707
+ * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1708
+ * @return {Command} `this` command for chaining
1709
+ */
1710
+ allowExcessArguments(allowExcess = true) {
1711
+ this._allowExcessArguments = !!allowExcess;
1712
+ return this;
1713
+ }
1714
+ /**
1715
+ * Enable positional options. Positional means global options are specified before subcommands which lets
1716
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1717
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
1718
+ *
1719
+ * @param {boolean} [positional]
1720
+ * @return {Command} `this` command for chaining
1721
+ */
1722
+ enablePositionalOptions(positional = true) {
1723
+ this._enablePositionalOptions = !!positional;
1724
+ return this;
1725
+ }
1726
+ /**
1727
+ * Pass through options that come after command-arguments rather than treat them as command-options,
1728
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1729
+ * positional options to have been enabled on the program (parent commands).
1730
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
1731
+ *
1732
+ * @param {boolean} [passThrough] for unknown options.
1733
+ * @return {Command} `this` command for chaining
1734
+ */
1735
+ passThroughOptions(passThrough = true) {
1736
+ this._passThroughOptions = !!passThrough;
1737
+ this._checkForBrokenPassThrough();
1738
+ return this;
1739
+ }
1740
+ /**
1741
+ * @private
1742
+ */
1743
+ _checkForBrokenPassThrough() {
1744
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1745
+ }
1746
+ /**
1747
+ * Whether to store option values as properties on command object,
1748
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
1749
+ *
1750
+ * @param {boolean} [storeAsProperties=true]
1751
+ * @return {Command} `this` command for chaining
1752
+ */
1753
+ storeOptionsAsProperties(storeAsProperties = true) {
1754
+ if (this.options.length) throw new Error("call .storeOptionsAsProperties() before adding options");
1755
+ if (Object.keys(this._optionValues).length) throw new Error("call .storeOptionsAsProperties() before setting option values");
1756
+ this._storeOptionsAsProperties = !!storeAsProperties;
1757
+ return this;
1758
+ }
1759
+ /**
1760
+ * Retrieve option value.
1761
+ *
1762
+ * @param {string} key
1763
+ * @return {object} value
1764
+ */
1765
+ getOptionValue(key) {
1766
+ if (this._storeOptionsAsProperties) return this[key];
1767
+ return this._optionValues[key];
1768
+ }
1769
+ /**
1770
+ * Store option value.
1771
+ *
1772
+ * @param {string} key
1773
+ * @param {object} value
1774
+ * @return {Command} `this` command for chaining
1775
+ */
1776
+ setOptionValue(key, value) {
1777
+ return this.setOptionValueWithSource(key, value, void 0);
1778
+ }
1779
+ /**
1780
+ * Store option value and where the value came from.
1781
+ *
1782
+ * @param {string} key
1783
+ * @param {object} value
1784
+ * @param {string} source - expected values are default/config/env/cli/implied
1785
+ * @return {Command} `this` command for chaining
1786
+ */
1787
+ setOptionValueWithSource(key, value, source) {
1788
+ if (this._storeOptionsAsProperties) this[key] = value;
1789
+ else this._optionValues[key] = value;
1790
+ this._optionValueSources[key] = source;
1791
+ return this;
1792
+ }
1793
+ /**
1794
+ * Get source of option value.
1795
+ * Expected values are default | config | env | cli | implied
1796
+ *
1797
+ * @param {string} key
1798
+ * @return {string}
1799
+ */
1800
+ getOptionValueSource(key) {
1801
+ return this._optionValueSources[key];
1802
+ }
1803
+ /**
1804
+ * Get source of option value. See also .optsWithGlobals().
1805
+ * Expected values are default | config | env | cli | implied
1806
+ *
1807
+ * @param {string} key
1808
+ * @return {string}
1809
+ */
1810
+ getOptionValueSourceWithGlobals(key) {
1811
+ let source;
1812
+ this._getCommandAndAncestors().forEach((cmd) => {
1813
+ if (cmd.getOptionValueSource(key) !== void 0) source = cmd.getOptionValueSource(key);
1814
+ });
1815
+ return source;
1816
+ }
1817
+ /**
1818
+ * Get user arguments from implied or explicit arguments.
1819
+ * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1820
+ *
1821
+ * @private
1822
+ */
1823
+ _prepareUserArgs(argv, parseOptions) {
1824
+ if (argv !== void 0 && !Array.isArray(argv)) throw new Error("first parameter to parse must be array or undefined");
1825
+ parseOptions = parseOptions || {};
1826
+ if (argv === void 0 && parseOptions.from === void 0) {
1827
+ if (process$2.versions?.electron) parseOptions.from = "electron";
1828
+ const execArgv = process$2.execArgv ?? [];
1829
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) parseOptions.from = "eval";
1830
+ }
1831
+ if (argv === void 0) argv = process$2.argv;
1832
+ this.rawArgs = argv.slice();
1833
+ let userArgs;
1834
+ switch (parseOptions.from) {
1835
+ case void 0:
1836
+ case "node":
1837
+ this._scriptPath = argv[1];
1838
+ userArgs = argv.slice(2);
1839
+ break;
1840
+ case "electron":
1841
+ if (process$2.defaultApp) {
1842
+ this._scriptPath = argv[1];
1843
+ userArgs = argv.slice(2);
1844
+ } else userArgs = argv.slice(1);
1845
+ break;
1846
+ case "user":
1847
+ userArgs = argv.slice(0);
1848
+ break;
1849
+ case "eval":
1850
+ userArgs = argv.slice(1);
1851
+ break;
1852
+ default: throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1853
+ }
1854
+ if (!this._name && this._scriptPath) this.nameFromFilename(this._scriptPath);
1855
+ this._name = this._name || "program";
1856
+ return userArgs;
1857
+ }
1858
+ /**
1859
+ * Parse `argv`, setting options and invoking commands when defined.
1860
+ *
1861
+ * Use parseAsync instead of parse if any of your action handlers are async.
1862
+ *
1863
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1864
+ *
1865
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1866
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1867
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1868
+ * - `'user'`: just user arguments
1869
+ *
1870
+ * @example
1871
+ * program.parse(); // parse process.argv and auto-detect electron and special node flags
1872
+ * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
1873
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1874
+ *
1875
+ * @param {string[]} [argv] - optional, defaults to process.argv
1876
+ * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
1877
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
1878
+ * @return {Command} `this` command for chaining
1879
+ */
1880
+ parse(argv, parseOptions) {
1881
+ this._prepareForParse();
1882
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1883
+ this._parseCommand([], userArgs);
1884
+ return this;
1885
+ }
1886
+ /**
1887
+ * Parse `argv`, setting options and invoking commands when defined.
1888
+ *
1889
+ * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
1890
+ *
1891
+ * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
1892
+ * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
1893
+ * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
1894
+ * - `'user'`: just user arguments
1895
+ *
1896
+ * @example
1897
+ * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
1898
+ * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
1899
+ * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
1900
+ *
1901
+ * @param {string[]} [argv]
1902
+ * @param {object} [parseOptions]
1903
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
1904
+ * @return {Promise}
1905
+ */
1906
+ async parseAsync(argv, parseOptions) {
1907
+ this._prepareForParse();
1908
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1909
+ await this._parseCommand([], userArgs);
1910
+ return this;
1911
+ }
1912
+ _prepareForParse() {
1913
+ if (this._savedState === null) this.saveStateBeforeParse();
1914
+ else this.restoreStateBeforeParse();
1915
+ }
1916
+ /**
1917
+ * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
1918
+ * Not usually called directly, but available for subclasses to save their custom state.
1919
+ *
1920
+ * This is called in a lazy way. Only commands used in parsing chain will have state saved.
1921
+ */
1922
+ saveStateBeforeParse() {
1923
+ this._savedState = {
1924
+ _name: this._name,
1925
+ _optionValues: { ...this._optionValues },
1926
+ _optionValueSources: { ...this._optionValueSources }
1927
+ };
1928
+ }
1929
+ /**
1930
+ * Restore state before parse for calls after the first.
1931
+ * Not usually called directly, but available for subclasses to save their custom state.
1932
+ *
1933
+ * This is called in a lazy way. Only commands used in parsing chain will have state restored.
1934
+ */
1935
+ restoreStateBeforeParse() {
1936
+ if (this._storeOptionsAsProperties) throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1937
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1938
+ this._name = this._savedState._name;
1939
+ this._scriptPath = null;
1940
+ this.rawArgs = [];
1941
+ this._optionValues = { ...this._savedState._optionValues };
1942
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1943
+ this.args = [];
1944
+ this.processedArgs = [];
1945
+ }
1946
+ /**
1947
+ * Throw if expected executable is missing. Add lots of help for author.
1948
+ *
1949
+ * @param {string} executableFile
1950
+ * @param {string} executableDir
1951
+ * @param {string} subcommandName
1952
+ */
1953
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1954
+ if (fs$3.existsSync(executableFile)) return;
1955
+ const executableMissing = `'${executableFile}' does not exist
1956
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1957
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1958
+ - ${executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory"}`;
1959
+ throw new Error(executableMissing);
1960
+ }
1961
+ /**
1962
+ * Execute a sub-command executable.
1963
+ *
1964
+ * @private
1965
+ */
1966
+ _executeSubCommand(subcommand, args) {
1967
+ args = args.slice();
1968
+ let launchWithNode = false;
1969
+ const sourceExt = [
1970
+ ".js",
1971
+ ".ts",
1972
+ ".tsx",
1973
+ ".mjs",
1974
+ ".cjs"
1975
+ ];
1976
+ function findFile(baseDir, baseName) {
1977
+ const localBin = path$2.resolve(baseDir, baseName);
1978
+ if (fs$3.existsSync(localBin)) return localBin;
1979
+ if (sourceExt.includes(path$2.extname(baseName))) return void 0;
1980
+ const foundExt = sourceExt.find((ext) => fs$3.existsSync(`${localBin}${ext}`));
1981
+ if (foundExt) return `${localBin}${foundExt}`;
1982
+ }
1983
+ this._checkForMissingMandatoryOptions();
1984
+ this._checkForConflictingOptions();
1985
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1986
+ let executableDir = this._executableDir || "";
1987
+ if (this._scriptPath) {
1988
+ let resolvedScriptPath;
1989
+ try {
1990
+ resolvedScriptPath = fs$3.realpathSync(this._scriptPath);
1991
+ } catch {
1992
+ resolvedScriptPath = this._scriptPath;
1993
+ }
1994
+ executableDir = path$2.resolve(path$2.dirname(resolvedScriptPath), executableDir);
1995
+ }
1996
+ if (executableDir) {
1997
+ let localFile = findFile(executableDir, executableFile);
1998
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1999
+ const legacyName = path$2.basename(this._scriptPath, path$2.extname(this._scriptPath));
2000
+ if (legacyName !== this._name) localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
2001
+ }
2002
+ executableFile = localFile || executableFile;
2003
+ }
2004
+ launchWithNode = sourceExt.includes(path$2.extname(executableFile));
2005
+ let proc;
2006
+ if (process$2.platform !== "win32") if (launchWithNode) {
2007
+ args.unshift(executableFile);
2008
+ args = incrementNodeInspectorPort(process$2.execArgv).concat(args);
2009
+ proc = childProcess$1.spawn(process$2.argv[0], args, { stdio: "inherit" });
2010
+ } else proc = childProcess$1.spawn(executableFile, args, { stdio: "inherit" });
2011
+ else {
2012
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
2013
+ args.unshift(executableFile);
2014
+ args = incrementNodeInspectorPort(process$2.execArgv).concat(args);
2015
+ proc = childProcess$1.spawn(process$2.execPath, args, { stdio: "inherit" });
2016
+ }
2017
+ if (!proc.killed) [
2018
+ "SIGUSR1",
2019
+ "SIGUSR2",
2020
+ "SIGTERM",
2021
+ "SIGINT",
2022
+ "SIGHUP"
2023
+ ].forEach((signal) => {
2024
+ process$2.on(signal, () => {
2025
+ if (proc.killed === false && proc.exitCode === null) proc.kill(signal);
2026
+ });
2027
+ });
2028
+ const exitCallback = this._exitCallback;
2029
+ proc.on("close", (code) => {
2030
+ code = code ?? 1;
2031
+ if (!exitCallback) process$2.exit(code);
2032
+ else exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
2033
+ });
2034
+ proc.on("error", (err) => {
2035
+ if (err.code === "ENOENT") this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
2036
+ else if (err.code === "EACCES") throw new Error(`'${executableFile}' not executable`);
2037
+ if (!exitCallback) process$2.exit(1);
2038
+ else {
2039
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
2040
+ wrappedError.nestedError = err;
2041
+ exitCallback(wrappedError);
2042
+ }
2043
+ });
2044
+ this.runningCommand = proc;
2045
+ }
2046
+ /**
2047
+ * @private
2048
+ */
2049
+ _dispatchSubcommand(commandName, operands, unknown) {
2050
+ const subCommand = this._findCommand(commandName);
2051
+ if (!subCommand) this.help({ error: true });
2052
+ subCommand._prepareForParse();
2053
+ let promiseChain;
2054
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
2055
+ promiseChain = this._chainOrCall(promiseChain, () => {
2056
+ if (subCommand._executableHandler) this._executeSubCommand(subCommand, operands.concat(unknown));
2057
+ else return subCommand._parseCommand(operands, unknown);
2058
+ });
2059
+ return promiseChain;
2060
+ }
2061
+ /**
2062
+ * Invoke help directly if possible, or dispatch if necessary.
2063
+ * e.g. help foo
2064
+ *
2065
+ * @private
2066
+ */
2067
+ _dispatchHelpCommand(subcommandName) {
2068
+ if (!subcommandName) this.help();
2069
+ const subCommand = this._findCommand(subcommandName);
2070
+ if (subCommand && !subCommand._executableHandler) subCommand.help();
2071
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
2072
+ }
2073
+ /**
2074
+ * Check this.args against expected this.registeredArguments.
2075
+ *
2076
+ * @private
2077
+ */
2078
+ _checkNumberOfArguments() {
2079
+ this.registeredArguments.forEach((arg, i) => {
2080
+ if (arg.required && this.args[i] == null) this.missingArgument(arg.name());
2081
+ });
2082
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) return;
2083
+ if (this.args.length > this.registeredArguments.length) this._excessArguments(this.args);
2084
+ }
2085
+ /**
2086
+ * Process this.args using this.registeredArguments and save as this.processedArgs!
2087
+ *
2088
+ * @private
2089
+ */
2090
+ _processArguments() {
2091
+ const myParseArg = (argument, value, previous) => {
2092
+ let parsedValue = value;
2093
+ if (value !== null && argument.parseArg) {
2094
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2095
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
2096
+ }
2097
+ return parsedValue;
2098
+ };
2099
+ this._checkNumberOfArguments();
2100
+ const processedArgs = [];
2101
+ this.registeredArguments.forEach((declaredArg, index) => {
2102
+ let value = declaredArg.defaultValue;
2103
+ if (declaredArg.variadic) {
2104
+ if (index < this.args.length) {
2105
+ value = this.args.slice(index);
2106
+ if (declaredArg.parseArg) value = value.reduce((processed, v) => {
2107
+ return myParseArg(declaredArg, v, processed);
2108
+ }, declaredArg.defaultValue);
2109
+ } else if (value === void 0) value = [];
2110
+ } else if (index < this.args.length) {
2111
+ value = this.args[index];
2112
+ if (declaredArg.parseArg) value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2113
+ }
2114
+ processedArgs[index] = value;
2115
+ });
2116
+ this.processedArgs = processedArgs;
2117
+ }
2118
+ /**
2119
+ * Once we have a promise we chain, but call synchronously until then.
2120
+ *
2121
+ * @param {(Promise|undefined)} promise
2122
+ * @param {Function} fn
2123
+ * @return {(Promise|undefined)}
2124
+ * @private
2125
+ */
2126
+ _chainOrCall(promise, fn) {
2127
+ if (promise?.then && typeof promise.then === "function") return promise.then(() => fn());
2128
+ return fn();
2129
+ }
2130
+ /**
2131
+ *
2132
+ * @param {(Promise|undefined)} promise
2133
+ * @param {string} event
2134
+ * @return {(Promise|undefined)}
2135
+ * @private
2136
+ */
2137
+ _chainOrCallHooks(promise, event) {
2138
+ let result = promise;
2139
+ const hooks = [];
2140
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2141
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2142
+ hooks.push({
2143
+ hookedCommand,
2144
+ callback
2145
+ });
2146
+ });
2147
+ });
2148
+ if (event === "postAction") hooks.reverse();
2149
+ hooks.forEach((hookDetail) => {
2150
+ result = this._chainOrCall(result, () => {
2151
+ return hookDetail.callback(hookDetail.hookedCommand, this);
2152
+ });
2153
+ });
2154
+ return result;
2155
+ }
2156
+ /**
2157
+ *
2158
+ * @param {(Promise|undefined)} promise
2159
+ * @param {Command} subCommand
2160
+ * @param {string} event
2161
+ * @return {(Promise|undefined)}
2162
+ * @private
2163
+ */
2164
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
2165
+ let result = promise;
2166
+ if (this._lifeCycleHooks[event] !== void 0) this._lifeCycleHooks[event].forEach((hook) => {
2167
+ result = this._chainOrCall(result, () => {
2168
+ return hook(this, subCommand);
2169
+ });
2170
+ });
2171
+ return result;
2172
+ }
2173
+ /**
2174
+ * Process arguments in context of this command.
2175
+ * Returns action result, in case it is a promise.
2176
+ *
2177
+ * @private
2178
+ */
2179
+ _parseCommand(operands, unknown) {
2180
+ const parsed = this.parseOptions(unknown);
2181
+ this._parseOptionsEnv();
2182
+ this._parseOptionsImplied();
2183
+ operands = operands.concat(parsed.operands);
2184
+ unknown = parsed.unknown;
2185
+ this.args = operands.concat(unknown);
2186
+ if (operands && this._findCommand(operands[0])) return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2187
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) return this._dispatchHelpCommand(operands[1]);
2188
+ if (this._defaultCommandName) {
2189
+ this._outputHelpIfRequested(unknown);
2190
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
2191
+ }
2192
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) this.help({ error: true });
2193
+ this._outputHelpIfRequested(parsed.unknown);
2194
+ this._checkForMissingMandatoryOptions();
2195
+ this._checkForConflictingOptions();
2196
+ const checkForUnknownOptions = () => {
2197
+ if (parsed.unknown.length > 0) this.unknownOption(parsed.unknown[0]);
2198
+ };
2199
+ const commandEvent = `command:${this.name()}`;
2200
+ if (this._actionHandler) {
2201
+ checkForUnknownOptions();
2202
+ this._processArguments();
2203
+ let promiseChain;
2204
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2205
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
2206
+ if (this.parent) promiseChain = this._chainOrCall(promiseChain, () => {
2207
+ this.parent.emit(commandEvent, operands, unknown);
2208
+ });
2209
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2210
+ return promiseChain;
2211
+ }
2212
+ if (this.parent?.listenerCount(commandEvent)) {
2213
+ checkForUnknownOptions();
2214
+ this._processArguments();
2215
+ this.parent.emit(commandEvent, operands, unknown);
2216
+ } else if (operands.length) {
2217
+ if (this._findCommand("*")) return this._dispatchSubcommand("*", operands, unknown);
2218
+ if (this.listenerCount("command:*")) this.emit("command:*", operands, unknown);
2219
+ else if (this.commands.length) this.unknownCommand();
2220
+ else {
2221
+ checkForUnknownOptions();
2222
+ this._processArguments();
2223
+ }
2224
+ } else if (this.commands.length) {
2225
+ checkForUnknownOptions();
2226
+ this.help({ error: true });
2227
+ } else {
2228
+ checkForUnknownOptions();
2229
+ this._processArguments();
2230
+ }
2231
+ }
2232
+ /**
2233
+ * Find matching command.
2234
+ *
2235
+ * @private
2236
+ * @return {Command | undefined}
2237
+ */
2238
+ _findCommand(name) {
2239
+ if (!name) return void 0;
2240
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
2241
+ }
2242
+ /**
2243
+ * Return an option matching `arg` if any.
2244
+ *
2245
+ * @param {string} arg
2246
+ * @return {Option}
2247
+ * @package
2248
+ */
2249
+ _findOption(arg) {
2250
+ return this.options.find((option) => option.is(arg));
2251
+ }
2252
+ /**
2253
+ * Display an error message if a mandatory option does not have a value.
2254
+ * Called after checking for help flags in leaf subcommand.
2255
+ *
2256
+ * @private
2257
+ */
2258
+ _checkForMissingMandatoryOptions() {
2259
+ this._getCommandAndAncestors().forEach((cmd) => {
2260
+ cmd.options.forEach((anOption) => {
2261
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) cmd.missingMandatoryOptionValue(anOption);
2262
+ });
2263
+ });
2264
+ }
2265
+ /**
2266
+ * Display an error message if conflicting options are used together in this.
2267
+ *
2268
+ * @private
2269
+ */
2270
+ _checkForConflictingLocalOptions() {
2271
+ const definedNonDefaultOptions = this.options.filter((option) => {
2272
+ const optionKey = option.attributeName();
2273
+ if (this.getOptionValue(optionKey) === void 0) return false;
2274
+ return this.getOptionValueSource(optionKey) !== "default";
2275
+ });
2276
+ definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0).forEach((option) => {
2277
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
2278
+ if (conflictingAndDefined) this._conflictingOption(option, conflictingAndDefined);
2279
+ });
2280
+ }
2281
+ /**
2282
+ * Display an error message if conflicting options are used together.
2283
+ * Called after checking for help flags in leaf subcommand.
2284
+ *
2285
+ * @private
2286
+ */
2287
+ _checkForConflictingOptions() {
2288
+ this._getCommandAndAncestors().forEach((cmd) => {
2289
+ cmd._checkForConflictingLocalOptions();
2290
+ });
2291
+ }
2292
+ /**
2293
+ * Parse options from `argv` removing known options,
2294
+ * and return argv split into operands and unknown arguments.
2295
+ *
2296
+ * Side effects: modifies command by storing options. Does not reset state if called again.
2297
+ *
2298
+ * Examples:
2299
+ *
2300
+ * argv => operands, unknown
2301
+ * --known kkk op => [op], []
2302
+ * op --known kkk => [op], []
2303
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
2304
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
2305
+ *
2306
+ * @param {string[]} args
2307
+ * @return {{operands: string[], unknown: string[]}}
2308
+ */
2309
+ parseOptions(args) {
2310
+ const operands = [];
2311
+ const unknown = [];
2312
+ let dest = operands;
2313
+ function maybeOption(arg) {
2314
+ return arg.length > 1 && arg[0] === "-";
2315
+ }
2316
+ const negativeNumberArg = (arg) => {
2317
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
2318
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
2319
+ };
2320
+ let activeVariadicOption = null;
2321
+ let activeGroup = null;
2322
+ let i = 0;
2323
+ while (i < args.length || activeGroup) {
2324
+ const arg = activeGroup ?? args[i++];
2325
+ activeGroup = null;
2326
+ if (arg === "--") {
2327
+ if (dest === unknown) dest.push(arg);
2328
+ dest.push(...args.slice(i));
2329
+ break;
2330
+ }
2331
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
2332
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
2333
+ continue;
2334
+ }
2335
+ activeVariadicOption = null;
2336
+ if (maybeOption(arg)) {
2337
+ const option = this._findOption(arg);
2338
+ if (option) {
2339
+ if (option.required) {
2340
+ const value = args[i++];
2341
+ if (value === void 0) this.optionMissingArgument(option);
2342
+ this.emit(`option:${option.name()}`, value);
2343
+ } else if (option.optional) {
2344
+ let value = null;
2345
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) value = args[i++];
2346
+ this.emit(`option:${option.name()}`, value);
2347
+ } else this.emit(`option:${option.name()}`);
2348
+ activeVariadicOption = option.variadic ? option : null;
2349
+ continue;
2350
+ }
2351
+ }
2352
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2353
+ const option = this._findOption(`-${arg[1]}`);
2354
+ if (option) {
2355
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) this.emit(`option:${option.name()}`, arg.slice(2));
2356
+ else {
2357
+ this.emit(`option:${option.name()}`);
2358
+ activeGroup = `-${arg.slice(2)}`;
2359
+ }
2360
+ continue;
2361
+ }
2362
+ }
2363
+ if (/^--[^=]+=/.test(arg)) {
2364
+ const index = arg.indexOf("=");
2365
+ const option = this._findOption(arg.slice(0, index));
2366
+ if (option && (option.required || option.optional)) {
2367
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
2368
+ continue;
2369
+ }
2370
+ }
2371
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) dest = unknown;
2372
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2373
+ if (this._findCommand(arg)) {
2374
+ operands.push(arg);
2375
+ unknown.push(...args.slice(i));
2376
+ break;
2377
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2378
+ operands.push(arg, ...args.slice(i));
2379
+ break;
2380
+ } else if (this._defaultCommandName) {
2381
+ unknown.push(arg, ...args.slice(i));
2382
+ break;
2383
+ }
2384
+ }
2385
+ if (this._passThroughOptions) {
2386
+ dest.push(arg, ...args.slice(i));
2387
+ break;
2388
+ }
2389
+ dest.push(arg);
2390
+ }
2391
+ return {
2392
+ operands,
2393
+ unknown
2394
+ };
2395
+ }
2396
+ /**
2397
+ * Return an object containing local option values as key-value pairs.
2398
+ *
2399
+ * @return {object}
2400
+ */
2401
+ opts() {
2402
+ if (this._storeOptionsAsProperties) {
2403
+ const result = {};
2404
+ const len = this.options.length;
2405
+ for (let i = 0; i < len; i++) {
2406
+ const key = this.options[i].attributeName();
2407
+ result[key] = key === this._versionOptionName ? this._version : this[key];
2408
+ }
2409
+ return result;
2410
+ }
2411
+ return this._optionValues;
2412
+ }
2413
+ /**
2414
+ * Return an object containing merged local and global option values as key-value pairs.
2415
+ *
2416
+ * @return {object}
2417
+ */
2418
+ optsWithGlobals() {
2419
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
2420
+ }
2421
+ /**
2422
+ * Display error message and exit (or call exitOverride).
2423
+ *
2424
+ * @param {string} message
2425
+ * @param {object} [errorOptions]
2426
+ * @param {string} [errorOptions.code] - an id string representing the error
2427
+ * @param {number} [errorOptions.exitCode] - used with process.exit
2428
+ */
2429
+ error(message, errorOptions) {
2430
+ this._outputConfiguration.outputError(`${message}\n`, this._outputConfiguration.writeErr);
2431
+ if (typeof this._showHelpAfterError === "string") this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`);
2432
+ else if (this._showHelpAfterError) {
2433
+ this._outputConfiguration.writeErr("\n");
2434
+ this.outputHelp({ error: true });
2435
+ }
2436
+ const config = errorOptions || {};
2437
+ const exitCode = config.exitCode || 1;
2438
+ const code = config.code || "commander.error";
2439
+ this._exit(exitCode, code, message);
2440
+ }
2441
+ /**
2442
+ * Apply any option related environment variables, if option does
2443
+ * not have a value from cli or client code.
2444
+ *
2445
+ * @private
2446
+ */
2447
+ _parseOptionsEnv() {
2448
+ this.options.forEach((option) => {
2449
+ if (option.envVar && option.envVar in process$2.env) {
2450
+ const optionKey = option.attributeName();
2451
+ if (this.getOptionValue(optionKey) === void 0 || [
2452
+ "default",
2453
+ "config",
2454
+ "env"
2455
+ ].includes(this.getOptionValueSource(optionKey))) if (option.required || option.optional) this.emit(`optionEnv:${option.name()}`, process$2.env[option.envVar]);
2456
+ else this.emit(`optionEnv:${option.name()}`);
2457
+ }
2458
+ });
2459
+ }
2460
+ /**
2461
+ * Apply any implied option values, if option is undefined or default value.
2462
+ *
2463
+ * @private
2464
+ */
2465
+ _parseOptionsImplied() {
2466
+ const dualHelper = new DualOptions(this.options);
2467
+ const hasCustomOptionValue = (optionKey) => {
2468
+ return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2469
+ };
2470
+ this.options.filter((option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
2471
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2472
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
2473
+ });
2474
+ });
2475
+ }
2476
+ /**
2477
+ * Argument `name` is missing.
2478
+ *
2479
+ * @param {string} name
2480
+ * @private
2481
+ */
2482
+ missingArgument(name) {
2483
+ const message = `error: missing required argument '${name}'`;
2484
+ this.error(message, { code: "commander.missingArgument" });
2485
+ }
2486
+ /**
2487
+ * `Option` is missing an argument.
2488
+ *
2489
+ * @param {Option} option
2490
+ * @private
2491
+ */
2492
+ optionMissingArgument(option) {
2493
+ const message = `error: option '${option.flags}' argument missing`;
2494
+ this.error(message, { code: "commander.optionMissingArgument" });
2495
+ }
2496
+ /**
2497
+ * `Option` does not have a value, and is a mandatory option.
2498
+ *
2499
+ * @param {Option} option
2500
+ * @private
2501
+ */
2502
+ missingMandatoryOptionValue(option) {
2503
+ const message = `error: required option '${option.flags}' not specified`;
2504
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
2505
+ }
2506
+ /**
2507
+ * `Option` conflicts with another option.
2508
+ *
2509
+ * @param {Option} option
2510
+ * @param {Option} conflictingOption
2511
+ * @private
2512
+ */
2513
+ _conflictingOption(option, conflictingOption) {
2514
+ const findBestOptionFromValue = (option) => {
2515
+ const optionKey = option.attributeName();
2516
+ const optionValue = this.getOptionValue(optionKey);
2517
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
2518
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
2519
+ if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) return negativeOption;
2520
+ return positiveOption || option;
2521
+ };
2522
+ const getErrorMessage = (option) => {
2523
+ const bestOption = findBestOptionFromValue(option);
2524
+ const optionKey = bestOption.attributeName();
2525
+ if (this.getOptionValueSource(optionKey) === "env") return `environment variable '${bestOption.envVar}'`;
2526
+ return `option '${bestOption.flags}'`;
2527
+ };
2528
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2529
+ this.error(message, { code: "commander.conflictingOption" });
2530
+ }
2531
+ /**
2532
+ * Unknown option `flag`.
2533
+ *
2534
+ * @param {string} flag
2535
+ * @private
2536
+ */
2537
+ unknownOption(flag) {
2538
+ if (this._allowUnknownOption) return;
2539
+ let suggestion = "";
2540
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
2541
+ let candidateFlags = [];
2542
+ let command = this;
2543
+ do {
2544
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2545
+ candidateFlags = candidateFlags.concat(moreFlags);
2546
+ command = command.parent;
2547
+ } while (command && !command._enablePositionalOptions);
2548
+ suggestion = suggestSimilar(flag, candidateFlags);
2549
+ }
2550
+ const message = `error: unknown option '${flag}'${suggestion}`;
2551
+ this.error(message, { code: "commander.unknownOption" });
2552
+ }
2553
+ /**
2554
+ * Excess arguments, more than expected.
2555
+ *
2556
+ * @param {string[]} receivedArgs
2557
+ * @private
2558
+ */
2559
+ _excessArguments(receivedArgs) {
2560
+ if (this._allowExcessArguments) return;
2561
+ const expected = this.registeredArguments.length;
2562
+ const s = expected === 1 ? "" : "s";
2563
+ const message = `error: too many arguments${this.parent ? ` for '${this.name()}'` : ""}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2564
+ this.error(message, { code: "commander.excessArguments" });
2565
+ }
2566
+ /**
2567
+ * Unknown command.
2568
+ *
2569
+ * @private
2570
+ */
2571
+ unknownCommand() {
2572
+ const unknownName = this.args[0];
2573
+ let suggestion = "";
2574
+ if (this._showSuggestionAfterError) {
2575
+ const candidateNames = [];
2576
+ this.createHelp().visibleCommands(this).forEach((command) => {
2577
+ candidateNames.push(command.name());
2578
+ if (command.alias()) candidateNames.push(command.alias());
2579
+ });
2580
+ suggestion = suggestSimilar(unknownName, candidateNames);
2581
+ }
2582
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
2583
+ this.error(message, { code: "commander.unknownCommand" });
2584
+ }
2585
+ /**
2586
+ * Get or set the program version.
2587
+ *
2588
+ * This method auto-registers the "-V, --version" option which will print the version number.
2589
+ *
2590
+ * You can optionally supply the flags and description to override the defaults.
2591
+ *
2592
+ * @param {string} [str]
2593
+ * @param {string} [flags]
2594
+ * @param {string} [description]
2595
+ * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2596
+ */
2597
+ version(str, flags, description) {
2598
+ if (str === void 0) return this._version;
2599
+ this._version = str;
2600
+ flags = flags || "-V, --version";
2601
+ description = description || "output the version number";
2602
+ const versionOption = this.createOption(flags, description);
2603
+ this._versionOptionName = versionOption.attributeName();
2604
+ this._registerOption(versionOption);
2605
+ this.on("option:" + versionOption.name(), () => {
2606
+ this._outputConfiguration.writeOut(`${str}\n`);
2607
+ this._exit(0, "commander.version", str);
2608
+ });
2609
+ return this;
2610
+ }
2611
+ /**
2612
+ * Set the description.
2613
+ *
2614
+ * @param {string} [str]
2615
+ * @param {object} [argsDescription]
2616
+ * @return {(string|Command)}
2617
+ */
2618
+ description(str, argsDescription) {
2619
+ if (str === void 0 && argsDescription === void 0) return this._description;
2620
+ this._description = str;
2621
+ if (argsDescription) this._argsDescription = argsDescription;
2622
+ return this;
2623
+ }
2624
+ /**
2625
+ * Set the summary. Used when listed as subcommand of parent.
2626
+ *
2627
+ * @param {string} [str]
2628
+ * @return {(string|Command)}
2629
+ */
2630
+ summary(str) {
2631
+ if (str === void 0) return this._summary;
2632
+ this._summary = str;
2633
+ return this;
2634
+ }
2635
+ /**
2636
+ * Set an alias for the command.
2637
+ *
2638
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2639
+ *
2640
+ * @param {string} [alias]
2641
+ * @return {(string|Command)}
2642
+ */
2643
+ alias(alias) {
2644
+ if (alias === void 0) return this._aliases[0];
2645
+ /** @type {Command} */
2646
+ let command = this;
2647
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) command = this.commands[this.commands.length - 1];
2648
+ if (alias === command._name) throw new Error("Command alias can't be the same as its name");
2649
+ const matchingCommand = this.parent?._findCommand(alias);
2650
+ if (matchingCommand) {
2651
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2652
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
2653
+ }
2654
+ command._aliases.push(alias);
2655
+ return this;
2656
+ }
2657
+ /**
2658
+ * Set aliases for the command.
2659
+ *
2660
+ * Only the first alias is shown in the auto-generated help.
2661
+ *
2662
+ * @param {string[]} [aliases]
2663
+ * @return {(string[]|Command)}
2664
+ */
2665
+ aliases(aliases) {
2666
+ if (aliases === void 0) return this._aliases;
2667
+ aliases.forEach((alias) => this.alias(alias));
2668
+ return this;
2669
+ }
2670
+ /**
2671
+ * Set / get the command usage `str`.
2672
+ *
2673
+ * @param {string} [str]
2674
+ * @return {(string|Command)}
2675
+ */
2676
+ usage(str) {
2677
+ if (str === void 0) {
2678
+ if (this._usage) return this._usage;
2679
+ const args = this.registeredArguments.map((arg) => {
2680
+ return humanReadableArgName(arg);
2681
+ });
2682
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
2683
+ }
2684
+ this._usage = str;
2685
+ return this;
2686
+ }
2687
+ /**
2688
+ * Get or set the name of the command.
2689
+ *
2690
+ * @param {string} [str]
2691
+ * @return {(string|Command)}
2692
+ */
2693
+ name(str) {
2694
+ if (str === void 0) return this._name;
2695
+ this._name = str;
2696
+ return this;
2697
+ }
2698
+ /**
2699
+ * Set/get the help group heading for this subcommand in parent command's help.
2700
+ *
2701
+ * @param {string} [heading]
2702
+ * @return {Command | string}
2703
+ */
2704
+ helpGroup(heading) {
2705
+ if (heading === void 0) return this._helpGroupHeading ?? "";
2706
+ this._helpGroupHeading = heading;
2707
+ return this;
2708
+ }
2709
+ /**
2710
+ * Set/get the default help group heading for subcommands added to this command.
2711
+ * (This does not override a group set directly on the subcommand using .helpGroup().)
2712
+ *
2713
+ * @example
2714
+ * program.commandsGroup('Development Commands:);
2715
+ * program.command('watch')...
2716
+ * program.command('lint')...
2717
+ * ...
2718
+ *
2719
+ * @param {string} [heading]
2720
+ * @returns {Command | string}
2721
+ */
2722
+ commandsGroup(heading) {
2723
+ if (heading === void 0) return this._defaultCommandGroup ?? "";
2724
+ this._defaultCommandGroup = heading;
2725
+ return this;
2726
+ }
2727
+ /**
2728
+ * Set/get the default help group heading for options added to this command.
2729
+ * (This does not override a group set directly on the option using .helpGroup().)
2730
+ *
2731
+ * @example
2732
+ * program
2733
+ * .optionsGroup('Development Options:')
2734
+ * .option('-d, --debug', 'output extra debugging')
2735
+ * .option('-p, --profile', 'output profiling information')
2736
+ *
2737
+ * @param {string} [heading]
2738
+ * @returns {Command | string}
2739
+ */
2740
+ optionsGroup(heading) {
2741
+ if (heading === void 0) return this._defaultOptionGroup ?? "";
2742
+ this._defaultOptionGroup = heading;
2743
+ return this;
2744
+ }
2745
+ /**
2746
+ * @param {Option} option
2747
+ * @private
2748
+ */
2749
+ _initOptionGroup(option) {
2750
+ if (this._defaultOptionGroup && !option.helpGroupHeading) option.helpGroup(this._defaultOptionGroup);
2751
+ }
2752
+ /**
2753
+ * @param {Command} cmd
2754
+ * @private
2755
+ */
2756
+ _initCommandGroup(cmd) {
2757
+ if (this._defaultCommandGroup && !cmd.helpGroup()) cmd.helpGroup(this._defaultCommandGroup);
2758
+ }
2759
+ /**
2760
+ * Set the name of the command from script filename, such as process.argv[1],
2761
+ * or require.main.filename, or __filename.
2762
+ *
2763
+ * (Used internally and public although not documented in README.)
2764
+ *
2765
+ * @example
2766
+ * program.nameFromFilename(require.main.filename);
2767
+ *
2768
+ * @param {string} filename
2769
+ * @return {Command}
2770
+ */
2771
+ nameFromFilename(filename) {
2772
+ this._name = path$2.basename(filename, path$2.extname(filename));
2773
+ return this;
2774
+ }
2775
+ /**
2776
+ * Get or set the directory for searching for executable subcommands of this command.
2777
+ *
2778
+ * @example
2779
+ * program.executableDir(__dirname);
2780
+ * // or
2781
+ * program.executableDir('subcommands');
2782
+ *
2783
+ * @param {string} [path]
2784
+ * @return {(string|null|Command)}
2785
+ */
2786
+ executableDir(path) {
2787
+ if (path === void 0) return this._executableDir;
2788
+ this._executableDir = path;
2789
+ return this;
2790
+ }
2791
+ /**
2792
+ * Return program help documentation.
2793
+ *
2794
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
2795
+ * @return {string}
2796
+ */
2797
+ helpInformation(contextOptions) {
2798
+ const helper = this.createHelp();
2799
+ const context = this._getOutputContext(contextOptions);
2800
+ helper.prepareContext({
2801
+ error: context.error,
2802
+ helpWidth: context.helpWidth,
2803
+ outputHasColors: context.hasColors
2804
+ });
2805
+ const text = helper.formatHelp(this, helper);
2806
+ if (context.hasColors) return text;
2807
+ return this._outputConfiguration.stripColor(text);
2808
+ }
2809
+ /**
2810
+ * @typedef HelpContext
2811
+ * @type {object}
2812
+ * @property {boolean} error
2813
+ * @property {number} helpWidth
2814
+ * @property {boolean} hasColors
2815
+ * @property {function} write - includes stripColor if needed
2816
+ *
2817
+ * @returns {HelpContext}
2818
+ * @private
2819
+ */
2820
+ _getOutputContext(contextOptions) {
2821
+ contextOptions = contextOptions || {};
2822
+ const error = !!contextOptions.error;
2823
+ let baseWrite;
2824
+ let hasColors;
2825
+ let helpWidth;
2826
+ if (error) {
2827
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
2828
+ hasColors = this._outputConfiguration.getErrHasColors();
2829
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
2830
+ } else {
2831
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
2832
+ hasColors = this._outputConfiguration.getOutHasColors();
2833
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
2834
+ }
2835
+ const write = (str) => {
2836
+ if (!hasColors) str = this._outputConfiguration.stripColor(str);
2837
+ return baseWrite(str);
2838
+ };
2839
+ return {
2840
+ error,
2841
+ write,
2842
+ hasColors,
2843
+ helpWidth
2844
+ };
2845
+ }
2846
+ /**
2847
+ * Output help information for this command.
2848
+ *
2849
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2850
+ *
2851
+ * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2852
+ */
2853
+ outputHelp(contextOptions) {
2854
+ let deprecatedCallback;
2855
+ if (typeof contextOptions === "function") {
2856
+ deprecatedCallback = contextOptions;
2857
+ contextOptions = void 0;
2858
+ }
2859
+ const outputContext = this._getOutputContext(contextOptions);
2860
+ /** @type {HelpTextEventContext} */
2861
+ const eventContext = {
2862
+ error: outputContext.error,
2863
+ write: outputContext.write,
2864
+ command: this
2865
+ };
2866
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
2867
+ this.emit("beforeHelp", eventContext);
2868
+ let helpInformation = this.helpInformation({ error: outputContext.error });
2869
+ if (deprecatedCallback) {
2870
+ helpInformation = deprecatedCallback(helpInformation);
2871
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) throw new Error("outputHelp callback must return a string or a Buffer");
2872
+ }
2873
+ outputContext.write(helpInformation);
2874
+ if (this._getHelpOption()?.long) this.emit(this._getHelpOption().long);
2875
+ this.emit("afterHelp", eventContext);
2876
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
2877
+ }
2878
+ /**
2879
+ * You can pass in flags and a description to customise the built-in help option.
2880
+ * Pass in false to disable the built-in help option.
2881
+ *
2882
+ * @example
2883
+ * program.helpOption('-?, --help' 'show help'); // customise
2884
+ * program.helpOption(false); // disable
2885
+ *
2886
+ * @param {(string | boolean)} flags
2887
+ * @param {string} [description]
2888
+ * @return {Command} `this` command for chaining
2889
+ */
2890
+ helpOption(flags, description) {
2891
+ if (typeof flags === "boolean") {
2892
+ if (flags) {
2893
+ if (this._helpOption === null) this._helpOption = void 0;
2894
+ if (this._defaultOptionGroup) this._initOptionGroup(this._getHelpOption());
2895
+ } else this._helpOption = null;
2896
+ return this;
2897
+ }
2898
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
2899
+ if (flags || description) this._initOptionGroup(this._helpOption);
2900
+ return this;
2901
+ }
2902
+ /**
2903
+ * Lazy create help option.
2904
+ * Returns null if has been disabled with .helpOption(false).
2905
+ *
2906
+ * @returns {(Option | null)} the help option
2907
+ * @package
2908
+ */
2909
+ _getHelpOption() {
2910
+ if (this._helpOption === void 0) this.helpOption(void 0, void 0);
2911
+ return this._helpOption;
2912
+ }
2913
+ /**
2914
+ * Supply your own option to use for the built-in help option.
2915
+ * This is an alternative to using helpOption() to customise the flags and description etc.
2916
+ *
2917
+ * @param {Option} option
2918
+ * @return {Command} `this` command for chaining
2919
+ */
2920
+ addHelpOption(option) {
2921
+ this._helpOption = option;
2922
+ this._initOptionGroup(option);
2923
+ return this;
2924
+ }
2925
+ /**
2926
+ * Output help information and exit.
2927
+ *
2928
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
2929
+ *
2930
+ * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
2931
+ */
2932
+ help(contextOptions) {
2933
+ this.outputHelp(contextOptions);
2934
+ let exitCode = Number(process$2.exitCode ?? 0);
2935
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) exitCode = 1;
2936
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2937
+ }
2938
+ /**
2939
+ * // Do a little typing to coordinate emit and listener for the help text events.
2940
+ * @typedef HelpTextEventContext
2941
+ * @type {object}
2942
+ * @property {boolean} error
2943
+ * @property {Command} command
2944
+ * @property {function} write
2945
+ */
2946
+ /**
2947
+ * Add additional text to be displayed with the built-in help.
2948
+ *
2949
+ * Position is 'before' or 'after' to affect just this command,
2950
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
2951
+ *
2952
+ * @param {string} position - before or after built-in help
2953
+ * @param {(string | Function)} text - string to add, or a function returning a string
2954
+ * @return {Command} `this` command for chaining
2955
+ */
2956
+ addHelpText(position, text) {
2957
+ const allowedValues = [
2958
+ "beforeAll",
2959
+ "before",
2960
+ "after",
2961
+ "afterAll"
2962
+ ];
2963
+ if (!allowedValues.includes(position)) throw new Error(`Unexpected value for position to addHelpText.
2964
+ Expecting one of '${allowedValues.join("', '")}'`);
2965
+ const helpEvent = `${position}Help`;
2966
+ this.on(helpEvent, (context) => {
2967
+ let helpStr;
2968
+ if (typeof text === "function") helpStr = text({
2969
+ error: context.error,
2970
+ command: context.command
2971
+ });
2972
+ else helpStr = text;
2973
+ if (helpStr) context.write(`${helpStr}\n`);
2974
+ });
2975
+ return this;
2976
+ }
2977
+ /**
2978
+ * Output help information if help flags specified
2979
+ *
2980
+ * @param {Array} args - array of options to search for help flags
2981
+ * @private
2982
+ */
2983
+ _outputHelpIfRequested(args) {
2984
+ const helpOption = this._getHelpOption();
2985
+ if (helpOption && args.find((arg) => helpOption.is(arg))) {
2986
+ this.outputHelp();
2987
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2988
+ }
2989
+ }
2990
+ };
2991
+ /**
2992
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
2993
+ *
2994
+ * @param {string[]} args - array of arguments from node.execArgv
2995
+ * @returns {string[]}
2996
+ * @private
2997
+ */
2998
+ function incrementNodeInspectorPort(args) {
2999
+ return args.map((arg) => {
3000
+ if (!arg.startsWith("--inspect")) return arg;
3001
+ let debugOption;
3002
+ let debugHost = "127.0.0.1";
3003
+ let debugPort = "9229";
3004
+ let match;
3005
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) debugOption = match[1];
3006
+ else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3007
+ debugOption = match[1];
3008
+ if (/^\d+$/.test(match[3])) debugPort = match[3];
3009
+ else debugHost = match[3];
3010
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3011
+ debugOption = match[1];
3012
+ debugHost = match[3];
3013
+ debugPort = match[4];
3014
+ }
3015
+ if (debugOption && debugPort !== "0") return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3016
+ return arg;
3017
+ });
3018
+ }
3019
+ /**
3020
+ * @returns {boolean | undefined}
3021
+ * @package
3022
+ */
3023
+ function useColor() {
3024
+ if (process$2.env.NO_COLOR || process$2.env.FORCE_COLOR === "0" || process$2.env.FORCE_COLOR === "false") return false;
3025
+ if (process$2.env.FORCE_COLOR || process$2.env.CLICOLOR_FORCE !== void 0) return true;
3026
+ }
3027
+ exports.Command = Command;
3028
+ exports.useColor = useColor;
3029
+ }));
3030
+ const { program: program$1, createCommand, createArgument, createOption, CommanderError, InvalidArgumentError, InvalidOptionArgumentError, Command, Argument, Option, Help } = (/* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports) => {
3031
+ const { Argument } = require_argument();
3032
+ const { Command } = require_command();
3033
+ const { CommanderError, InvalidArgumentError } = require_error();
3034
+ const { Help } = require_help();
3035
+ const { Option } = require_option();
3036
+ exports.program = new Command();
3037
+ exports.createCommand = (name) => new Command(name);
3038
+ exports.createOption = (flags, description) => new Option(flags, description);
3039
+ exports.createArgument = (name, description) => new Argument(name, description);
3040
+ /**
3041
+ * Expose classes
3042
+ */
3043
+ exports.Command = Command;
3044
+ exports.Option = Option;
3045
+ exports.Argument = Argument;
3046
+ exports.Help = Help;
3047
+ exports.CommanderError = CommanderError;
3048
+ exports.InvalidArgumentError = InvalidArgumentError;
3049
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
3050
+ })))(), 1)).default;
3051
+ //#endregion
3052
+ //#region src/utils/configShim.ts
3053
+ const CONFIG_EXTS = [
3054
+ "ts",
3055
+ "cts",
3056
+ "mts",
3057
+ "js",
3058
+ "cjs",
3059
+ "mjs"
3060
+ ];
3061
+ const findConfig = (cwd, base) => {
3062
+ for (const ext of CONFIG_EXTS) {
3063
+ const candidate = path$1.join(cwd, `${base}.config.${ext}`);
3064
+ if (fs$2.existsSync(candidate)) return candidate;
3065
+ }
3066
+ return null;
3067
+ };
3068
+ /**
3069
+ * Make Tile Push commands work against a published `@hot-updater/cli-tools`.
3070
+ *
3071
+ * Published cli-tools hardcodes its config filename to `hot-updater.config.*`
3072
+ * and ignores `HOT_UPDATER_CONFIG_NAME` (that override is fork-only). Tile Push
3073
+ * ships its config as `tile-push.config.*`, so on a plain `npm i` install the
3074
+ * loader would never find it.
3075
+ *
3076
+ * Fix: for the duration of a command, mirror `tile-push.config.*` to a transient
3077
+ * `hot-updater.config.<sameExt>` the published loader will find. Byte-identical,
3078
+ * so every relative import + env reference resolves the same. Removed after.
3079
+ *
3080
+ * No-op (writes nothing) when there's no `tile-push.config.*` (e.g. `init`,
3081
+ * `whoami`) or a real `hot-updater.config.*` already exists.
3082
+ */
3083
+ const ensureHotUpdaterConfig = (cwd = process.cwd()) => {
3084
+ const src = findConfig(cwd, "tile-push");
3085
+ if (!src) return () => {};
3086
+ if (findConfig(cwd, "hot-updater")) return () => {};
3087
+ const ext = src.split(".").pop();
3088
+ const dest = path$1.join(cwd, `hot-updater.config.${ext}`);
3089
+ try {
3090
+ fs$2.copyFileSync(src, dest);
3091
+ } catch {
3092
+ return () => {};
3093
+ }
3094
+ let cleaned = false;
3095
+ const cleanup = () => {
3096
+ if (cleaned) return;
3097
+ cleaned = true;
3098
+ try {
3099
+ fs$2.unlinkSync(dest);
3100
+ } catch {}
3101
+ };
3102
+ process.once("exit", cleanup);
3103
+ return cleanup;
3104
+ };
3105
+ //#endregion
3106
+ //#region src/utils/outputFilter.ts
3107
+ /**
3108
+ * Output filter that rewrites "hot-updater" / "Hot Updater" strings in
3109
+ * stdout/stderr to their Tile Push equivalents, so wrapped command output
3110
+ * never leaks the underlying tool's name.
3111
+ *
3112
+ * Implementation: we hijack process.stdout.write and process.stderr.write
3113
+ * for the duration of the wrapped call, run the regex on each chunk before
3114
+ * forwarding to the original writer. ANSI color codes pass through untouched
3115
+ * because the regex only matches alphabetic sequences.
3116
+ *
3117
+ * `withOutputFilter(fn)` is fire-and-forget — even if fn throws, the
3118
+ * originals are restored in a finally.
3119
+ *
3120
+ * It also mirrors `tile-push.config.*` to a transient `hot-updater.config.*`
3121
+ * (see {@link ensureHotUpdaterConfig}) so config discovery works against a
3122
+ * published `@hot-updater/cli-tools`, then removes it.
3123
+ */
3124
+ /**
3125
+ * How the user actually invokes this CLI, for the command suggestions we echo back.
3126
+ *
3127
+ * A wrapper sets this to its own verb: the Tile CLI runs us as `tile ota …`, so a
3128
+ * message reading "run 'tile-push fingerprint create'" sends people to a binary they
3129
+ * never installed. Defaults to our own name when nobody wraps us.
3130
+ */
3131
+ const CLI_NAME = process.env.TILE_PUSH_CLI_NAME?.trim() || "tile-push";
3132
+ /**
3133
+ * URLs must survive verbatim. Rewriting "hot-updater" everywhere also rewrote it INSIDE
3134
+ * the upstream repo link, so the banner advertised github.com/gronxb/tile-push — a
3135
+ * repository that does not exist — and asked users to star it. Park real URLs behind a
3136
+ * placeholder, run the rewrites, then restore them.
3137
+ */
3138
+ const URL_RE = /https?:\/\/\S+/g;
3139
+ const URL_TOKEN = "\0URL\0";
3140
+ const REPLACEMENTS = [
3141
+ [/Hot Updater/g, "Tile Push"],
3142
+ [/HotUpdater/g, "TilePush"],
3143
+ [/* @__PURE__ */ new RegExp("hot-updater(?= )", "g"), CLI_NAME],
3144
+ [/hot-updater/g, "tile-push"]
3145
+ ];
3146
+ /**
3147
+ * Drop the upstream banner entirely.
3148
+ *
3149
+ * ╭───────────────────────────────────────────╮
3150
+ * │ Tile Push - React Native OTA Solution │
3151
+ * │ Github: https://github.com/… │
3152
+ * │ Give a ⭐️ if you like it! │
3153
+ * ╰───────────────────────────────────────────╯
3154
+ *
3155
+ * It advertises a third-party repo and asks OUR users to star it, on every
3156
+ * command. It cannot be turned off upstream: `printBanner()` is called
3157
+ * unconditionally by every handler, and although `HOT_UPDATER_SKIP_BANNER=1` is
3158
+ * set in 18 places, nothing reads it. The only upstream guard is
3159
+ * `if (!options.json)` on three bundle subcommands — which is why `--json` was
3160
+ * the one clean path.
3161
+ *
3162
+ * Removing it HERE rather than in the Tile CLI is deliberate: the wrapper would
3163
+ * have to pipe the child's stdout to filter it, and this CLI is interactive
3164
+ * (clack prompts), so piping trades working prompts for a tidy banner. We are
3165
+ * already inside the write path, so it costs nothing here.
3166
+ *
3167
+ * Matched narrowly. The banner is a standalone rounded box; the boxes this CLI
3168
+ * draws itself open with `◇ …╮` and close with `├──╯`, so they cannot match.
3169
+ * The content guard is a second lock: a rounded box is dropped only if it
3170
+ * actually carries banner text.
3171
+ *
3172
+ * Caveat: this fires only when the banner arrives in one write, which is how
3173
+ * upstream emits it today. A future upstream that streamed it line-by-line
3174
+ * would slip through — visible immediately, and not worth carrying cross-chunk
3175
+ * state for until it happens.
3176
+ */
3177
+ const ROUNDED_BOX_RE = /╭[─]+╮[\s\S]*?╰[─]+╯\r?\n?/g;
3178
+ const BANNER_CONTENT_RE = /Give a ⭐|OTA Solution|Github:/;
3179
+ const stripBanner = (s) => s.replace(ROUNDED_BOX_RE, (block) => BANNER_CONTENT_RE.test(block) ? "" : block);
3180
+ const rewrite = (s) => {
3181
+ const urls = [];
3182
+ let out = s.replace(URL_RE, (u) => {
3183
+ urls.push(u);
3184
+ return URL_TOKEN;
3185
+ });
3186
+ for (const [pat, rep] of REPLACEMENTS) out = out.replace(pat, rep);
3187
+ let i = 0;
3188
+ return stripBanner(out.replace(new RegExp(URL_TOKEN, "g"), () => urls[i++] ?? ""));
3189
+ };
3190
+ const wrap = (original) => {
3191
+ return function wrapped(chunk, encOrCb, cb) {
3192
+ const filtered = rewrite(typeof chunk === "string" ? chunk : chunk.toString("utf8"));
3193
+ if (typeof encOrCb === "function") return original.call(this, filtered, encOrCb);
3194
+ return original.call(this, filtered, encOrCb, cb);
3195
+ };
3196
+ };
3197
+ const withOutputFilter = async (fn) => {
3198
+ const origOut = process.stdout.write.bind(process.stdout);
3199
+ const origErr = process.stderr.write.bind(process.stderr);
3200
+ const cleanupConfig = ensureHotUpdaterConfig();
3201
+ process.stdout.write = wrap(origOut);
3202
+ process.stderr.write = wrap(origErr);
3203
+ try {
3204
+ return await fn();
3205
+ } finally {
3206
+ process.stdout.write = origOut;
3207
+ process.stderr.write = origErr;
3208
+ cleanupConfig();
3209
+ }
3210
+ };
3211
+ //#endregion
3212
+ //#region src/commands/bundle.ts
3213
+ const parseBooleanOption = (value) => {
3214
+ if (value === "true") return true;
3215
+ if (value === "false") return false;
3216
+ throw new InvalidArgumentError("must be true or false");
3217
+ };
3218
+ const parseRolloutCohortCount = (value) => {
3219
+ const count = Number.parseInt(value, 10);
3220
+ if (!Number.isInteger(count) || count < 0 || count > 1e3) throw new InvalidArgumentError("must be an integer between 0 and 1000");
3221
+ return count;
3222
+ };
3223
+ const platformOption = new Option("--platform <platform>", "ios | android").choices(["ios", "android"]);
3224
+ const withWrapEnv = async (fn) => {
3225
+ process.env.HOT_UPDATER_CONFIG_NAME = "tile-push";
3226
+ process.env.HOT_UPDATER_SKIP_BANNER = "1";
3227
+ return withOutputFilter(fn);
3228
+ };
3229
+ /**
3230
+ * tile-push bundle <subcommand>
3231
+ *
3232
+ * Wraps hot-updater's bundle management commands. All subcommands run
3233
+ * through the configured database plugin — for tile-push customers that's
3234
+ * our tilePushDatabase, which proxies every call through the server.
3235
+ */
3236
+ const registerBundle = (program) => {
3237
+ const bundleCmd = program.command("bundle").description("Manage bundles");
3238
+ bundleCmd.command("list").description("List bundles, most recent first").option("-c, --channel <channel>", "filter by channel").option("--json", "output raw JSON").addOption(platformOption).option("--limit <n>", "max results", (value) => {
3239
+ const n = Number.parseInt(value, 10);
3240
+ if (!Number.isInteger(n) || n <= 0) throw new InvalidArgumentError("must be a positive integer");
3241
+ return n;
3242
+ }, 20).action(async (options) => {
3243
+ await withWrapEnv(() => handleBundleList(options));
3244
+ });
3245
+ bundleCmd.command("show").description("Show one bundle by id").argument("<bundle-id>", "bundle id").option("--json", "output raw JSON").action(async (bundleId, options) => {
3246
+ await withWrapEnv(() => handleBundleShow(bundleId, options));
3247
+ });
3248
+ bundleCmd.command("disable").description("Disable a bundle by id").argument("<bundle-id>", "bundle id").option("-y, --yes", "skip confirmation prompt").action(async (bundleId, options) => {
3249
+ await withWrapEnv(() => handleBundleSetEnabled(bundleId, false, options));
3250
+ });
3251
+ bundleCmd.command("enable").description("Re-enable a bundle by id").argument("<bundle-id>", "bundle id").option("-y, --yes", "skip confirmation prompt").action(async (bundleId, options) => {
3252
+ await withWrapEnv(() => handleBundleSetEnabled(bundleId, true, options));
3253
+ });
3254
+ bundleCmd.command("update").description("Update bundle rollout / targeting metadata").argument("<bundle-id>", "bundle id").option("--rollout-cohort-count <count>", "rollout cohort count (0-1000)", parseRolloutCohortCount).option("--force-update <value>", "force-update flag (true or false)", parseBooleanOption).option("--target-cohorts <cohorts>", "comma-separated target cohorts").option("--clear-target-cohorts", "clear target cohorts").option("--json", "output the updated bundle as JSON").option("-y, --yes", "skip confirmation prompt").action(async (...args) => {
3255
+ await withWrapEnv(() => handleBundleUpdate(...args));
3256
+ });
3257
+ bundleCmd.command("delete").description("Delete a bundle record by id").argument("<bundle-id>", "bundle id").option("-y, --yes", "skip confirmation prompt").action(async (bundleId, options) => {
3258
+ await withWrapEnv(() => handleBundleDelete(bundleId, options));
3259
+ });
3260
+ bundleCmd.command("promote").description("Move or copy a bundle to a different channel").argument("<bundle-id>", "bundle id").requiredOption("-t, --target <channel>", "target channel").addOption(new Option("-a, --action <action>", "copy creates a new bundle id; move keeps the id").choices(["copy", "move"]).default("copy")).option("-y, --yes", "skip confirmation prompt").action(async (bundleId, options) => {
3261
+ await withWrapEnv(() => handlePromote(bundleId, options));
3262
+ });
3263
+ };
3264
+ //#endregion
3265
+ //#region src/commands/channel.ts
3266
+ /**
3267
+ * tile-push channel
3268
+ * tile-push channel set <channel>
3269
+ *
3270
+ * Reads/writes native files (Android BuildConfig, iOS Info.plist) — no
3271
+ * server interaction, just local file ops.
3272
+ */
3273
+ const registerChannel = (program) => {
3274
+ const channelCmd = program.command("channel").description("Manage channels");
3275
+ channelCmd.action(async () => {
3276
+ process.env.HOT_UPDATER_CONFIG_NAME = "tile-push";
3277
+ process.env.HOT_UPDATER_SKIP_BANNER = "1";
3278
+ await withOutputFilter(() => handleChannel());
3279
+ });
3280
+ channelCmd.command("set").description("Set the channel for Android (BuildConfig) and iOS (Info.plist)").argument("<channel>", "channel to set").action(async (channel) => {
3281
+ process.env.HOT_UPDATER_CONFIG_NAME = "tile-push";
3282
+ process.env.HOT_UPDATER_SKIP_BANNER = "1";
3283
+ await withOutputFilter(() => handleSetChannel(channel));
3284
+ });
3285
+ };
3286
+ //#endregion
3287
+ //#region ../../node_modules/.pnpm/is-docker@3.0.0/node_modules/is-docker/index.js
3288
+ let isDockerCached;
3289
+ function hasDockerEnv() {
3290
+ try {
3291
+ fs.statSync("/.dockerenv");
3292
+ return true;
3293
+ } catch {
3294
+ return false;
3295
+ }
3296
+ }
3297
+ function hasDockerCGroup() {
3298
+ try {
3299
+ return fs.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
3300
+ } catch {
3301
+ return false;
3302
+ }
3303
+ }
3304
+ function isDocker() {
3305
+ if (isDockerCached === void 0) isDockerCached = hasDockerEnv() || hasDockerCGroup();
3306
+ return isDockerCached;
3307
+ }
3308
+ //#endregion
3309
+ //#region ../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js
3310
+ let cachedResult;
3311
+ const hasContainerEnv = () => {
3312
+ try {
3313
+ fs.statSync("/run/.containerenv");
3314
+ return true;
3315
+ } catch {
3316
+ return false;
3317
+ }
3318
+ };
3319
+ function isInsideContainer() {
3320
+ if (cachedResult === void 0) cachedResult = hasContainerEnv() || isDocker();
3321
+ return cachedResult;
3322
+ }
3323
+ //#endregion
3324
+ //#region ../../node_modules/.pnpm/is-wsl@3.1.1/node_modules/is-wsl/index.js
3325
+ const isWsl = () => {
3326
+ if (process$1.platform !== "linux") return false;
3327
+ if (os.release().toLowerCase().includes("microsoft")) {
3328
+ if (isInsideContainer()) return false;
3329
+ return true;
3330
+ }
3331
+ try {
3332
+ if (fs.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft")) return !isInsideContainer();
3333
+ } catch {}
3334
+ if (fs.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop") || fs.existsSync("/run/WSL")) return !isInsideContainer();
3335
+ return false;
3336
+ };
3337
+ var is_wsl_default = process$1.env.__IS_WSL_TEST__ ? isWsl : isWsl();
3338
+ //#endregion
3339
+ //#region ../../node_modules/.pnpm/define-lazy-prop@3.0.0/node_modules/define-lazy-prop/index.js
3340
+ function defineLazyProperty(object, propertyName, valueGetter) {
3341
+ const define = (value) => Object.defineProperty(object, propertyName, {
3342
+ value,
3343
+ enumerable: true,
3344
+ writable: true
3345
+ });
3346
+ Object.defineProperty(object, propertyName, {
3347
+ configurable: true,
3348
+ enumerable: true,
3349
+ get() {
3350
+ const result = valueGetter();
3351
+ define(result);
3352
+ return result;
3353
+ },
3354
+ set(value) {
3355
+ define(value);
3356
+ }
3357
+ });
3358
+ return object;
3359
+ }
3360
+ //#endregion
3361
+ //#region ../../node_modules/.pnpm/default-browser-id@5.0.1/node_modules/default-browser-id/index.js
3362
+ const execFileAsync$3 = promisify(execFile);
3363
+ async function defaultBrowserId() {
3364
+ if (process$1.platform !== "darwin") throw new Error("macOS only");
3365
+ const { stdout } = await execFileAsync$3("defaults", [
3366
+ "read",
3367
+ "com.apple.LaunchServices/com.apple.launchservices.secure",
3368
+ "LSHandlers"
3369
+ ]);
3370
+ const browserId = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout)?.groups.id ?? "com.apple.Safari";
3371
+ if (browserId === "com.apple.safari") return "com.apple.Safari";
3372
+ return browserId;
3373
+ }
3374
+ //#endregion
3375
+ //#region ../../node_modules/.pnpm/run-applescript@7.0.0/node_modules/run-applescript/index.js
3376
+ const execFileAsync$2 = promisify(execFile);
3377
+ async function runAppleScript(script, { humanReadableOutput = true } = {}) {
3378
+ if (process$1.platform !== "darwin") throw new Error("macOS only");
3379
+ const { stdout } = await execFileAsync$2("osascript", [
3380
+ "-e",
3381
+ script,
3382
+ humanReadableOutput ? [] : ["-ss"]
3383
+ ]);
3384
+ return stdout.trim();
3385
+ }
3386
+ //#endregion
3387
+ //#region ../../node_modules/.pnpm/bundle-name@4.1.0/node_modules/bundle-name/index.js
3388
+ async function bundleName(bundleId) {
3389
+ return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`);
3390
+ }
3391
+ //#endregion
3392
+ //#region ../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/windows.js
3393
+ const execFileAsync$1 = promisify(execFile);
3394
+ const windowsBrowserProgIds = {
3395
+ MSEdgeHTM: {
3396
+ name: "Edge",
3397
+ id: "com.microsoft.edge"
3398
+ },
3399
+ MSEdgeBHTML: {
3400
+ name: "Edge Beta",
3401
+ id: "com.microsoft.edge.beta"
3402
+ },
3403
+ MSEdgeDHTML: {
3404
+ name: "Edge Dev",
3405
+ id: "com.microsoft.edge.dev"
3406
+ },
3407
+ AppXq0fevzme2pys62n3e0fbqa7peapykr8v: {
3408
+ name: "Edge",
3409
+ id: "com.microsoft.edge.old"
3410
+ },
3411
+ ChromeHTML: {
3412
+ name: "Chrome",
3413
+ id: "com.google.chrome"
3414
+ },
3415
+ ChromeBHTML: {
3416
+ name: "Chrome Beta",
3417
+ id: "com.google.chrome.beta"
3418
+ },
3419
+ ChromeDHTML: {
3420
+ name: "Chrome Dev",
3421
+ id: "com.google.chrome.dev"
3422
+ },
3423
+ ChromiumHTM: {
3424
+ name: "Chromium",
3425
+ id: "org.chromium.Chromium"
3426
+ },
3427
+ BraveHTML: {
3428
+ name: "Brave",
3429
+ id: "com.brave.Browser"
3430
+ },
3431
+ BraveBHTML: {
3432
+ name: "Brave Beta",
3433
+ id: "com.brave.Browser.beta"
3434
+ },
3435
+ BraveDHTML: {
3436
+ name: "Brave Dev",
3437
+ id: "com.brave.Browser.dev"
3438
+ },
3439
+ BraveSSHTM: {
3440
+ name: "Brave Nightly",
3441
+ id: "com.brave.Browser.nightly"
3442
+ },
3443
+ FirefoxURL: {
3444
+ name: "Firefox",
3445
+ id: "org.mozilla.firefox"
3446
+ },
3447
+ OperaStable: {
3448
+ name: "Opera",
3449
+ id: "com.operasoftware.Opera"
3450
+ },
3451
+ VivaldiHTM: {
3452
+ name: "Vivaldi",
3453
+ id: "com.vivaldi.Vivaldi"
3454
+ },
3455
+ "IE.HTTP": {
3456
+ name: "Internet Explorer",
3457
+ id: "com.microsoft.ie"
3458
+ }
3459
+ };
3460
+ new Map(Object.entries(windowsBrowserProgIds));
3461
+ var UnknownBrowserError = class extends Error {};
3462
+ async function defaultBrowser$1(_execFileAsync = execFileAsync$1) {
3463
+ const { stdout } = await _execFileAsync("reg", [
3464
+ "QUERY",
3465
+ " HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
3466
+ "/v",
3467
+ "ProgId"
3468
+ ]);
3469
+ const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);
3470
+ if (!match) throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
3471
+ const { id } = match.groups;
3472
+ const dotIndex = id.lastIndexOf(".");
3473
+ const hyphenIndex = id.lastIndexOf("-");
3474
+ const baseIdByDot = dotIndex === -1 ? void 0 : id.slice(0, dotIndex);
3475
+ const baseIdByHyphen = hyphenIndex === -1 ? void 0 : id.slice(0, hyphenIndex);
3476
+ return windowsBrowserProgIds[id] ?? windowsBrowserProgIds[baseIdByDot] ?? windowsBrowserProgIds[baseIdByHyphen] ?? {
3477
+ name: id,
3478
+ id
3479
+ };
3480
+ }
3481
+ //#endregion
3482
+ //#region ../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/index.js
3483
+ const execFileAsync = promisify(execFile);
3484
+ const titleize = (string) => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase());
3485
+ async function defaultBrowser() {
3486
+ if (process$1.platform === "darwin") {
3487
+ const id = await defaultBrowserId();
3488
+ return {
3489
+ name: await bundleName(id),
3490
+ id
3491
+ };
3492
+ }
3493
+ if (process$1.platform === "linux") {
3494
+ const { stdout } = await execFileAsync("xdg-mime", [
3495
+ "query",
3496
+ "default",
3497
+ "x-scheme-handler/http"
3498
+ ]);
3499
+ const id = stdout.trim();
3500
+ return {
3501
+ name: titleize(id.replace(/.desktop$/, "").replace("-", " ")),
3502
+ id
3503
+ };
3504
+ }
3505
+ if (process$1.platform === "win32") return defaultBrowser$1();
3506
+ throw new Error("Only macOS, Linux, and Windows are supported");
3507
+ }
3508
+ //#endregion
3509
+ //#region ../../node_modules/.pnpm/open@10.1.0/node_modules/open/index.js
3510
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
3511
+ const localXdgOpenPath = path.join(__dirname, "xdg-open");
3512
+ const { platform, arch } = process$1;
3513
+ /**
3514
+ Get the mount point for fixed drives in WSL.
3515
+
3516
+ @inner
3517
+ @returns {string} The mount point.
3518
+ */
3519
+ const getWslDrivesMountPoint = (() => {
3520
+ const defaultMountPoint = "/mnt/";
3521
+ let mountPoint;
3522
+ return async function() {
3523
+ if (mountPoint) return mountPoint;
3524
+ const configFilePath = "/etc/wsl.conf";
3525
+ let isConfigFileExists = false;
3526
+ try {
3527
+ await fs$1.access(configFilePath, constants.F_OK);
3528
+ isConfigFileExists = true;
3529
+ } catch {}
3530
+ if (!isConfigFileExists) return defaultMountPoint;
3531
+ const configContent = await fs$1.readFile(configFilePath, { encoding: "utf8" });
3532
+ const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
3533
+ if (!configMountPoint) return defaultMountPoint;
3534
+ mountPoint = configMountPoint.groups.mountPoint.trim();
3535
+ mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
3536
+ return mountPoint;
3537
+ };
3538
+ })();
3539
+ const pTryEach = async (array, mapper) => {
3540
+ let latestError;
3541
+ for (const item of array) try {
3542
+ return await mapper(item);
3543
+ } catch (error) {
3544
+ latestError = error;
3545
+ }
3546
+ throw latestError;
3547
+ };
3548
+ const baseOpen = async (options) => {
3549
+ options = {
3550
+ wait: false,
3551
+ background: false,
3552
+ newInstance: false,
3553
+ allowNonzeroExitCode: false,
3554
+ ...options
3555
+ };
3556
+ if (Array.isArray(options.app)) return pTryEach(options.app, (singleApp) => baseOpen({
3557
+ ...options,
3558
+ app: singleApp
3559
+ }));
3560
+ let { name: app, arguments: appArguments = [] } = options.app ?? {};
3561
+ appArguments = [...appArguments];
3562
+ if (Array.isArray(app)) return pTryEach(app, (appName) => baseOpen({
3563
+ ...options,
3564
+ app: {
3565
+ name: appName,
3566
+ arguments: appArguments
3567
+ }
3568
+ }));
3569
+ if (app === "browser" || app === "browserPrivate") {
3570
+ const ids = {
3571
+ "com.google.chrome": "chrome",
3572
+ "google-chrome.desktop": "chrome",
3573
+ "org.mozilla.firefox": "firefox",
3574
+ "firefox.desktop": "firefox",
3575
+ "com.microsoft.msedge": "edge",
3576
+ "com.microsoft.edge": "edge",
3577
+ "microsoft-edge.desktop": "edge"
3578
+ };
3579
+ const flags = {
3580
+ chrome: "--incognito",
3581
+ firefox: "--private-window",
3582
+ edge: "--inPrivate"
3583
+ };
3584
+ const browser = await defaultBrowser();
3585
+ if (browser.id in ids) {
3586
+ const browserName = ids[browser.id];
3587
+ if (app === "browserPrivate") appArguments.push(flags[browserName]);
3588
+ return baseOpen({
3589
+ ...options,
3590
+ app: {
3591
+ name: apps[browserName],
3592
+ arguments: appArguments
3593
+ }
3594
+ });
3595
+ }
3596
+ throw new Error(`${browser.name} is not supported as a default browser`);
3597
+ }
3598
+ let command;
3599
+ const cliArguments = [];
3600
+ const childProcessOptions = {};
3601
+ if (platform === "darwin") {
3602
+ command = "open";
3603
+ if (options.wait) cliArguments.push("--wait-apps");
3604
+ if (options.background) cliArguments.push("--background");
3605
+ if (options.newInstance) cliArguments.push("--new");
3606
+ if (app) cliArguments.push("-a", app);
3607
+ } else if (platform === "win32" || is_wsl_default && !isInsideContainer() && !app) {
3608
+ const mountPoint = await getWslDrivesMountPoint();
3609
+ command = is_wsl_default ? `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` : `${process$1.env.SYSTEMROOT || process$1.env.windir || "C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell`;
3610
+ cliArguments.push("-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand");
3611
+ if (!is_wsl_default) childProcessOptions.windowsVerbatimArguments = true;
3612
+ const encodedArguments = ["Start"];
3613
+ if (options.wait) encodedArguments.push("-Wait");
3614
+ if (app) {
3615
+ encodedArguments.push(`"\`"${app}\`""`);
3616
+ if (options.target) appArguments.push(options.target);
3617
+ } else if (options.target) encodedArguments.push(`"${options.target}"`);
3618
+ if (appArguments.length > 0) {
3619
+ appArguments = appArguments.map((argument) => `"\`"${argument}\`""`);
3620
+ encodedArguments.push("-ArgumentList", appArguments.join(","));
3621
+ }
3622
+ options.target = Buffer$1.from(encodedArguments.join(" "), "utf16le").toString("base64");
3623
+ } else {
3624
+ if (app) command = app;
3625
+ else {
3626
+ const isBundled = !__dirname || __dirname === "/";
3627
+ let exeLocalXdgOpen = false;
3628
+ try {
3629
+ await fs$1.access(localXdgOpenPath, constants.X_OK);
3630
+ exeLocalXdgOpen = true;
3631
+ } catch {}
3632
+ command = process$1.versions.electron ?? (platform === "android" || isBundled || !exeLocalXdgOpen) ? "xdg-open" : localXdgOpenPath;
3633
+ }
3634
+ if (appArguments.length > 0) cliArguments.push(...appArguments);
3635
+ if (!options.wait) {
3636
+ childProcessOptions.stdio = "ignore";
3637
+ childProcessOptions.detached = true;
3638
+ }
3639
+ }
3640
+ if (platform === "darwin" && appArguments.length > 0) cliArguments.push("--args", ...appArguments);
3641
+ if (options.target) cliArguments.push(options.target);
3642
+ const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
3643
+ if (options.wait) return new Promise((resolve, reject) => {
3644
+ subprocess.once("error", reject);
3645
+ subprocess.once("close", (exitCode) => {
3646
+ if (!options.allowNonzeroExitCode && exitCode > 0) {
3647
+ reject(/* @__PURE__ */ new Error(`Exited with code ${exitCode}`));
3648
+ return;
3649
+ }
3650
+ resolve(subprocess);
3651
+ });
3652
+ });
3653
+ subprocess.unref();
3654
+ return subprocess;
3655
+ };
3656
+ const open = (target, options) => {
3657
+ if (typeof target !== "string") throw new TypeError("Expected a `target`");
3658
+ return baseOpen({
3659
+ ...options,
3660
+ target
3661
+ });
3662
+ };
3663
+ function detectArchBinary(binary) {
3664
+ if (typeof binary === "string" || Array.isArray(binary)) return binary;
3665
+ const { [arch]: archBinary } = binary;
3666
+ if (!archBinary) throw new Error(`${arch} is not supported`);
3667
+ return archBinary;
3668
+ }
3669
+ function detectPlatformBinary({ [platform]: platformBinary }, { wsl }) {
3670
+ if (wsl && is_wsl_default) return detectArchBinary(wsl);
3671
+ if (!platformBinary) throw new Error(`${platform} is not supported`);
3672
+ return detectArchBinary(platformBinary);
3673
+ }
3674
+ const apps = {};
3675
+ defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
3676
+ darwin: "google chrome",
3677
+ win32: "chrome",
3678
+ linux: [
3679
+ "google-chrome",
3680
+ "google-chrome-stable",
3681
+ "chromium"
3682
+ ]
3683
+ }, { wsl: {
3684
+ ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
3685
+ x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]
3686
+ } }));
3687
+ defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
3688
+ darwin: "firefox",
3689
+ win32: "C:\\Program Files\\Mozilla Firefox\\firefox.exe",
3690
+ linux: "firefox"
3691
+ }, { wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe" }));
3692
+ defineLazyProperty(apps, "edge", () => detectPlatformBinary({
3693
+ darwin: "microsoft edge",
3694
+ win32: "msedge",
3695
+ linux: ["microsoft-edge", "microsoft-edge-dev"]
3696
+ }, { wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe" }));
3697
+ defineLazyProperty(apps, "browser", () => "browser");
3698
+ defineLazyProperty(apps, "browserPrivate", () => "browserPrivate");
3699
+ //#endregion
3700
+ //#region src/branding.ts
3701
+ var import_picocolors = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
3702
+ let p = process || {}, argv = p.argv || [], env = p.env || {};
3703
+ let isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
3704
+ let formatter = (open, close, replace = open) => (input) => {
3705
+ let string = "" + input, index = string.indexOf(close, open.length);
3706
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
3707
+ };
3708
+ let replaceClose = (string, close, replace, index) => {
3709
+ let result = "", cursor = 0;
3710
+ do {
3711
+ result += string.substring(cursor, index) + replace;
3712
+ cursor = index + close.length;
3713
+ index = string.indexOf(close, cursor);
3714
+ } while (~index);
3715
+ return result + string.substring(cursor);
3716
+ };
3717
+ let createColors = (enabled = isColorSupported) => {
3718
+ let f = enabled ? formatter : () => String;
3719
+ return {
3720
+ isColorSupported: enabled,
3721
+ reset: f("\x1B[0m", "\x1B[0m"),
3722
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
3723
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
3724
+ italic: f("\x1B[3m", "\x1B[23m"),
3725
+ underline: f("\x1B[4m", "\x1B[24m"),
3726
+ inverse: f("\x1B[7m", "\x1B[27m"),
3727
+ hidden: f("\x1B[8m", "\x1B[28m"),
3728
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
3729
+ black: f("\x1B[30m", "\x1B[39m"),
3730
+ red: f("\x1B[31m", "\x1B[39m"),
3731
+ green: f("\x1B[32m", "\x1B[39m"),
3732
+ yellow: f("\x1B[33m", "\x1B[39m"),
3733
+ blue: f("\x1B[34m", "\x1B[39m"),
3734
+ magenta: f("\x1B[35m", "\x1B[39m"),
3735
+ cyan: f("\x1B[36m", "\x1B[39m"),
3736
+ white: f("\x1B[37m", "\x1B[39m"),
3737
+ gray: f("\x1B[90m", "\x1B[39m"),
3738
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
3739
+ bgRed: f("\x1B[41m", "\x1B[49m"),
3740
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
3741
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
3742
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
3743
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
3744
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
3745
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
3746
+ blackBright: f("\x1B[90m", "\x1B[39m"),
3747
+ redBright: f("\x1B[91m", "\x1B[39m"),
3748
+ greenBright: f("\x1B[92m", "\x1B[39m"),
3749
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
3750
+ blueBright: f("\x1B[94m", "\x1B[39m"),
3751
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
3752
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
3753
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
3754
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
3755
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
3756
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
3757
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
3758
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
3759
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
3760
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
3761
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
3762
+ };
3763
+ };
3764
+ module.exports = createColors();
3765
+ module.exports.createColors = createColors;
3766
+ })))(), 1);
3767
+ /**
3768
+ * Tile Push CLI banner. Printed at the start of each branded command
3769
+ * (deploy, init, bundle ops). Replaces the hot-updater banner which is
3770
+ * suppressed via HOT_UPDATER_SKIP_BANNER=1 when we invoke wrapped commands.
3771
+ */
3772
+ const BANNER_LINES = [
3773
+ " ████████╗██╗██╗ ███████╗ ██████╗ ██╗ ██╗███████╗██╗ ██╗",
3774
+ " ╚══██╔══╝██║██║ ██╔════╝ ██╔══██╗██║ ██║██╔════╝██║ ██║",
3775
+ " ██║ ██║██║ █████╗ ██████╔╝██║ ██║███████╗███████║",
3776
+ " ██║ ██║██║ ██╔══╝ ██╔═══╝ ██║ ██║╚════██║██╔══██║",
3777
+ " ██║ ██║███████╗███████╗ ██║ ╚██████╔╝███████║██║ ██║",
3778
+ " ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝"
3779
+ ];
3780
+ const TAGLINE = "OTA updates for React Native";
3781
+ const printTilePushBanner = (version) => {
3782
+ if (process.env.TILE_PUSH_SKIP_BANNER) return;
3783
+ const lines = ["", ...BANNER_LINES.map((l) => import_picocolors.default.cyan(l))];
3784
+ const taglineLine = version ? `${TAGLINE} · v${version}` : TAGLINE;
3785
+ lines.push("", ` ${import_picocolors.default.dim(taglineLine)}`, "");
3786
+ console.log(lines.join("\n"));
3787
+ };
3788
+ /**
3789
+ * Banner + tenant context. Use this for any command that's about to act on
3790
+ * a tenant (deploy, rollback, bundle disable/enable/delete) so the customer
3791
+ * sees which app they're about to touch BEFORE the action runs.
3792
+ *
3793
+ * Loads credentials best-effort: if not configured, prints the banner with
3794
+ * a "no credentials" warning instead of crashing — the underlying command
3795
+ * will surface the proper error a moment later, but the banner needs to
3796
+ * print first so the customer at least sees that we *tried* to identify
3797
+ * the tenant.
3798
+ */
3799
+ const printTilePushHeader = async (version) => {
3800
+ printTilePushBanner(version);
3801
+ if (process.env.TILE_PUSH_SKIP_BANNER) return;
3802
+ let appId = null;
3803
+ let apiUrl = null;
3804
+ try {
3805
+ const creds = await loadCredentials();
3806
+ if (creds) {
3807
+ appId = creds.appId;
3808
+ apiUrl = creds.apiUrl ?? null;
3809
+ }
3810
+ } catch {}
3811
+ if (appId) {
3812
+ const label = (k) => import_picocolors.default.dim(k.padEnd(8));
3813
+ console.log(` ${label("Tenant:")}${import_picocolors.default.bold(import_picocolors.default.cyan(appId))}`);
3814
+ if (apiUrl) console.log(` ${label("Server:")}${apiUrl}`);
3815
+ console.log("");
3816
+ } else {
3817
+ console.log(` ${import_picocolors.default.yellow("!")} ${import_picocolors.default.yellow("No Tile Push credentials configured")} — run ${import_picocolors.default.bold("tile-push init")} or export ${import_picocolors.default.bold("TILE_PUSH_APP_ID")} + ${import_picocolors.default.bold("TILE_PUSH_TOKEN")}`);
3818
+ console.log("");
3819
+ }
3820
+ };
3821
+ /**
3822
+ * Branded success message — used at the end of deploy / bundle commands.
3823
+ */
3824
+ const tilePushSuccess = (msg) => `${import_picocolors.default.green("✔")} ${msg}`;
3825
+ /**
3826
+ * Branded error message — for top-level catches before process exit.
3827
+ */
3828
+ const tilePushError = (msg) => `${import_picocolors.default.red("✖")} ${import_picocolors.default.red(msg)}`;
3829
+ //#endregion
3830
+ //#region src/commands/console.ts
3831
+ const DEFAULT_CONSOLE_URL = "https://console.tile-push.app";
3832
+ /**
3833
+ * tile-push console
3834
+ *
3835
+ * Opens the web console for the current tenant in the default browser.
3836
+ * The URL is derived from the active appId so customers don't have to
3837
+ * remember it (or paste it from Slack).
3838
+ */
3839
+ const registerConsole = (program) => {
3840
+ program.command("console").description("Open the Tile Push web console for the current tenant").option("--url <baseUrl>", "console base URL (defaults to https://console.tile-push.app)").action(async (options) => {
3841
+ try {
3842
+ const client = await TilePushClient.create();
3843
+ const target = `${(options.url ?? DEFAULT_CONSOLE_URL).replace(/\/+$/, "")}/${encodeURIComponent(client.appId)}`;
3844
+ console.log(`Opening ${target} ...`);
3845
+ await open(target);
3846
+ } catch (err) {
3847
+ console.error(tilePushError(err.message));
3848
+ process.exitCode = 1;
3849
+ }
3850
+ });
3851
+ };
3852
+ //#endregion
3853
+ //#region src/commands/deploy.ts
3854
+ const SEMVER_RANGE_PATTERN = /^[\d\sxX*~^.<>=|&-]+$/;
3855
+ const DEFAULT_CHANNEL = "production";
3856
+ /**
3857
+ * tile-push deploy
3858
+ *
3859
+ * Wraps hot-updater's deploy command. The wrap injects:
3860
+ * - HOT_UPDATER_CONFIG_NAME=tile-push so the loader looks for tile-push.config.ts
3861
+ * - HOT_UPDATER_SKIP_BANNER=1 so the hot-updater banner is suppressed
3862
+ * - withOutputFilter() so any leaking "Hot Updater" strings become "Tile Push"
3863
+ * - our own banner before invocation
3864
+ */
3865
+ const registerDeploy = (program) => {
3866
+ program.command("deploy").description("Build and ship a new bundle to Tile Push").addOption(new Option("-p, --platform <platform>", "ios | android").choices(["ios", "android"])).addOption(new Option("-t, --target-app-version <targetAppVersion>", "target app version (semver, e.g. 1.0.0, 1.x.x)").argParser((value) => {
3867
+ if (!SEMVER_RANGE_PATTERN.test(value)) throw new InvalidArgumentError("Invalid semver range (e.g. 1.0.0, 1.x.x).");
3868
+ return value;
3869
+ })).addOption(new Option("-d, --disabled", "ship disabled").default(false)).addOption(new Option("-f, --force-update", "require immediate update on launch").default(false)).addOption(new Option("-o, --bundle-output-path <bundleOutputPath>", "output dir for the bundle archive")).addOption(new Option("-r, --rollout <percentage>", "rollout percentage (0-100)").argParser((value) => {
3870
+ try {
3871
+ return normalizeRolloutPercentage(value);
3872
+ } catch (error) {
3873
+ throw new InvalidArgumentError(error.message);
3874
+ }
3875
+ }).default(100)).addOption(new Option("-i, --interactive", "prompt for missing options interactively").default(true)).addOption(new Option("-c, --channel <channel>", "release channel").default(DEFAULT_CHANNEL)).addOption(new Option("-m, --message <message>", "release notes; falls back to the latest git commit message")).action(async (options) => {
3876
+ process.env.HOT_UPDATER_CONFIG_NAME = "tile-push";
3877
+ process.env.HOT_UPDATER_SKIP_BANNER = "1";
3878
+ await printTilePushHeader();
3879
+ await withOutputFilter(() => deploy(options));
3880
+ });
3881
+ };
3882
+ //#endregion
3883
+ //#region src/commands/doctor.ts
3884
+ const fmt = (c) => {
3885
+ return `${c.status === "ok" ? import_picocolors.default.green("✔") : c.status === "warn" ? import_picocolors.default.yellow("!") : import_picocolors.default.red("✖")} ${c.name} — ${c.detail}`;
3886
+ };
3887
+ /**
3888
+ * tile-push doctor
3889
+ *
3890
+ * Runs through the common setup checks and reports which ones pass/fail.
3891
+ * Customer-facing — message wording assumes no prior context.
3892
+ */
3893
+ const registerDoctor = (program) => {
3894
+ program.command("doctor").description("Check the health of your Tile Push setup").option("--json", "output machine-readable JSON").action(async (options) => {
3895
+ const checks = [];
3896
+ const cwd = process.cwd();
3897
+ const configPath = join(cwd, "tile-push.config.ts");
3898
+ checks.push(existsSync(configPath) ? {
3899
+ name: "Config",
3900
+ status: "ok",
3901
+ detail: `tile-push.config.ts found at ${cwd}`
3902
+ } : {
3903
+ name: "Config",
3904
+ status: "fail",
3905
+ detail: "tile-push.config.ts missing in cwd. Run `tile-push init`."
3906
+ });
3907
+ const diag = await credentialsDiagnostic();
3908
+ if (diag.source === "env") checks.push({
3909
+ name: "Credentials",
3910
+ status: "ok",
3911
+ detail: `Loaded from ${diag.pathOrEnv}`
3912
+ });
3913
+ else if (diag.source === "file") checks.push({
3914
+ name: "Credentials",
3915
+ status: diag.modeOk ? "ok" : "warn",
3916
+ detail: diag.modeOk ? `Loaded from ${diag.pathOrEnv} (mode 0600)` : `Loaded from ${diag.pathOrEnv} but permissions are not 0600 — anyone with shell access can read your deploy token`
3917
+ });
3918
+ else checks.push({
3919
+ name: "Credentials",
3920
+ status: "fail",
3921
+ detail: `No credentials. Run \`tile-push init\` or set TILE_PUSH_APP_ID + TILE_PUSH_TOKEN.`
3922
+ });
3923
+ if (await loadCredentials()) try {
3924
+ const me = await (await TilePushClient.create()).get("/me");
3925
+ checks.push({
3926
+ name: "Server",
3927
+ status: "ok",
3928
+ detail: `Authenticated as "${me.tenantName}" with token "${me.tokenLabel}"`
3929
+ });
3930
+ } catch (err) {
3931
+ checks.push({
3932
+ name: "Server",
3933
+ status: "fail",
3934
+ detail: `Could not reach Tile Push API: ${err.message}`
3935
+ });
3936
+ }
3937
+ else checks.push({
3938
+ name: "Server",
3939
+ status: "warn",
3940
+ detail: "Skipped — no credentials to test with"
3941
+ });
3942
+ if (existsSync(join(cwd, "package.json"))) checks.push({
3943
+ name: "Project",
3944
+ status: "ok",
3945
+ detail: `package.json found at ${cwd}`
3946
+ });
3947
+ else checks.push({
3948
+ name: "Project",
3949
+ status: "warn",
3950
+ detail: "No package.json in cwd — run doctor from your RN project root"
3951
+ });
3952
+ if (options.json) {
3953
+ console.log(JSON.stringify(checks, null, 2));
3954
+ if (!checks.every((c) => c.status === "ok")) process.exitCode = 1;
3955
+ return;
3956
+ }
3957
+ for (const c of checks) console.log(fmt(c));
3958
+ const failed = checks.filter((c) => c.status === "fail");
3959
+ if (failed.length > 0) {
3960
+ console.log("");
3961
+ console.log(tilePushError(`${failed.length} check(s) failed.`));
3962
+ process.exitCode = 1;
3963
+ } else {
3964
+ console.log("");
3965
+ console.log(import_picocolors.default.green("All checks passed."));
3966
+ }
3967
+ });
3968
+ };
3969
+ //#endregion
3970
+ //#region src/commands/fingerprint.ts
3971
+ /**
3972
+ * tile-push fingerprint — compute / verify current fingerprint
3973
+ * tile-push fingerprint create — write a new fingerprint snapshot
3974
+ *
3975
+ * Fingerprints are pure local computation (no server interaction), so
3976
+ * these wraps exist purely for branding consistency.
3977
+ */
3978
+ const registerFingerprint = (program) => {
3979
+ const fpCmd = program.command("fingerprint").description("Generate fingerprint");
3980
+ fpCmd.action(async () => {
3981
+ process.env.HOT_UPDATER_CONFIG_NAME = "tile-push";
3982
+ process.env.HOT_UPDATER_SKIP_BANNER = "1";
3983
+ await withOutputFilter(() => handleFingerprint());
3984
+ });
3985
+ fpCmd.command("create").description("Create fingerprint").action(async () => {
3986
+ process.env.HOT_UPDATER_CONFIG_NAME = "tile-push";
3987
+ process.env.HOT_UPDATER_SKIP_BANNER = "1";
3988
+ await withOutputFilter(() => handleCreateFingerprint());
3989
+ });
3990
+ };
3991
+ //#endregion
3992
+ //#region src/commands/info.ts
3993
+ /**
3994
+ * tile-push info
3995
+ *
3996
+ * Prints every setting the CLI will resolve at runtime AND where each value
3997
+ * came from (env var, project .env file, ~/.tile-push/credentials.json,
3998
+ * default). Equivalent to `sentry-cli info` — the debugging tool you reach
3999
+ * for first when something resolves to a value you didn't expect.
4000
+ *
4001
+ * Non-destructive. Read-only. Safe to run anywhere.
4002
+ */
4003
+ const DEFAULT_API_URL = "https://ota.tile.dev";
4004
+ const CREDS_PATH = join(homedir(), ".tile-push", "credentials.json");
4005
+ const sourceLabel = (s) => {
4006
+ switch (s.kind) {
4007
+ case "env": return `env ${s.name}`;
4008
+ case "dotenv": return `${s.path} (.env file)`;
4009
+ case "credsFile": return s.path;
4010
+ case "default": return "default";
4011
+ case "missing": return "not set";
4012
+ }
4013
+ };
4014
+ const maskToken = (token) => {
4015
+ if (token.length <= 8) return "•".repeat(token.length);
4016
+ const tail = token.slice(-4);
4017
+ return `${token.slice(0, 4)}${"•".repeat(Math.min(token.length - 8, 12))}${tail}`;
4018
+ };
4019
+ /**
4020
+ * Parse a .env file just enough to pull out the keys we care about. We
4021
+ * deliberately don't depend on the `dotenv` package — we only need to
4022
+ * surface the value to the user; we don't load it into process.env (that's
4023
+ * the project's tile-push.config.ts's job via `import "dotenv/config"`).
4024
+ */
4025
+ const readDotenvKey = (envPath, key) => {
4026
+ if (!existsSync(envPath)) return null;
4027
+ try {
4028
+ const text = readFileSync(envPath, "utf8");
4029
+ for (const raw of text.split("\n")) {
4030
+ const line = raw.trim();
4031
+ if (!line || line.startsWith("#")) continue;
4032
+ const eq = line.indexOf("=");
4033
+ if (eq === -1) continue;
4034
+ if (line.slice(0, eq).trim() !== key) continue;
4035
+ let v = line.slice(eq + 1).trim();
4036
+ if (v.startsWith("\"") && v.endsWith("\"") || v.startsWith("'") && v.endsWith("'")) v = v.slice(1, -1);
4037
+ return v;
4038
+ }
4039
+ } catch {}
4040
+ return null;
4041
+ };
4042
+ const readCredsFile = () => {
4043
+ if (!existsSync(CREDS_PATH)) return null;
4044
+ try {
4045
+ const raw = readFileSync(CREDS_PATH, "utf8");
4046
+ return JSON.parse(raw);
4047
+ } catch {
4048
+ return null;
4049
+ }
4050
+ };
4051
+ const credsFileMode = () => {
4052
+ if (!existsSync(CREDS_PATH)) return null;
4053
+ try {
4054
+ const m = statSync(CREDS_PATH).mode & 511;
4055
+ return {
4056
+ ok: m === 384,
4057
+ mode: m.toString(8).padStart(4, "0")
4058
+ };
4059
+ } catch {
4060
+ return null;
4061
+ }
4062
+ };
4063
+ /**
4064
+ * Resolve a single string-valued setting in priority order:
4065
+ * 1. env var
4066
+ * 2. .env file in cwd
4067
+ * 3. credentials file
4068
+ * 4. fallback default (if provided)
4069
+ *
4070
+ * Also tracks any conflicting values from lower-priority sources so we can
4071
+ * warn about them — drift between .env and creds.json is a common cause of
4072
+ * "why am I deploying to the wrong tenant?"
4073
+ */
4074
+ const resolveSetting = (config) => {
4075
+ const candidates = [];
4076
+ if (config.envName) {
4077
+ const v = process.env[config.envName];
4078
+ if (v) candidates.push({
4079
+ value: v,
4080
+ source: {
4081
+ kind: "env",
4082
+ name: config.envName
4083
+ }
4084
+ });
4085
+ }
4086
+ if (config.dotenvKey) {
4087
+ const v = readDotenvKey(config.dotenvPath, config.dotenvKey);
4088
+ if (v) candidates.push({
4089
+ value: v,
4090
+ source: {
4091
+ kind: "dotenv",
4092
+ path: config.dotenvPath
4093
+ }
4094
+ });
4095
+ }
4096
+ if (config.credsValue) candidates.push({
4097
+ value: config.credsValue,
4098
+ source: {
4099
+ kind: "credsFile",
4100
+ path: CREDS_PATH
4101
+ }
4102
+ });
4103
+ if (candidates.length === 0) {
4104
+ if (config.fallback) return {
4105
+ value: config.fallback,
4106
+ source: { kind: "default" }
4107
+ };
4108
+ return {
4109
+ value: null,
4110
+ source: { kind: "missing" }
4111
+ };
4112
+ }
4113
+ const [primary, ...rest] = candidates;
4114
+ const conflicts = rest.filter((c) => c.value !== primary.value);
4115
+ return {
4116
+ value: primary.value,
4117
+ source: primary.source,
4118
+ conflicts: conflicts.length > 0 ? conflicts : void 0
4119
+ };
4120
+ };
4121
+ const fmtKv = (key, value, source) => {
4122
+ return ` ${import_picocolors.default.bold(key.padEnd(8))}${value} ${import_picocolors.default.dim(`← ${source}`)}`;
4123
+ };
4124
+ const VERSION$1 = "0.1.0";
4125
+ const registerInfo = (program) => {
4126
+ program.command("info").description("Print resolved Tile Push CLI settings and where each came from").option("--no-network", "skip the server reachability + auth check").option("--json", "output machine-readable JSON").action(async (options) => {
4127
+ const cwd = process.cwd();
4128
+ const configPath = join(cwd, "tile-push.config.ts");
4129
+ const envPath = join(cwd, ".env");
4130
+ const pkgPath = join(cwd, "package.json");
4131
+ const creds = readCredsFile();
4132
+ const credsMode = credsFileMode();
4133
+ const appId = resolveSetting({
4134
+ envName: "TILE_PUSH_APP_ID",
4135
+ dotenvKey: "TILE_PUSH_APP_ID",
4136
+ dotenvPath: envPath,
4137
+ credsValue: creds?.appId
4138
+ });
4139
+ const token = resolveSetting({
4140
+ envName: "TILE_PUSH_TOKEN",
4141
+ dotenvKey: "TILE_PUSH_TOKEN",
4142
+ dotenvPath: envPath,
4143
+ credsValue: creds?.token
4144
+ });
4145
+ const apiUrl = resolveSetting({
4146
+ envName: "TILE_PUSH_API_URL",
4147
+ dotenvKey: null,
4148
+ dotenvPath: envPath,
4149
+ credsValue: creds?.apiUrl,
4150
+ fallback: DEFAULT_API_URL
4151
+ });
4152
+ if (options.json) {
4153
+ const payload = {
4154
+ version: VERSION$1,
4155
+ binary: process.argv[1],
4156
+ node: process.version,
4157
+ platform: `${process.platform}/${process.arch}`,
4158
+ cwd,
4159
+ project: {
4160
+ configPath,
4161
+ configExists: existsSync(configPath),
4162
+ envPath,
4163
+ envExists: existsSync(envPath),
4164
+ pkgPath,
4165
+ pkgExists: existsSync(pkgPath)
4166
+ },
4167
+ user: {
4168
+ credsPath: CREDS_PATH,
4169
+ credsExists: !!creds,
4170
+ credsModeOk: credsMode?.ok ?? null,
4171
+ credsMode: credsMode?.mode ?? null
4172
+ },
4173
+ settings: {
4174
+ appId: {
4175
+ value: appId.value,
4176
+ source: sourceLabel(appId.source)
4177
+ },
4178
+ token: {
4179
+ value: token.value ? maskToken(token.value) : null,
4180
+ source: sourceLabel(token.source)
4181
+ },
4182
+ apiUrl: {
4183
+ value: apiUrl.value,
4184
+ source: sourceLabel(apiUrl.source)
4185
+ }
4186
+ },
4187
+ conflicts: {
4188
+ appId: appId.conflicts?.map((c) => ({
4189
+ value: c.value,
4190
+ source: sourceLabel(c.source)
4191
+ })),
4192
+ token: token.conflicts?.map((c) => ({
4193
+ value: maskToken(c.value),
4194
+ source: sourceLabel(c.source)
4195
+ })),
4196
+ apiUrl: apiUrl.conflicts?.map((c) => ({
4197
+ value: c.value,
4198
+ source: sourceLabel(c.source)
4199
+ }))
4200
+ }
4201
+ };
4202
+ console.log(JSON.stringify(payload, null, 2));
4203
+ return;
4204
+ }
4205
+ const rel = (p) => relative(cwd, p) || `.${p.endsWith("/") ? "/" : ""}`;
4206
+ console.log("");
4207
+ console.log(import_picocolors.default.bold("Tile Push CLI"));
4208
+ console.log(` version ${VERSION$1}`);
4209
+ console.log(` binary ${process.argv[1]}`);
4210
+ console.log(` node ${process.version}`);
4211
+ console.log(` platform ${process.platform}/${process.arch}`);
4212
+ console.log(` cwd ${cwd}`);
4213
+ console.log("");
4214
+ console.log(import_picocolors.default.bold("Project files (resolved from cwd)"));
4215
+ const mark = (ok) => ok ? import_picocolors.default.green("✔") : import_picocolors.default.dim("·");
4216
+ console.log(` ${mark(existsSync(configPath))} tile-push.config.ts ${import_picocolors.default.dim(rel(configPath))}`);
4217
+ console.log(` ${mark(existsSync(envPath))} .env ${import_picocolors.default.dim(rel(envPath))}`);
4218
+ console.log(` ${mark(existsSync(pkgPath))} package.json ${import_picocolors.default.dim(rel(pkgPath))}`);
4219
+ console.log("");
4220
+ console.log(import_picocolors.default.bold("User files (~/.tile-push)"));
4221
+ if (creds) {
4222
+ const modeColor = credsMode?.ok ?? false ? import_picocolors.default.green : import_picocolors.default.yellow;
4223
+ console.log(` ${import_picocolors.default.green("✔")} credentials.json ${import_picocolors.default.dim(CREDS_PATH)} ${modeColor(`(mode ${credsMode?.mode})`)}`);
4224
+ if (credsMode && !credsMode.ok) console.log(import_picocolors.default.yellow(` ! permissions should be 0600 — run: chmod 600 ${CREDS_PATH}`));
4225
+ } else console.log(` ${import_picocolors.default.dim("·")} credentials.json ${import_picocolors.default.dim(`${CREDS_PATH} (not present)`)}`);
4226
+ console.log("");
4227
+ console.log(import_picocolors.default.bold("Resolved settings"));
4228
+ if (appId.value) console.log(fmtKv("appId", appId.value, sourceLabel(appId.source)));
4229
+ else console.log(fmtKv("appId", import_picocolors.default.red("(not set)"), sourceLabel(appId.source)));
4230
+ if (token.value) console.log(fmtKv("token", maskToken(token.value), sourceLabel(token.source)));
4231
+ else console.log(fmtKv("token", import_picocolors.default.red("(not set)"), sourceLabel(token.source)));
4232
+ console.log(fmtKv("apiUrl", apiUrl.value ?? "", sourceLabel(apiUrl.source)));
4233
+ const conflicts = [
4234
+ ["appId", appId],
4235
+ ["token", token],
4236
+ ["apiUrl", apiUrl]
4237
+ ].filter(([, r]) => r.conflicts && r.conflicts.length > 0);
4238
+ if (conflicts.length > 0) {
4239
+ console.log("");
4240
+ console.log(import_picocolors.default.yellow(import_picocolors.default.bold("Conflicts")));
4241
+ for (const [name, r] of conflicts) {
4242
+ console.log(` ${import_picocolors.default.yellow("!")} ${name} differs across sources:`);
4243
+ for (const c of r.conflicts) {
4244
+ const shown = name === "token" ? maskToken(c.value) : c.value;
4245
+ console.log(` ${import_picocolors.default.dim(sourceLabel(c.source))}: ${shown}`);
4246
+ }
4247
+ }
4248
+ console.log(import_picocolors.default.dim(" (the value listed above under 'Resolved settings' wins per precedence: env > .env > credentials.json)"));
4249
+ }
4250
+ if (options.network === false) {
4251
+ console.log("");
4252
+ console.log(import_picocolors.default.dim("Server check skipped (--no-network)."));
4253
+ return;
4254
+ }
4255
+ if (!appId.value || !token.value) {
4256
+ console.log("");
4257
+ console.log(import_picocolors.default.dim("Server check skipped — no appId/token to authenticate with."));
4258
+ return;
4259
+ }
4260
+ console.log("");
4261
+ console.log(import_picocolors.default.bold("Server check"));
4262
+ try {
4263
+ const me = await (await TilePushClient.create()).get("/me");
4264
+ console.log(` ${import_picocolors.default.green("✔")} authenticated as "${me.tenantName}" (token: ${me.tokenLabel})`);
4265
+ } catch (err) {
4266
+ const msg = err instanceof Error ? err.message : String(err);
4267
+ console.log(` ${import_picocolors.default.red("✖")} ${msg}`);
4268
+ process.exitCode = 1;
4269
+ }
4270
+ });
4271
+ };
4272
+ //#endregion
4273
+ //#region src/commands/init.ts
4274
+ const prompt = (question, defaultValue) => {
4275
+ const rl = createInterface({
4276
+ input: process.stdin,
4277
+ output: process.stdout
4278
+ });
4279
+ const promptText = defaultValue ? `${question} ${import_picocolors.default.dim(`(${defaultValue})`)} ` : `${question} `;
4280
+ return new Promise((resolve) => {
4281
+ rl.question(promptText, (answer) => {
4282
+ rl.close();
4283
+ resolve(answer.trim() || defaultValue || "");
4284
+ });
4285
+ });
4286
+ };
4287
+ const promptYesNo = async (question, defaultYes = true) => {
4288
+ const hint = defaultYes ? "Y/n" : "y/N";
4289
+ const ans = await prompt(`${question} ${import_picocolors.default.dim(`[${hint}]`)}`);
4290
+ if (!ans) return defaultYes;
4291
+ return /^y(es)?$/i.test(ans);
4292
+ };
4293
+ const detectBundler = (cwd) => {
4294
+ const pkgPath = join(cwd, "package.json");
4295
+ if (!existsSync(pkgPath)) return null;
4296
+ try {
4297
+ const raw = readFileSync(pkgPath, "utf8");
4298
+ const pkg = JSON.parse(raw);
4299
+ const all = {
4300
+ ...pkg.dependencies,
4301
+ ...pkg.devDependencies
4302
+ };
4303
+ if (all.expo) return "expo";
4304
+ if (all["react-native"]) return "metro";
4305
+ } catch {}
4306
+ return null;
4307
+ };
4308
+ const renderConfig = (bundler) => {
4309
+ return `// Auto-loads .env so TILE_PUSH_APP_ID below resolves when invoked via
4310
+ // \`tile-push deploy\` from a shell that hasn't exported it explicitly.
4311
+ import "dotenv/config";
4312
+
4313
+ import { defineConfig } from "hot-updater";
4314
+ ${bundler === "expo" ? `import { expo } from "@hot-updater/expo";` : `import { metro } from "@hot-updater/metro";`}
4315
+ import { tilePushDatabase, tilePushStorage } from "@tiledev/tile-push-cli";
4316
+
4317
+ const appId = process.env.TILE_PUSH_APP_ID;
4318
+ if (!appId) {
4319
+ throw new Error(
4320
+ "TILE_PUSH_APP_ID is not set. Run \`tile-push init\` or export it manually.",
4321
+ );
4322
+ }
4323
+
4324
+ export default defineConfig({
4325
+ build: ${bundler === "expo" ? "expo({ enableHermes: true })" : "metro()"},
4326
+ storage: tilePushStorage({ appId }),
4327
+ database: tilePushDatabase({ appId }),
4328
+ // Fingerprint strategy: device sends its native fingerprint hash on
4329
+ // check-update and is only served bundles built from a matching native
4330
+ // tree. Safer than appVersion alone — catches accidental native drift.
4331
+ updateStrategy: "fingerprint",
4332
+ });
4333
+ `;
4334
+ };
4335
+ const upsertEnv = async (path, key, value) => {
4336
+ let existing = "";
4337
+ try {
4338
+ existing = await readFile(path, "utf8");
4339
+ } catch (err) {
4340
+ if (err.code !== "ENOENT") throw err;
4341
+ }
4342
+ const lines = existing.split("\n");
4343
+ let found = false;
4344
+ for (let i = 0; i < lines.length; i++) if (lines[i].startsWith(`${key}=`)) {
4345
+ lines[i] = `${key}=${value}`;
4346
+ found = true;
4347
+ break;
4348
+ }
4349
+ if (!found) {
4350
+ if (existing && !existing.endsWith("\n")) lines.push("");
4351
+ lines.push(`${key}=${value}`);
4352
+ }
4353
+ await writeFile(path, lines.join("\n"));
4354
+ };
4355
+ const registerInit = (program) => {
4356
+ program.command("init").description("Configure a project for Tile Push deploys").option("--app-id <appId>", "tenant app id (tk_...)").option("--token <token>", "deploy token").option("--bundler <bundler>", "bundler to use (metro|expo); auto-detected if omitted").option("--api-url <url>", "Tile Push API URL override").option("-y, --yes", "accept overwrites without prompting").action(async (options) => {
4357
+ printTilePushBanner();
4358
+ const cwd = process.cwd();
4359
+ const configPath = join(cwd, "tile-push.config.ts");
4360
+ const envPath = join(cwd, ".env");
4361
+ const appId = options.appId ?? await prompt("App id (e.g. tk_acme):");
4362
+ if (!appId) {
4363
+ console.error(tilePushError("App id is required."));
4364
+ process.exitCode = 1;
4365
+ return;
4366
+ }
4367
+ const token = options.token ?? await prompt("Deploy token (paste from the Tile Push console):");
4368
+ if (!token) {
4369
+ console.error(tilePushError("Deploy token is required."));
4370
+ process.exitCode = 1;
4371
+ return;
4372
+ }
4373
+ const detected = detectBundler(cwd);
4374
+ const bundler = options.bundler ?? detected ?? await prompt("Bundler (metro|expo):", "metro");
4375
+ if (existsSync(configPath) && !options.yes) if (!await promptYesNo(`${configPath} already exists. Overwrite?`, false)) console.log("Skipped config write.");
4376
+ else {
4377
+ await writeFile(configPath, renderConfig(bundler));
4378
+ console.log(tilePushSuccess(`Wrote ${configPath}`));
4379
+ }
4380
+ else {
4381
+ await writeFile(configPath, renderConfig(bundler));
4382
+ console.log(tilePushSuccess(`Wrote ${configPath}`));
4383
+ }
4384
+ await upsertEnv(envPath, "TILE_PUSH_APP_ID", appId);
4385
+ console.log(tilePushSuccess(`Added TILE_PUSH_APP_ID to ${envPath}`));
4386
+ await saveCredentials({
4387
+ appId,
4388
+ token,
4389
+ apiUrl: options.apiUrl
4390
+ });
4391
+ console.log(tilePushSuccess("Saved credentials to ~/.tile-push/credentials.json"));
4392
+ console.log("");
4393
+ console.log(`Next steps:`);
4394
+ console.log(` ${import_picocolors.default.cyan("tile-push deploy")} — ship a bundle`);
4395
+ console.log(` ${import_picocolors.default.cyan("tile-push whoami")} — verify your connection`);
4396
+ console.log(` ${import_picocolors.default.cyan("tile-push doctor")} — diagnose setup issues`);
4397
+ });
4398
+ };
4399
+ //#endregion
4400
+ //#region src/commands/rollback.ts
4401
+ /**
4402
+ * tile-push rollback <channel>
4403
+ *
4404
+ * Disables the most recent enabled bundle on a channel. The device picks
4405
+ * up the disabled flag on its next check-update and rolls back to the
4406
+ * previous enabled bundle (or INIT_ROLLBACK if none).
4407
+ */
4408
+ const registerRollback = (program) => {
4409
+ program.command("rollback").description("Disable the most recent enabled bundle on a channel").argument("<channel>", "channel to roll back").addOption(new Option("--platform <platform>", "ios | android").choices(["ios", "android"])).option("-y, --yes", "skip confirmation prompt").option("--target <bundle-id>", "scope rollback to exactly this bundle id (use to retry a failed rollback)").action(async (channel, options) => {
4410
+ process.env.HOT_UPDATER_CONFIG_NAME = "tile-push";
4411
+ process.env.HOT_UPDATER_SKIP_BANNER = "1";
4412
+ await printTilePushHeader();
4413
+ await withOutputFilter(() => handleRollback(channel, options));
4414
+ });
4415
+ };
4416
+ //#endregion
4417
+ //#region src/commands/whoami.ts
4418
+ /**
4419
+ * tile-push whoami
4420
+ *
4421
+ * Hits GET /me on the server and prints the active tenant identity. Useful
4422
+ * for confirming the right credentials are in place before deploying.
4423
+ */
4424
+ const registerWhoami = (program) => {
4425
+ program.command("whoami").description("Show the active Tile Push tenant and token info").option("--json", "output as JSON").action(async (options) => {
4426
+ try {
4427
+ const me = await (await TilePushClient.create()).get("/me");
4428
+ if (options.json) {
4429
+ console.log(JSON.stringify(me, null, 2));
4430
+ return;
4431
+ }
4432
+ console.log(`${import_picocolors.default.bold("Tenant:")} ${me.tenantName}`);
4433
+ console.log(`${import_picocolors.default.bold("App id:")} ${me.appId}`);
4434
+ console.log(`${import_picocolors.default.bold("Token: ")} ${me.tokenLabel}`);
4435
+ } catch (err) {
4436
+ if (err instanceof TilePushApiError) console.error(tilePushError(err.message));
4437
+ else console.error(tilePushError(err.message));
4438
+ process.exitCode = 1;
4439
+ }
4440
+ });
4441
+ };
4442
+ //#endregion
4443
+ //#region bin/tile-push.ts
4444
+ const VERSION = "0.1.0";
4445
+ const program = new Command();
4446
+ program.name("tile-push").description("Tile Push — OTA updates for React Native").version(VERSION);
4447
+ registerInit(program);
4448
+ registerDeploy(program);
4449
+ registerBundle(program);
4450
+ registerRollback(program);
4451
+ registerChannel(program);
4452
+ registerFingerprint(program);
4453
+ registerWhoami(program);
4454
+ registerConsole(program);
4455
+ registerDoctor(program);
4456
+ registerInfo(program);
4457
+ program.parseAsync(process.argv).catch((err) => {
4458
+ console.error(err);
4459
+ process.exit(1);
4460
+ });
4461
+ //#endregion
4462
+ export {};