@uipath/api-workflow-tool 1.203.0-preview.205 → 1.204.0-preview.206

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,4809 @@
1
+ import {
2
+ CommandDimensions,
3
+ ErrorDimensions,
4
+ LOCAL_PERMISSION_ERROR_CODES,
5
+ TelemetryService,
6
+ buildAgentSessionTelemetry,
7
+ buildCommandTelemetryAttribution,
8
+ catchError,
9
+ findHttpStatusInGraph,
10
+ recordSuppliedArgumentValues,
11
+ redactProperties,
12
+ releaseSuppliedArgumentValues,
13
+ singleton,
14
+ walkErrorGraph
15
+ } from "./packager-tool-69mfq5g8.js";
16
+ import {
17
+ __commonJS,
18
+ __require,
19
+ __toESM
20
+ } from "./packager-tool-1de529jm.js";
21
+
22
+ // ../../node_modules/commander/lib/error.js
23
+ var require_error = __commonJS(function(exports) {
24
+ class CommanderError extends Error {
25
+ constructor(exitCode, code, message) {
26
+ super(message);
27
+ Error.captureStackTrace(this, this.constructor);
28
+ this.name = this.constructor.name;
29
+ this.code = code;
30
+ this.exitCode = exitCode;
31
+ this.nestedError = undefined;
32
+ }
33
+ }
34
+
35
+ class InvalidArgumentError extends CommanderError {
36
+ constructor(message) {
37
+ super(1, "commander.invalidArgument", message);
38
+ Error.captureStackTrace(this, this.constructor);
39
+ this.name = this.constructor.name;
40
+ }
41
+ }
42
+ exports.CommanderError = CommanderError;
43
+ exports.InvalidArgumentError = InvalidArgumentError;
44
+ });
45
+
46
+ // ../../node_modules/commander/lib/argument.js
47
+ var require_argument = __commonJS(function(exports) {
48
+ var { InvalidArgumentError } = require_error();
49
+
50
+ class Argument {
51
+ constructor(name, description) {
52
+ this.description = description || "";
53
+ this.variadic = false;
54
+ this.parseArg = undefined;
55
+ this.defaultValue = undefined;
56
+ this.defaultValueDescription = undefined;
57
+ this.argChoices = undefined;
58
+ switch (name[0]) {
59
+ case "<":
60
+ this.required = true;
61
+ this._name = name.slice(1, -1);
62
+ break;
63
+ case "[":
64
+ this.required = false;
65
+ this._name = name.slice(1, -1);
66
+ break;
67
+ default:
68
+ this.required = true;
69
+ this._name = name;
70
+ break;
71
+ }
72
+ if (this._name.endsWith("...")) {
73
+ this.variadic = true;
74
+ this._name = this._name.slice(0, -3);
75
+ }
76
+ }
77
+ name() {
78
+ return this._name;
79
+ }
80
+ _collectValue(value, previous) {
81
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
82
+ return [value];
83
+ }
84
+ previous.push(value);
85
+ return previous;
86
+ }
87
+ default(value, description) {
88
+ this.defaultValue = value;
89
+ this.defaultValueDescription = description;
90
+ return this;
91
+ }
92
+ argParser(fn) {
93
+ this.parseArg = fn;
94
+ return this;
95
+ }
96
+ choices(values) {
97
+ this.argChoices = values.slice();
98
+ this.parseArg = (arg, previous) => {
99
+ if (!this.argChoices.includes(arg)) {
100
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
101
+ }
102
+ if (this.variadic) {
103
+ return this._collectValue(arg, previous);
104
+ }
105
+ return arg;
106
+ };
107
+ return this;
108
+ }
109
+ argRequired() {
110
+ this.required = true;
111
+ return this;
112
+ }
113
+ argOptional() {
114
+ this.required = false;
115
+ return this;
116
+ }
117
+ }
118
+ function humanReadableArgName(arg) {
119
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
120
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
121
+ }
122
+ exports.Argument = Argument;
123
+ exports.humanReadableArgName = humanReadableArgName;
124
+ });
125
+
126
+ // ../../node_modules/commander/lib/help.js
127
+ var require_help = __commonJS(function(exports) {
128
+ var { humanReadableArgName } = require_argument();
129
+
130
+ class Help {
131
+ constructor() {
132
+ this.helpWidth = undefined;
133
+ this.minWidthToWrap = 40;
134
+ this.sortSubcommands = false;
135
+ this.sortOptions = false;
136
+ this.showGlobalOptions = false;
137
+ }
138
+ prepareContext(contextOptions) {
139
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
140
+ }
141
+ visibleCommands(cmd) {
142
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
143
+ const helpCommand = cmd._getHelpCommand();
144
+ if (helpCommand && !helpCommand._hidden) {
145
+ visibleCommands.push(helpCommand);
146
+ }
147
+ if (this.sortSubcommands) {
148
+ visibleCommands.sort((a, b) => {
149
+ return a.name().localeCompare(b.name());
150
+ });
151
+ }
152
+ return visibleCommands;
153
+ }
154
+ compareOptions(a, b) {
155
+ const getSortKey = (option) => {
156
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
157
+ };
158
+ return getSortKey(a).localeCompare(getSortKey(b));
159
+ }
160
+ visibleOptions(cmd) {
161
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
162
+ const helpOption = cmd._getHelpOption();
163
+ if (helpOption && !helpOption.hidden) {
164
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
165
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
166
+ if (!removeShort && !removeLong) {
167
+ visibleOptions.push(helpOption);
168
+ } else if (helpOption.long && !removeLong) {
169
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
170
+ } else if (helpOption.short && !removeShort) {
171
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
172
+ }
173
+ }
174
+ if (this.sortOptions) {
175
+ visibleOptions.sort(this.compareOptions);
176
+ }
177
+ return visibleOptions;
178
+ }
179
+ visibleGlobalOptions(cmd) {
180
+ if (!this.showGlobalOptions)
181
+ return [];
182
+ const globalOptions = [];
183
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
184
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
185
+ globalOptions.push(...visibleOptions);
186
+ }
187
+ if (this.sortOptions) {
188
+ globalOptions.sort(this.compareOptions);
189
+ }
190
+ return globalOptions;
191
+ }
192
+ visibleArguments(cmd) {
193
+ if (cmd._argsDescription) {
194
+ cmd.registeredArguments.forEach((argument) => {
195
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
196
+ });
197
+ }
198
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
199
+ return cmd.registeredArguments;
200
+ }
201
+ return [];
202
+ }
203
+ subcommandTerm(cmd) {
204
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
205
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
206
+ }
207
+ optionTerm(option) {
208
+ return option.flags;
209
+ }
210
+ argumentTerm(argument) {
211
+ return argument.name();
212
+ }
213
+ longestSubcommandTermLength(cmd, helper) {
214
+ return helper.visibleCommands(cmd).reduce((max, command) => {
215
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
216
+ }, 0);
217
+ }
218
+ longestOptionTermLength(cmd, helper) {
219
+ return helper.visibleOptions(cmd).reduce((max, option) => {
220
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
221
+ }, 0);
222
+ }
223
+ longestGlobalOptionTermLength(cmd, helper) {
224
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
225
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
226
+ }, 0);
227
+ }
228
+ longestArgumentTermLength(cmd, helper) {
229
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
230
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
231
+ }, 0);
232
+ }
233
+ commandUsage(cmd) {
234
+ let cmdName = cmd._name;
235
+ if (cmd._aliases[0]) {
236
+ cmdName = cmdName + "|" + cmd._aliases[0];
237
+ }
238
+ let ancestorCmdNames = "";
239
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
240
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
241
+ }
242
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
243
+ }
244
+ commandDescription(cmd) {
245
+ return cmd.description();
246
+ }
247
+ subcommandDescription(cmd) {
248
+ return cmd.summary() || cmd.description();
249
+ }
250
+ optionDescription(option) {
251
+ const extraInfo = [];
252
+ if (option.argChoices) {
253
+ extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
254
+ }
255
+ if (option.defaultValue !== undefined) {
256
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
257
+ if (showDefault) {
258
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
259
+ }
260
+ }
261
+ if (option.presetArg !== undefined && option.optional) {
262
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
263
+ }
264
+ if (option.envVar !== undefined) {
265
+ extraInfo.push(`env: ${option.envVar}`);
266
+ }
267
+ if (extraInfo.length > 0) {
268
+ const extraDescription = `(${extraInfo.join(", ")})`;
269
+ if (option.description) {
270
+ return `${option.description} ${extraDescription}`;
271
+ }
272
+ return extraDescription;
273
+ }
274
+ return option.description;
275
+ }
276
+ argumentDescription(argument) {
277
+ const extraInfo = [];
278
+ if (argument.argChoices) {
279
+ extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
280
+ }
281
+ if (argument.defaultValue !== undefined) {
282
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
283
+ }
284
+ if (extraInfo.length > 0) {
285
+ const extraDescription = `(${extraInfo.join(", ")})`;
286
+ if (argument.description) {
287
+ return `${argument.description} ${extraDescription}`;
288
+ }
289
+ return extraDescription;
290
+ }
291
+ return argument.description;
292
+ }
293
+ formatItemList(heading, items, helper) {
294
+ if (items.length === 0)
295
+ return [];
296
+ return [helper.styleTitle(heading), ...items, ""];
297
+ }
298
+ groupItems(unsortedItems, visibleItems, getGroup) {
299
+ const result = new Map;
300
+ unsortedItems.forEach((item) => {
301
+ const group = getGroup(item);
302
+ if (!result.has(group))
303
+ result.set(group, []);
304
+ });
305
+ visibleItems.forEach((item) => {
306
+ const group = getGroup(item);
307
+ if (!result.has(group)) {
308
+ result.set(group, []);
309
+ }
310
+ result.get(group).push(item);
311
+ });
312
+ return result;
313
+ }
314
+ formatHelp(cmd, helper) {
315
+ const termWidth = helper.padWidth(cmd, helper);
316
+ const helpWidth = helper.helpWidth ?? 80;
317
+ function callFormatItem(term, description) {
318
+ return helper.formatItem(term, termWidth, description, helper);
319
+ }
320
+ let output = [
321
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
322
+ ""
323
+ ];
324
+ const commandDescription = helper.commandDescription(cmd);
325
+ if (commandDescription.length > 0) {
326
+ output = output.concat([
327
+ helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth),
328
+ ""
329
+ ]);
330
+ }
331
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
332
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
333
+ });
334
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
335
+ const optionGroups = this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:");
336
+ optionGroups.forEach((options, group) => {
337
+ const optionList = options.map((option) => {
338
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
339
+ });
340
+ output = output.concat(this.formatItemList(group, optionList, helper));
341
+ });
342
+ if (helper.showGlobalOptions) {
343
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
344
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
345
+ });
346
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
347
+ }
348
+ const commandGroups = this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:");
349
+ commandGroups.forEach((commands, group) => {
350
+ const commandList = commands.map((sub) => {
351
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
352
+ });
353
+ output = output.concat(this.formatItemList(group, commandList, helper));
354
+ });
355
+ return output.join(`
356
+ `);
357
+ }
358
+ displayWidth(str) {
359
+ return stripColor(str).length;
360
+ }
361
+ styleTitle(str) {
362
+ return str;
363
+ }
364
+ styleUsage(str) {
365
+ return str.split(" ").map((word) => {
366
+ if (word === "[options]")
367
+ return this.styleOptionText(word);
368
+ if (word === "[command]")
369
+ return this.styleSubcommandText(word);
370
+ if (word[0] === "[" || word[0] === "<")
371
+ return this.styleArgumentText(word);
372
+ return this.styleCommandText(word);
373
+ }).join(" ");
374
+ }
375
+ styleCommandDescription(str) {
376
+ return this.styleDescriptionText(str);
377
+ }
378
+ styleOptionDescription(str) {
379
+ return this.styleDescriptionText(str);
380
+ }
381
+ styleSubcommandDescription(str) {
382
+ return this.styleDescriptionText(str);
383
+ }
384
+ styleArgumentDescription(str) {
385
+ return this.styleDescriptionText(str);
386
+ }
387
+ styleDescriptionText(str) {
388
+ return str;
389
+ }
390
+ styleOptionTerm(str) {
391
+ return this.styleOptionText(str);
392
+ }
393
+ styleSubcommandTerm(str) {
394
+ return str.split(" ").map((word) => {
395
+ if (word === "[options]")
396
+ return this.styleOptionText(word);
397
+ if (word[0] === "[" || word[0] === "<")
398
+ return this.styleArgumentText(word);
399
+ return this.styleSubcommandText(word);
400
+ }).join(" ");
401
+ }
402
+ styleArgumentTerm(str) {
403
+ return this.styleArgumentText(str);
404
+ }
405
+ styleOptionText(str) {
406
+ return str;
407
+ }
408
+ styleArgumentText(str) {
409
+ return str;
410
+ }
411
+ styleSubcommandText(str) {
412
+ return str;
413
+ }
414
+ styleCommandText(str) {
415
+ return str;
416
+ }
417
+ padWidth(cmd, helper) {
418
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
419
+ }
420
+ preformatted(str) {
421
+ return /\n[^\S\r\n]/.test(str);
422
+ }
423
+ formatItem(term, termWidth, description, helper) {
424
+ const itemIndent = 2;
425
+ const itemIndentStr = " ".repeat(itemIndent);
426
+ if (!description)
427
+ return itemIndentStr + term;
428
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
429
+ const spacerWidth = 2;
430
+ const helpWidth = this.helpWidth ?? 80;
431
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
432
+ let formattedDescription;
433
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
434
+ formattedDescription = description;
435
+ } else {
436
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
437
+ formattedDescription = wrappedDescription.replace(/\n/g, `
438
+ ` + " ".repeat(termWidth + spacerWidth));
439
+ }
440
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
441
+ ${itemIndentStr}`);
442
+ }
443
+ boxWrap(str, width) {
444
+ if (width < this.minWidthToWrap)
445
+ return str;
446
+ const rawLines = str.split(/\r\n|\n/);
447
+ const chunkPattern = /[\s]*[^\s]+/g;
448
+ const wrappedLines = [];
449
+ rawLines.forEach((line) => {
450
+ const chunks = line.match(chunkPattern);
451
+ if (chunks === null) {
452
+ wrappedLines.push("");
453
+ return;
454
+ }
455
+ let sumChunks = [chunks.shift()];
456
+ let sumWidth = this.displayWidth(sumChunks[0]);
457
+ chunks.forEach((chunk) => {
458
+ const visibleWidth = this.displayWidth(chunk);
459
+ if (sumWidth + visibleWidth <= width) {
460
+ sumChunks.push(chunk);
461
+ sumWidth += visibleWidth;
462
+ return;
463
+ }
464
+ wrappedLines.push(sumChunks.join(""));
465
+ const nextChunk = chunk.trimStart();
466
+ sumChunks = [nextChunk];
467
+ sumWidth = this.displayWidth(nextChunk);
468
+ });
469
+ wrappedLines.push(sumChunks.join(""));
470
+ });
471
+ return wrappedLines.join(`
472
+ `);
473
+ }
474
+ }
475
+ function stripColor(str) {
476
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
477
+ return str.replace(sgrPattern, "");
478
+ }
479
+ exports.Help = Help;
480
+ exports.stripColor = stripColor;
481
+ });
482
+
483
+ // ../../node_modules/commander/lib/option.js
484
+ var require_option = __commonJS(function(exports) {
485
+ var { InvalidArgumentError } = require_error();
486
+
487
+ class Option {
488
+ constructor(flags, description) {
489
+ this.flags = flags;
490
+ this.description = description || "";
491
+ this.required = flags.includes("<");
492
+ this.optional = flags.includes("[");
493
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
494
+ this.mandatory = false;
495
+ const optionFlags = splitOptionFlags(flags);
496
+ this.short = optionFlags.shortFlag;
497
+ this.long = optionFlags.longFlag;
498
+ this.negate = false;
499
+ if (this.long) {
500
+ this.negate = this.long.startsWith("--no-");
501
+ }
502
+ this.defaultValue = undefined;
503
+ this.defaultValueDescription = undefined;
504
+ this.presetArg = undefined;
505
+ this.envVar = undefined;
506
+ this.parseArg = undefined;
507
+ this.hidden = false;
508
+ this.argChoices = undefined;
509
+ this.conflictsWith = [];
510
+ this.implied = undefined;
511
+ this.helpGroupHeading = undefined;
512
+ }
513
+ default(value, description) {
514
+ this.defaultValue = value;
515
+ this.defaultValueDescription = description;
516
+ return this;
517
+ }
518
+ preset(arg) {
519
+ this.presetArg = arg;
520
+ return this;
521
+ }
522
+ conflicts(names) {
523
+ this.conflictsWith = this.conflictsWith.concat(names);
524
+ return this;
525
+ }
526
+ implies(impliedOptionValues) {
527
+ let newImplied = impliedOptionValues;
528
+ if (typeof impliedOptionValues === "string") {
529
+ newImplied = { [impliedOptionValues]: true };
530
+ }
531
+ this.implied = Object.assign(this.implied || {}, newImplied);
532
+ return this;
533
+ }
534
+ env(name) {
535
+ this.envVar = name;
536
+ return this;
537
+ }
538
+ argParser(fn) {
539
+ this.parseArg = fn;
540
+ return this;
541
+ }
542
+ makeOptionMandatory(mandatory = true) {
543
+ this.mandatory = !!mandatory;
544
+ return this;
545
+ }
546
+ hideHelp(hide = true) {
547
+ this.hidden = !!hide;
548
+ return this;
549
+ }
550
+ _collectValue(value, previous) {
551
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
552
+ return [value];
553
+ }
554
+ previous.push(value);
555
+ return previous;
556
+ }
557
+ choices(values) {
558
+ this.argChoices = values.slice();
559
+ this.parseArg = (arg, previous) => {
560
+ if (!this.argChoices.includes(arg)) {
561
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
562
+ }
563
+ if (this.variadic) {
564
+ return this._collectValue(arg, previous);
565
+ }
566
+ return arg;
567
+ };
568
+ return this;
569
+ }
570
+ name() {
571
+ if (this.long) {
572
+ return this.long.replace(/^--/, "");
573
+ }
574
+ return this.short.replace(/^-/, "");
575
+ }
576
+ attributeName() {
577
+ if (this.negate) {
578
+ return camelcase(this.name().replace(/^no-/, ""));
579
+ }
580
+ return camelcase(this.name());
581
+ }
582
+ helpGroup(heading) {
583
+ this.helpGroupHeading = heading;
584
+ return this;
585
+ }
586
+ is(arg) {
587
+ return this.short === arg || this.long === arg;
588
+ }
589
+ isBoolean() {
590
+ return !this.required && !this.optional && !this.negate;
591
+ }
592
+ }
593
+
594
+ class DualOptions {
595
+ constructor(options) {
596
+ this.positiveOptions = new Map;
597
+ this.negativeOptions = new Map;
598
+ this.dualOptions = new Set;
599
+ options.forEach((option) => {
600
+ if (option.negate) {
601
+ this.negativeOptions.set(option.attributeName(), option);
602
+ } else {
603
+ this.positiveOptions.set(option.attributeName(), option);
604
+ }
605
+ });
606
+ this.negativeOptions.forEach((value, key) => {
607
+ if (this.positiveOptions.has(key)) {
608
+ this.dualOptions.add(key);
609
+ }
610
+ });
611
+ }
612
+ valueFromOption(value, option) {
613
+ const optionKey = option.attributeName();
614
+ if (!this.dualOptions.has(optionKey))
615
+ return true;
616
+ const preset = this.negativeOptions.get(optionKey).presetArg;
617
+ const negativeValue = preset !== undefined ? preset : false;
618
+ return option.negate === (negativeValue === value);
619
+ }
620
+ }
621
+ function camelcase(str) {
622
+ return str.split("-").reduce((str2, word) => {
623
+ return str2 + word[0].toUpperCase() + word.slice(1);
624
+ });
625
+ }
626
+ function splitOptionFlags(flags) {
627
+ let shortFlag;
628
+ let longFlag;
629
+ const shortFlagExp = /^-[^-]$/;
630
+ const longFlagExp = /^--[^-]/;
631
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
632
+ if (shortFlagExp.test(flagParts[0]))
633
+ shortFlag = flagParts.shift();
634
+ if (longFlagExp.test(flagParts[0]))
635
+ longFlag = flagParts.shift();
636
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
637
+ shortFlag = flagParts.shift();
638
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
639
+ shortFlag = longFlag;
640
+ longFlag = flagParts.shift();
641
+ }
642
+ if (flagParts[0].startsWith("-")) {
643
+ const unsupportedFlag = flagParts[0];
644
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
645
+ if (/^-[^-][^-]/.test(unsupportedFlag))
646
+ throw new Error(`${baseError}
647
+ - a short flag is a single dash and a single character
648
+ - either use a single dash and a single character (for a short flag)
649
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
650
+ if (shortFlagExp.test(unsupportedFlag))
651
+ throw new Error(`${baseError}
652
+ - too many short flags`);
653
+ if (longFlagExp.test(unsupportedFlag))
654
+ throw new Error(`${baseError}
655
+ - too many long flags`);
656
+ throw new Error(`${baseError}
657
+ - unrecognised flag format`);
658
+ }
659
+ if (shortFlag === undefined && longFlag === undefined)
660
+ throw new Error(`option creation failed due to no flags found in '${flags}'.`);
661
+ return { shortFlag, longFlag };
662
+ }
663
+ exports.Option = Option;
664
+ exports.DualOptions = DualOptions;
665
+ });
666
+
667
+ // ../../node_modules/commander/lib/suggestSimilar.js
668
+ var require_suggestSimilar = __commonJS(function(exports) {
669
+ var maxDistance = 3;
670
+ function editDistance(a, b) {
671
+ if (Math.abs(a.length - b.length) > maxDistance)
672
+ return Math.max(a.length, b.length);
673
+ const d = [];
674
+ for (let i = 0;i <= a.length; i++) {
675
+ d[i] = [i];
676
+ }
677
+ for (let j = 0;j <= b.length; j++) {
678
+ d[0][j] = j;
679
+ }
680
+ for (let j = 1;j <= b.length; j++) {
681
+ for (let i = 1;i <= a.length; i++) {
682
+ let cost = 1;
683
+ if (a[i - 1] === b[j - 1]) {
684
+ cost = 0;
685
+ } else {
686
+ cost = 1;
687
+ }
688
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
689
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
690
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
691
+ }
692
+ }
693
+ }
694
+ return d[a.length][b.length];
695
+ }
696
+ function suggestSimilar(word, candidates) {
697
+ if (!candidates || candidates.length === 0)
698
+ return "";
699
+ candidates = Array.from(new Set(candidates));
700
+ const searchingOptions = word.startsWith("--");
701
+ if (searchingOptions) {
702
+ word = word.slice(2);
703
+ candidates = candidates.map((candidate) => candidate.slice(2));
704
+ }
705
+ let similar = [];
706
+ let bestDistance = maxDistance;
707
+ const minSimilarity = 0.4;
708
+ candidates.forEach((candidate) => {
709
+ if (candidate.length <= 1)
710
+ return;
711
+ const distance = editDistance(word, candidate);
712
+ const length = Math.max(word.length, candidate.length);
713
+ const similarity = (length - distance) / length;
714
+ if (similarity > minSimilarity) {
715
+ if (distance < bestDistance) {
716
+ bestDistance = distance;
717
+ similar = [candidate];
718
+ } else if (distance === bestDistance) {
719
+ similar.push(candidate);
720
+ }
721
+ }
722
+ });
723
+ similar.sort((a, b) => a.localeCompare(b));
724
+ if (searchingOptions) {
725
+ similar = similar.map((candidate) => `--${candidate}`);
726
+ }
727
+ if (similar.length > 1) {
728
+ return `
729
+ (Did you mean one of ${similar.join(", ")}?)`;
730
+ }
731
+ if (similar.length === 1) {
732
+ return `
733
+ (Did you mean ${similar[0]}?)`;
734
+ }
735
+ return "";
736
+ }
737
+ exports.suggestSimilar = suggestSimilar;
738
+ });
739
+
740
+ // ../../node_modules/commander/lib/command.js
741
+ var require_command = __commonJS(function(exports) {
742
+ var EventEmitter = __require("node:events").EventEmitter;
743
+ var childProcess = __require("node:child_process");
744
+ var path2 = __require("node:path");
745
+ var fs2 = __require("node:fs");
746
+ var process2 = __require("node:process");
747
+ var { Argument, humanReadableArgName } = require_argument();
748
+ var { CommanderError } = require_error();
749
+ var { Help, stripColor } = require_help();
750
+ var { Option, DualOptions } = require_option();
751
+ var { suggestSimilar } = require_suggestSimilar();
752
+
753
+ class Command extends EventEmitter {
754
+ constructor(name) {
755
+ super();
756
+ this.commands = [];
757
+ this.options = [];
758
+ this.parent = null;
759
+ this._allowUnknownOption = false;
760
+ this._allowExcessArguments = false;
761
+ this.registeredArguments = [];
762
+ this._args = this.registeredArguments;
763
+ this.args = [];
764
+ this.rawArgs = [];
765
+ this.processedArgs = [];
766
+ this._scriptPath = null;
767
+ this._name = name || "";
768
+ this._optionValues = {};
769
+ this._optionValueSources = {};
770
+ this._storeOptionsAsProperties = false;
771
+ this._actionHandler = null;
772
+ this._executableHandler = false;
773
+ this._executableFile = null;
774
+ this._executableDir = null;
775
+ this._defaultCommandName = null;
776
+ this._exitCallback = null;
777
+ this._aliases = [];
778
+ this._combineFlagAndOptionalValue = true;
779
+ this._description = "";
780
+ this._summary = "";
781
+ this._argsDescription = undefined;
782
+ this._enablePositionalOptions = false;
783
+ this._passThroughOptions = false;
784
+ this._lifeCycleHooks = {};
785
+ this._showHelpAfterError = false;
786
+ this._showSuggestionAfterError = true;
787
+ this._savedState = null;
788
+ this._outputConfiguration = {
789
+ writeOut: (str) => process2.stdout.write(str),
790
+ writeErr: (str) => process2.stderr.write(str),
791
+ outputError: (str, write) => write(str),
792
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
793
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
794
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
795
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
796
+ stripColor: (str) => stripColor(str)
797
+ };
798
+ this._hidden = false;
799
+ this._helpOption = undefined;
800
+ this._addImplicitHelpCommand = undefined;
801
+ this._helpCommand = undefined;
802
+ this._helpConfiguration = {};
803
+ this._helpGroupHeading = undefined;
804
+ this._defaultCommandGroup = undefined;
805
+ this._defaultOptionGroup = undefined;
806
+ }
807
+ copyInheritedSettings(sourceCommand) {
808
+ this._outputConfiguration = sourceCommand._outputConfiguration;
809
+ this._helpOption = sourceCommand._helpOption;
810
+ this._helpCommand = sourceCommand._helpCommand;
811
+ this._helpConfiguration = sourceCommand._helpConfiguration;
812
+ this._exitCallback = sourceCommand._exitCallback;
813
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
814
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
815
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
816
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
817
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
818
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
819
+ return this;
820
+ }
821
+ _getCommandAndAncestors() {
822
+ const result = [];
823
+ for (let command = this;command; command = command.parent) {
824
+ result.push(command);
825
+ }
826
+ return result;
827
+ }
828
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
829
+ let desc = actionOptsOrExecDesc;
830
+ let opts = execOpts;
831
+ if (typeof desc === "object" && desc !== null) {
832
+ opts = desc;
833
+ desc = null;
834
+ }
835
+ opts = opts || {};
836
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
837
+ const cmd = this.createCommand(name);
838
+ if (desc) {
839
+ cmd.description(desc);
840
+ cmd._executableHandler = true;
841
+ }
842
+ if (opts.isDefault)
843
+ this._defaultCommandName = cmd._name;
844
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
845
+ cmd._executableFile = opts.executableFile || null;
846
+ if (args)
847
+ cmd.arguments(args);
848
+ this._registerCommand(cmd);
849
+ cmd.parent = this;
850
+ cmd.copyInheritedSettings(this);
851
+ if (desc)
852
+ return this;
853
+ return cmd;
854
+ }
855
+ createCommand(name) {
856
+ return new Command(name);
857
+ }
858
+ createHelp() {
859
+ return Object.assign(new Help, this.configureHelp());
860
+ }
861
+ configureHelp(configuration) {
862
+ if (configuration === undefined)
863
+ return this._helpConfiguration;
864
+ this._helpConfiguration = configuration;
865
+ return this;
866
+ }
867
+ configureOutput(configuration) {
868
+ if (configuration === undefined)
869
+ return this._outputConfiguration;
870
+ this._outputConfiguration = {
871
+ ...this._outputConfiguration,
872
+ ...configuration
873
+ };
874
+ return this;
875
+ }
876
+ showHelpAfterError(displayHelp = true) {
877
+ if (typeof displayHelp !== "string")
878
+ displayHelp = !!displayHelp;
879
+ this._showHelpAfterError = displayHelp;
880
+ return this;
881
+ }
882
+ showSuggestionAfterError(displaySuggestion = true) {
883
+ this._showSuggestionAfterError = !!displaySuggestion;
884
+ return this;
885
+ }
886
+ addCommand(cmd, opts) {
887
+ if (!cmd._name) {
888
+ throw new Error(`Command passed to .addCommand() must have a name
889
+ - specify the name in Command constructor or using .name()`);
890
+ }
891
+ opts = opts || {};
892
+ if (opts.isDefault)
893
+ this._defaultCommandName = cmd._name;
894
+ if (opts.noHelp || opts.hidden)
895
+ cmd._hidden = true;
896
+ this._registerCommand(cmd);
897
+ cmd.parent = this;
898
+ cmd._checkForBrokenPassThrough();
899
+ return this;
900
+ }
901
+ createArgument(name, description) {
902
+ return new Argument(name, description);
903
+ }
904
+ argument(name, description, parseArg, defaultValue) {
905
+ const argument = this.createArgument(name, description);
906
+ if (typeof parseArg === "function") {
907
+ argument.default(defaultValue).argParser(parseArg);
908
+ } else {
909
+ argument.default(parseArg);
910
+ }
911
+ this.addArgument(argument);
912
+ return this;
913
+ }
914
+ arguments(names) {
915
+ names.trim().split(/ +/).forEach((detail) => {
916
+ this.argument(detail);
917
+ });
918
+ return this;
919
+ }
920
+ addArgument(argument) {
921
+ const previousArgument = this.registeredArguments.slice(-1)[0];
922
+ if (previousArgument?.variadic) {
923
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
924
+ }
925
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
926
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
927
+ }
928
+ this.registeredArguments.push(argument);
929
+ return this;
930
+ }
931
+ helpCommand(enableOrNameAndArgs, description) {
932
+ if (typeof enableOrNameAndArgs === "boolean") {
933
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
934
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
935
+ this._initCommandGroup(this._getHelpCommand());
936
+ }
937
+ return this;
938
+ }
939
+ const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
940
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
941
+ const helpDescription = description ?? "display help for command";
942
+ const helpCommand = this.createCommand(helpName);
943
+ helpCommand.helpOption(false);
944
+ if (helpArgs)
945
+ helpCommand.arguments(helpArgs);
946
+ if (helpDescription)
947
+ helpCommand.description(helpDescription);
948
+ this._addImplicitHelpCommand = true;
949
+ this._helpCommand = helpCommand;
950
+ if (enableOrNameAndArgs || description)
951
+ this._initCommandGroup(helpCommand);
952
+ return this;
953
+ }
954
+ addHelpCommand(helpCommand, deprecatedDescription) {
955
+ if (typeof helpCommand !== "object") {
956
+ this.helpCommand(helpCommand, deprecatedDescription);
957
+ return this;
958
+ }
959
+ this._addImplicitHelpCommand = true;
960
+ this._helpCommand = helpCommand;
961
+ this._initCommandGroup(helpCommand);
962
+ return this;
963
+ }
964
+ _getHelpCommand() {
965
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
966
+ if (hasImplicitHelpCommand) {
967
+ if (this._helpCommand === undefined) {
968
+ this.helpCommand(undefined, undefined);
969
+ }
970
+ return this._helpCommand;
971
+ }
972
+ return null;
973
+ }
974
+ hook(event, listener) {
975
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
976
+ if (!allowedValues.includes(event)) {
977
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
978
+ Expecting one of '${allowedValues.join("', '")}'`);
979
+ }
980
+ if (this._lifeCycleHooks[event]) {
981
+ this._lifeCycleHooks[event].push(listener);
982
+ } else {
983
+ this._lifeCycleHooks[event] = [listener];
984
+ }
985
+ return this;
986
+ }
987
+ exitOverride(fn) {
988
+ if (fn) {
989
+ this._exitCallback = fn;
990
+ } else {
991
+ this._exitCallback = (err) => {
992
+ if (err.code !== "commander.executeSubCommandAsync") {
993
+ throw err;
994
+ }
995
+ };
996
+ }
997
+ return this;
998
+ }
999
+ _exit(exitCode, code, message) {
1000
+ if (this._exitCallback) {
1001
+ this._exitCallback(new CommanderError(exitCode, code, message));
1002
+ }
1003
+ process2.exit(exitCode);
1004
+ }
1005
+ action(fn) {
1006
+ const listener = (args) => {
1007
+ const expectedArgsCount = this.registeredArguments.length;
1008
+ const actionArgs = args.slice(0, expectedArgsCount);
1009
+ if (this._storeOptionsAsProperties) {
1010
+ actionArgs[expectedArgsCount] = this;
1011
+ } else {
1012
+ actionArgs[expectedArgsCount] = this.opts();
1013
+ }
1014
+ actionArgs.push(this);
1015
+ return fn.apply(this, actionArgs);
1016
+ };
1017
+ this._actionHandler = listener;
1018
+ return this;
1019
+ }
1020
+ createOption(flags, description) {
1021
+ return new Option(flags, description);
1022
+ }
1023
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1024
+ try {
1025
+ return target.parseArg(value, previous);
1026
+ } catch (err) {
1027
+ if (err.code === "commander.invalidArgument") {
1028
+ const message = `${invalidArgumentMessage} ${err.message}`;
1029
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1030
+ }
1031
+ throw err;
1032
+ }
1033
+ }
1034
+ _registerOption(option) {
1035
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1036
+ if (matchingOption) {
1037
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1038
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1039
+ - already used by option '${matchingOption.flags}'`);
1040
+ }
1041
+ this._initOptionGroup(option);
1042
+ this.options.push(option);
1043
+ }
1044
+ _registerCommand(command) {
1045
+ const knownBy = (cmd) => {
1046
+ return [cmd.name()].concat(cmd.aliases());
1047
+ };
1048
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1049
+ if (alreadyUsed) {
1050
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1051
+ const newCmd = knownBy(command).join("|");
1052
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1053
+ }
1054
+ this._initCommandGroup(command);
1055
+ this.commands.push(command);
1056
+ }
1057
+ addOption(option) {
1058
+ this._registerOption(option);
1059
+ const oname = option.name();
1060
+ const name = option.attributeName();
1061
+ if (option.negate) {
1062
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1063
+ if (!this._findOption(positiveLongFlag)) {
1064
+ this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
1065
+ }
1066
+ } else if (option.defaultValue !== undefined) {
1067
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1068
+ }
1069
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1070
+ if (val == null && option.presetArg !== undefined) {
1071
+ val = option.presetArg;
1072
+ }
1073
+ const oldValue = this.getOptionValue(name);
1074
+ if (val !== null && option.parseArg) {
1075
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1076
+ } else if (val !== null && option.variadic) {
1077
+ val = option._collectValue(val, oldValue);
1078
+ }
1079
+ if (val == null) {
1080
+ if (option.negate) {
1081
+ val = false;
1082
+ } else if (option.isBoolean() || option.optional) {
1083
+ val = true;
1084
+ } else {
1085
+ val = "";
1086
+ }
1087
+ }
1088
+ this.setOptionValueWithSource(name, val, valueSource);
1089
+ };
1090
+ this.on("option:" + oname, (val) => {
1091
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1092
+ handleOptionValue(val, invalidValueMessage, "cli");
1093
+ });
1094
+ if (option.envVar) {
1095
+ this.on("optionEnv:" + oname, (val) => {
1096
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1097
+ handleOptionValue(val, invalidValueMessage, "env");
1098
+ });
1099
+ }
1100
+ return this;
1101
+ }
1102
+ _optionEx(config, flags, description, fn, defaultValue) {
1103
+ if (typeof flags === "object" && flags instanceof Option) {
1104
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1105
+ }
1106
+ const option = this.createOption(flags, description);
1107
+ option.makeOptionMandatory(!!config.mandatory);
1108
+ if (typeof fn === "function") {
1109
+ option.default(defaultValue).argParser(fn);
1110
+ } else if (fn instanceof RegExp) {
1111
+ const regex = fn;
1112
+ fn = (val, def) => {
1113
+ const m = regex.exec(val);
1114
+ return m ? m[0] : def;
1115
+ };
1116
+ option.default(defaultValue).argParser(fn);
1117
+ } else {
1118
+ option.default(fn);
1119
+ }
1120
+ return this.addOption(option);
1121
+ }
1122
+ option(flags, description, parseArg, defaultValue) {
1123
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1124
+ }
1125
+ requiredOption(flags, description, parseArg, defaultValue) {
1126
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1127
+ }
1128
+ combineFlagAndOptionalValue(combine = true) {
1129
+ this._combineFlagAndOptionalValue = !!combine;
1130
+ return this;
1131
+ }
1132
+ allowUnknownOption(allowUnknown = true) {
1133
+ this._allowUnknownOption = !!allowUnknown;
1134
+ return this;
1135
+ }
1136
+ allowExcessArguments(allowExcess = true) {
1137
+ this._allowExcessArguments = !!allowExcess;
1138
+ return this;
1139
+ }
1140
+ enablePositionalOptions(positional = true) {
1141
+ this._enablePositionalOptions = !!positional;
1142
+ return this;
1143
+ }
1144
+ passThroughOptions(passThrough = true) {
1145
+ this._passThroughOptions = !!passThrough;
1146
+ this._checkForBrokenPassThrough();
1147
+ return this;
1148
+ }
1149
+ _checkForBrokenPassThrough() {
1150
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1151
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1152
+ }
1153
+ }
1154
+ storeOptionsAsProperties(storeAsProperties = true) {
1155
+ if (this.options.length) {
1156
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1157
+ }
1158
+ if (Object.keys(this._optionValues).length) {
1159
+ throw new Error("call .storeOptionsAsProperties() before setting option values");
1160
+ }
1161
+ this._storeOptionsAsProperties = !!storeAsProperties;
1162
+ return this;
1163
+ }
1164
+ getOptionValue(key) {
1165
+ if (this._storeOptionsAsProperties) {
1166
+ return this[key];
1167
+ }
1168
+ return this._optionValues[key];
1169
+ }
1170
+ setOptionValue(key, value) {
1171
+ return this.setOptionValueWithSource(key, value, undefined);
1172
+ }
1173
+ setOptionValueWithSource(key, value, source) {
1174
+ if (this._storeOptionsAsProperties) {
1175
+ this[key] = value;
1176
+ } else {
1177
+ this._optionValues[key] = value;
1178
+ }
1179
+ this._optionValueSources[key] = source;
1180
+ return this;
1181
+ }
1182
+ getOptionValueSource(key) {
1183
+ return this._optionValueSources[key];
1184
+ }
1185
+ getOptionValueSourceWithGlobals(key) {
1186
+ let source;
1187
+ this._getCommandAndAncestors().forEach((cmd) => {
1188
+ if (cmd.getOptionValueSource(key) !== undefined) {
1189
+ source = cmd.getOptionValueSource(key);
1190
+ }
1191
+ });
1192
+ return source;
1193
+ }
1194
+ _prepareUserArgs(argv, parseOptions) {
1195
+ if (argv !== undefined && !Array.isArray(argv)) {
1196
+ throw new Error("first parameter to parse must be array or undefined");
1197
+ }
1198
+ parseOptions = parseOptions || {};
1199
+ if (argv === undefined && parseOptions.from === undefined) {
1200
+ if (process2.versions?.electron) {
1201
+ parseOptions.from = "electron";
1202
+ }
1203
+ const execArgv = process2.execArgv ?? [];
1204
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1205
+ parseOptions.from = "eval";
1206
+ }
1207
+ }
1208
+ if (argv === undefined) {
1209
+ argv = process2.argv;
1210
+ }
1211
+ this.rawArgs = argv.slice();
1212
+ let userArgs;
1213
+ switch (parseOptions.from) {
1214
+ case undefined:
1215
+ case "node":
1216
+ this._scriptPath = argv[1];
1217
+ userArgs = argv.slice(2);
1218
+ break;
1219
+ case "electron":
1220
+ if (process2.defaultApp) {
1221
+ this._scriptPath = argv[1];
1222
+ userArgs = argv.slice(2);
1223
+ } else {
1224
+ userArgs = argv.slice(1);
1225
+ }
1226
+ break;
1227
+ case "user":
1228
+ userArgs = argv.slice(0);
1229
+ break;
1230
+ case "eval":
1231
+ userArgs = argv.slice(1);
1232
+ break;
1233
+ default:
1234
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1235
+ }
1236
+ if (!this._name && this._scriptPath)
1237
+ this.nameFromFilename(this._scriptPath);
1238
+ this._name = this._name || "program";
1239
+ return userArgs;
1240
+ }
1241
+ parse(argv, parseOptions) {
1242
+ this._prepareForParse();
1243
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1244
+ this._parseCommand([], userArgs);
1245
+ return this;
1246
+ }
1247
+ async parseAsync(argv, parseOptions) {
1248
+ this._prepareForParse();
1249
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1250
+ await this._parseCommand([], userArgs);
1251
+ return this;
1252
+ }
1253
+ _prepareForParse() {
1254
+ if (this._savedState === null) {
1255
+ this.saveStateBeforeParse();
1256
+ } else {
1257
+ this.restoreStateBeforeParse();
1258
+ }
1259
+ }
1260
+ saveStateBeforeParse() {
1261
+ this._savedState = {
1262
+ _name: this._name,
1263
+ _optionValues: { ...this._optionValues },
1264
+ _optionValueSources: { ...this._optionValueSources }
1265
+ };
1266
+ }
1267
+ restoreStateBeforeParse() {
1268
+ if (this._storeOptionsAsProperties)
1269
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1270
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1271
+ this._name = this._savedState._name;
1272
+ this._scriptPath = null;
1273
+ this.rawArgs = [];
1274
+ this._optionValues = { ...this._savedState._optionValues };
1275
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1276
+ this.args = [];
1277
+ this.processedArgs = [];
1278
+ }
1279
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1280
+ if (fs2.existsSync(executableFile))
1281
+ return;
1282
+ const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
1283
+ const executableMissing = `'${executableFile}' does not exist
1284
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1285
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1286
+ - ${executableDirMessage}`;
1287
+ throw new Error(executableMissing);
1288
+ }
1289
+ _executeSubCommand(subcommand, args) {
1290
+ args = args.slice();
1291
+ let launchWithNode = false;
1292
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1293
+ function findFile(baseDir, baseName) {
1294
+ const localBin = path2.resolve(baseDir, baseName);
1295
+ if (fs2.existsSync(localBin))
1296
+ return localBin;
1297
+ if (sourceExt.includes(path2.extname(baseName)))
1298
+ return;
1299
+ const foundExt = sourceExt.find((ext) => fs2.existsSync(`${localBin}${ext}`));
1300
+ if (foundExt)
1301
+ return `${localBin}${foundExt}`;
1302
+ return;
1303
+ }
1304
+ this._checkForMissingMandatoryOptions();
1305
+ this._checkForConflictingOptions();
1306
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1307
+ let executableDir = this._executableDir || "";
1308
+ if (this._scriptPath) {
1309
+ let resolvedScriptPath;
1310
+ try {
1311
+ resolvedScriptPath = fs2.realpathSync(this._scriptPath);
1312
+ } catch {
1313
+ resolvedScriptPath = this._scriptPath;
1314
+ }
1315
+ executableDir = path2.resolve(path2.dirname(resolvedScriptPath), executableDir);
1316
+ }
1317
+ if (executableDir) {
1318
+ let localFile = findFile(executableDir, executableFile);
1319
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1320
+ const legacyName = path2.basename(this._scriptPath, path2.extname(this._scriptPath));
1321
+ if (legacyName !== this._name) {
1322
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1323
+ }
1324
+ }
1325
+ executableFile = localFile || executableFile;
1326
+ }
1327
+ launchWithNode = sourceExt.includes(path2.extname(executableFile));
1328
+ let proc;
1329
+ if (process2.platform !== "win32") {
1330
+ if (launchWithNode) {
1331
+ args.unshift(executableFile);
1332
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1333
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1334
+ } else {
1335
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1336
+ }
1337
+ } else {
1338
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1339
+ args.unshift(executableFile);
1340
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1341
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1342
+ }
1343
+ if (!proc.killed) {
1344
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1345
+ signals.forEach((signal) => {
1346
+ process2.on(signal, () => {
1347
+ if (proc.killed === false && proc.exitCode === null) {
1348
+ proc.kill(signal);
1349
+ }
1350
+ });
1351
+ });
1352
+ }
1353
+ const exitCallback = this._exitCallback;
1354
+ proc.on("close", (code) => {
1355
+ code = code ?? 1;
1356
+ if (!exitCallback) {
1357
+ process2.exit(code);
1358
+ } else {
1359
+ exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1360
+ }
1361
+ });
1362
+ proc.on("error", (err) => {
1363
+ if (err.code === "ENOENT") {
1364
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1365
+ } else if (err.code === "EACCES") {
1366
+ throw new Error(`'${executableFile}' not executable`);
1367
+ }
1368
+ if (!exitCallback) {
1369
+ process2.exit(1);
1370
+ } else {
1371
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1372
+ wrappedError.nestedError = err;
1373
+ exitCallback(wrappedError);
1374
+ }
1375
+ });
1376
+ this.runningCommand = proc;
1377
+ }
1378
+ _dispatchSubcommand(commandName, operands, unknown) {
1379
+ const subCommand = this._findCommand(commandName);
1380
+ if (!subCommand)
1381
+ this.help({ error: true });
1382
+ subCommand._prepareForParse();
1383
+ let promiseChain;
1384
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1385
+ promiseChain = this._chainOrCall(promiseChain, () => {
1386
+ if (subCommand._executableHandler) {
1387
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1388
+ } else {
1389
+ return subCommand._parseCommand(operands, unknown);
1390
+ }
1391
+ });
1392
+ return promiseChain;
1393
+ }
1394
+ _dispatchHelpCommand(subcommandName) {
1395
+ if (!subcommandName) {
1396
+ this.help();
1397
+ }
1398
+ const subCommand = this._findCommand(subcommandName);
1399
+ if (subCommand && !subCommand._executableHandler) {
1400
+ subCommand.help();
1401
+ }
1402
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
1403
+ }
1404
+ _checkNumberOfArguments() {
1405
+ this.registeredArguments.forEach((arg, i) => {
1406
+ if (arg.required && this.args[i] == null) {
1407
+ this.missingArgument(arg.name());
1408
+ }
1409
+ });
1410
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1411
+ return;
1412
+ }
1413
+ if (this.args.length > this.registeredArguments.length) {
1414
+ this._excessArguments(this.args);
1415
+ }
1416
+ }
1417
+ _processArguments() {
1418
+ const myParseArg = (argument, value, previous) => {
1419
+ let parsedValue = value;
1420
+ if (value !== null && argument.parseArg) {
1421
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1422
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1423
+ }
1424
+ return parsedValue;
1425
+ };
1426
+ this._checkNumberOfArguments();
1427
+ const processedArgs = [];
1428
+ this.registeredArguments.forEach((declaredArg, index) => {
1429
+ let value = declaredArg.defaultValue;
1430
+ if (declaredArg.variadic) {
1431
+ if (index < this.args.length) {
1432
+ value = this.args.slice(index);
1433
+ if (declaredArg.parseArg) {
1434
+ value = value.reduce((processed, v) => {
1435
+ return myParseArg(declaredArg, v, processed);
1436
+ }, declaredArg.defaultValue);
1437
+ }
1438
+ } else if (value === undefined) {
1439
+ value = [];
1440
+ }
1441
+ } else if (index < this.args.length) {
1442
+ value = this.args[index];
1443
+ if (declaredArg.parseArg) {
1444
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1445
+ }
1446
+ }
1447
+ processedArgs[index] = value;
1448
+ });
1449
+ this.processedArgs = processedArgs;
1450
+ }
1451
+ _chainOrCall(promise, fn) {
1452
+ if (promise?.then && typeof promise.then === "function") {
1453
+ return promise.then(() => fn());
1454
+ }
1455
+ return fn();
1456
+ }
1457
+ _chainOrCallHooks(promise, event) {
1458
+ let result = promise;
1459
+ const hooks = [];
1460
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
1461
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1462
+ hooks.push({ hookedCommand, callback });
1463
+ });
1464
+ });
1465
+ if (event === "postAction") {
1466
+ hooks.reverse();
1467
+ }
1468
+ hooks.forEach((hookDetail) => {
1469
+ result = this._chainOrCall(result, () => {
1470
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1471
+ });
1472
+ });
1473
+ return result;
1474
+ }
1475
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1476
+ let result = promise;
1477
+ if (this._lifeCycleHooks[event] !== undefined) {
1478
+ this._lifeCycleHooks[event].forEach((hook) => {
1479
+ result = this._chainOrCall(result, () => {
1480
+ return hook(this, subCommand);
1481
+ });
1482
+ });
1483
+ }
1484
+ return result;
1485
+ }
1486
+ _parseCommand(operands, unknown) {
1487
+ const parsed = this.parseOptions(unknown);
1488
+ this._parseOptionsEnv();
1489
+ this._parseOptionsImplied();
1490
+ operands = operands.concat(parsed.operands);
1491
+ unknown = parsed.unknown;
1492
+ this.args = operands.concat(unknown);
1493
+ if (operands && this._findCommand(operands[0])) {
1494
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1495
+ }
1496
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
1497
+ return this._dispatchHelpCommand(operands[1]);
1498
+ }
1499
+ if (this._defaultCommandName) {
1500
+ this._outputHelpIfRequested(unknown);
1501
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1502
+ }
1503
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1504
+ this.help({ error: true });
1505
+ }
1506
+ this._outputHelpIfRequested(parsed.unknown);
1507
+ this._checkForMissingMandatoryOptions();
1508
+ this._checkForConflictingOptions();
1509
+ const checkForUnknownOptions = () => {
1510
+ if (parsed.unknown.length > 0) {
1511
+ this.unknownOption(parsed.unknown[0]);
1512
+ }
1513
+ };
1514
+ const commandEvent = `command:${this.name()}`;
1515
+ if (this._actionHandler) {
1516
+ checkForUnknownOptions();
1517
+ this._processArguments();
1518
+ let promiseChain;
1519
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
1520
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
1521
+ if (this.parent) {
1522
+ promiseChain = this._chainOrCall(promiseChain, () => {
1523
+ this.parent.emit(commandEvent, operands, unknown);
1524
+ });
1525
+ }
1526
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
1527
+ return promiseChain;
1528
+ }
1529
+ if (this.parent?.listenerCount(commandEvent)) {
1530
+ checkForUnknownOptions();
1531
+ this._processArguments();
1532
+ this.parent.emit(commandEvent, operands, unknown);
1533
+ } else if (operands.length) {
1534
+ if (this._findCommand("*")) {
1535
+ return this._dispatchSubcommand("*", operands, unknown);
1536
+ }
1537
+ if (this.listenerCount("command:*")) {
1538
+ this.emit("command:*", operands, unknown);
1539
+ } else if (this.commands.length) {
1540
+ this.unknownCommand();
1541
+ } else {
1542
+ checkForUnknownOptions();
1543
+ this._processArguments();
1544
+ }
1545
+ } else if (this.commands.length) {
1546
+ checkForUnknownOptions();
1547
+ this.help({ error: true });
1548
+ } else {
1549
+ checkForUnknownOptions();
1550
+ this._processArguments();
1551
+ }
1552
+ }
1553
+ _findCommand(name) {
1554
+ if (!name)
1555
+ return;
1556
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
1557
+ }
1558
+ _findOption(arg) {
1559
+ return this.options.find((option) => option.is(arg));
1560
+ }
1561
+ _checkForMissingMandatoryOptions() {
1562
+ this._getCommandAndAncestors().forEach((cmd) => {
1563
+ cmd.options.forEach((anOption) => {
1564
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
1565
+ cmd.missingMandatoryOptionValue(anOption);
1566
+ }
1567
+ });
1568
+ });
1569
+ }
1570
+ _checkForConflictingLocalOptions() {
1571
+ const definedNonDefaultOptions = this.options.filter((option) => {
1572
+ const optionKey = option.attributeName();
1573
+ if (this.getOptionValue(optionKey) === undefined) {
1574
+ return false;
1575
+ }
1576
+ return this.getOptionValueSource(optionKey) !== "default";
1577
+ });
1578
+ const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
1579
+ optionsWithConflicting.forEach((option) => {
1580
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
1581
+ if (conflictingAndDefined) {
1582
+ this._conflictingOption(option, conflictingAndDefined);
1583
+ }
1584
+ });
1585
+ }
1586
+ _checkForConflictingOptions() {
1587
+ this._getCommandAndAncestors().forEach((cmd) => {
1588
+ cmd._checkForConflictingLocalOptions();
1589
+ });
1590
+ }
1591
+ parseOptions(args) {
1592
+ const operands = [];
1593
+ const unknown = [];
1594
+ let dest = operands;
1595
+ function maybeOption(arg) {
1596
+ return arg.length > 1 && arg[0] === "-";
1597
+ }
1598
+ const negativeNumberArg = (arg) => {
1599
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg))
1600
+ return false;
1601
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
1602
+ };
1603
+ let activeVariadicOption = null;
1604
+ let activeGroup = null;
1605
+ let i = 0;
1606
+ while (i < args.length || activeGroup) {
1607
+ const arg = activeGroup ?? args[i++];
1608
+ activeGroup = null;
1609
+ if (arg === "--") {
1610
+ if (dest === unknown)
1611
+ dest.push(arg);
1612
+ dest.push(...args.slice(i));
1613
+ break;
1614
+ }
1615
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
1616
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1617
+ continue;
1618
+ }
1619
+ activeVariadicOption = null;
1620
+ if (maybeOption(arg)) {
1621
+ const option = this._findOption(arg);
1622
+ if (option) {
1623
+ if (option.required) {
1624
+ const value = args[i++];
1625
+ if (value === undefined)
1626
+ this.optionMissingArgument(option);
1627
+ this.emit(`option:${option.name()}`, value);
1628
+ } else if (option.optional) {
1629
+ let value = null;
1630
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
1631
+ value = args[i++];
1632
+ }
1633
+ this.emit(`option:${option.name()}`, value);
1634
+ } else {
1635
+ this.emit(`option:${option.name()}`);
1636
+ }
1637
+ activeVariadicOption = option.variadic ? option : null;
1638
+ continue;
1639
+ }
1640
+ }
1641
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
1642
+ const option = this._findOption(`-${arg[1]}`);
1643
+ if (option) {
1644
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
1645
+ this.emit(`option:${option.name()}`, arg.slice(2));
1646
+ } else {
1647
+ this.emit(`option:${option.name()}`);
1648
+ activeGroup = `-${arg.slice(2)}`;
1649
+ }
1650
+ continue;
1651
+ }
1652
+ }
1653
+ if (/^--[^=]+=/.test(arg)) {
1654
+ const index = arg.indexOf("=");
1655
+ const option = this._findOption(arg.slice(0, index));
1656
+ if (option && (option.required || option.optional)) {
1657
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1658
+ continue;
1659
+ }
1660
+ }
1661
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
1662
+ dest = unknown;
1663
+ }
1664
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
1665
+ if (this._findCommand(arg)) {
1666
+ operands.push(arg);
1667
+ unknown.push(...args.slice(i));
1668
+ break;
1669
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
1670
+ operands.push(arg, ...args.slice(i));
1671
+ break;
1672
+ } else if (this._defaultCommandName) {
1673
+ unknown.push(arg, ...args.slice(i));
1674
+ break;
1675
+ }
1676
+ }
1677
+ if (this._passThroughOptions) {
1678
+ dest.push(arg, ...args.slice(i));
1679
+ break;
1680
+ }
1681
+ dest.push(arg);
1682
+ }
1683
+ return { operands, unknown };
1684
+ }
1685
+ opts() {
1686
+ if (this._storeOptionsAsProperties) {
1687
+ const result = {};
1688
+ const len = this.options.length;
1689
+ for (let i = 0;i < len; i++) {
1690
+ const key = this.options[i].attributeName();
1691
+ result[key] = key === this._versionOptionName ? this._version : this[key];
1692
+ }
1693
+ return result;
1694
+ }
1695
+ return this._optionValues;
1696
+ }
1697
+ optsWithGlobals() {
1698
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
1699
+ }
1700
+ error(message, errorOptions) {
1701
+ this._outputConfiguration.outputError(`${message}
1702
+ `, this._outputConfiguration.writeErr);
1703
+ if (typeof this._showHelpAfterError === "string") {
1704
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
1705
+ `);
1706
+ } else if (this._showHelpAfterError) {
1707
+ this._outputConfiguration.writeErr(`
1708
+ `);
1709
+ this.outputHelp({ error: true });
1710
+ }
1711
+ const config = errorOptions || {};
1712
+ const exitCode = config.exitCode || 1;
1713
+ const code = config.code || "commander.error";
1714
+ this._exit(exitCode, code, message);
1715
+ }
1716
+ _parseOptionsEnv() {
1717
+ this.options.forEach((option) => {
1718
+ if (option.envVar && option.envVar in process2.env) {
1719
+ const optionKey = option.attributeName();
1720
+ if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
1721
+ if (option.required || option.optional) {
1722
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
1723
+ } else {
1724
+ this.emit(`optionEnv:${option.name()}`);
1725
+ }
1726
+ }
1727
+ }
1728
+ });
1729
+ }
1730
+ _parseOptionsImplied() {
1731
+ const dualHelper = new DualOptions(this.options);
1732
+ const hasCustomOptionValue = (optionKey) => {
1733
+ return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
1734
+ };
1735
+ this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
1736
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
1737
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
1738
+ });
1739
+ });
1740
+ }
1741
+ missingArgument(name) {
1742
+ const message = `error: missing required argument '${name}'`;
1743
+ this.error(message, { code: "commander.missingArgument" });
1744
+ }
1745
+ optionMissingArgument(option) {
1746
+ const message = `error: option '${option.flags}' argument missing`;
1747
+ this.error(message, { code: "commander.optionMissingArgument" });
1748
+ }
1749
+ missingMandatoryOptionValue(option) {
1750
+ const message = `error: required option '${option.flags}' not specified`;
1751
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
1752
+ }
1753
+ _conflictingOption(option, conflictingOption) {
1754
+ const findBestOptionFromValue = (option2) => {
1755
+ const optionKey = option2.attributeName();
1756
+ const optionValue = this.getOptionValue(optionKey);
1757
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1758
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1759
+ if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1760
+ return negativeOption;
1761
+ }
1762
+ return positiveOption || option2;
1763
+ };
1764
+ const getErrorMessage = (option2) => {
1765
+ const bestOption = findBestOptionFromValue(option2);
1766
+ const optionKey = bestOption.attributeName();
1767
+ const source = this.getOptionValueSource(optionKey);
1768
+ if (source === "env") {
1769
+ return `environment variable '${bestOption.envVar}'`;
1770
+ }
1771
+ return `option '${bestOption.flags}'`;
1772
+ };
1773
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
1774
+ this.error(message, { code: "commander.conflictingOption" });
1775
+ }
1776
+ unknownOption(flag) {
1777
+ if (this._allowUnknownOption)
1778
+ return;
1779
+ let suggestion = "";
1780
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
1781
+ let candidateFlags = [];
1782
+ let command = this;
1783
+ do {
1784
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
1785
+ candidateFlags = candidateFlags.concat(moreFlags);
1786
+ command = command.parent;
1787
+ } while (command && !command._enablePositionalOptions);
1788
+ suggestion = suggestSimilar(flag, candidateFlags);
1789
+ }
1790
+ const message = `error: unknown option '${flag}'${suggestion}`;
1791
+ this.error(message, { code: "commander.unknownOption" });
1792
+ }
1793
+ _excessArguments(receivedArgs) {
1794
+ if (this._allowExcessArguments)
1795
+ return;
1796
+ const expected = this.registeredArguments.length;
1797
+ const s = expected === 1 ? "" : "s";
1798
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
1799
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
1800
+ this.error(message, { code: "commander.excessArguments" });
1801
+ }
1802
+ unknownCommand() {
1803
+ const unknownName = this.args[0];
1804
+ let suggestion = "";
1805
+ if (this._showSuggestionAfterError) {
1806
+ const candidateNames = [];
1807
+ this.createHelp().visibleCommands(this).forEach((command) => {
1808
+ candidateNames.push(command.name());
1809
+ if (command.alias())
1810
+ candidateNames.push(command.alias());
1811
+ });
1812
+ suggestion = suggestSimilar(unknownName, candidateNames);
1813
+ }
1814
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
1815
+ this.error(message, { code: "commander.unknownCommand" });
1816
+ }
1817
+ version(str, flags, description) {
1818
+ if (str === undefined)
1819
+ return this._version;
1820
+ this._version = str;
1821
+ flags = flags || "-V, --version";
1822
+ description = description || "output the version number";
1823
+ const versionOption = this.createOption(flags, description);
1824
+ this._versionOptionName = versionOption.attributeName();
1825
+ this._registerOption(versionOption);
1826
+ this.on("option:" + versionOption.name(), () => {
1827
+ this._outputConfiguration.writeOut(`${str}
1828
+ `);
1829
+ this._exit(0, "commander.version", str);
1830
+ });
1831
+ return this;
1832
+ }
1833
+ description(str, argsDescription) {
1834
+ if (str === undefined && argsDescription === undefined)
1835
+ return this._description;
1836
+ this._description = str;
1837
+ if (argsDescription) {
1838
+ this._argsDescription = argsDescription;
1839
+ }
1840
+ return this;
1841
+ }
1842
+ summary(str) {
1843
+ if (str === undefined)
1844
+ return this._summary;
1845
+ this._summary = str;
1846
+ return this;
1847
+ }
1848
+ alias(alias) {
1849
+ if (alias === undefined)
1850
+ return this._aliases[0];
1851
+ let command = this;
1852
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
1853
+ command = this.commands[this.commands.length - 1];
1854
+ }
1855
+ if (alias === command._name)
1856
+ throw new Error("Command alias can't be the same as its name");
1857
+ const matchingCommand = this.parent?._findCommand(alias);
1858
+ if (matchingCommand) {
1859
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
1860
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
1861
+ }
1862
+ command._aliases.push(alias);
1863
+ return this;
1864
+ }
1865
+ aliases(aliases) {
1866
+ if (aliases === undefined)
1867
+ return this._aliases;
1868
+ aliases.forEach((alias) => this.alias(alias));
1869
+ return this;
1870
+ }
1871
+ usage(str) {
1872
+ if (str === undefined) {
1873
+ if (this._usage)
1874
+ return this._usage;
1875
+ const args = this.registeredArguments.map((arg) => {
1876
+ return humanReadableArgName(arg);
1877
+ });
1878
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
1879
+ }
1880
+ this._usage = str;
1881
+ return this;
1882
+ }
1883
+ name(str) {
1884
+ if (str === undefined)
1885
+ return this._name;
1886
+ this._name = str;
1887
+ return this;
1888
+ }
1889
+ helpGroup(heading) {
1890
+ if (heading === undefined)
1891
+ return this._helpGroupHeading ?? "";
1892
+ this._helpGroupHeading = heading;
1893
+ return this;
1894
+ }
1895
+ commandsGroup(heading) {
1896
+ if (heading === undefined)
1897
+ return this._defaultCommandGroup ?? "";
1898
+ this._defaultCommandGroup = heading;
1899
+ return this;
1900
+ }
1901
+ optionsGroup(heading) {
1902
+ if (heading === undefined)
1903
+ return this._defaultOptionGroup ?? "";
1904
+ this._defaultOptionGroup = heading;
1905
+ return this;
1906
+ }
1907
+ _initOptionGroup(option) {
1908
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
1909
+ option.helpGroup(this._defaultOptionGroup);
1910
+ }
1911
+ _initCommandGroup(cmd) {
1912
+ if (this._defaultCommandGroup && !cmd.helpGroup())
1913
+ cmd.helpGroup(this._defaultCommandGroup);
1914
+ }
1915
+ nameFromFilename(filename) {
1916
+ this._name = path2.basename(filename, path2.extname(filename));
1917
+ return this;
1918
+ }
1919
+ executableDir(path3) {
1920
+ if (path3 === undefined)
1921
+ return this._executableDir;
1922
+ this._executableDir = path3;
1923
+ return this;
1924
+ }
1925
+ helpInformation(contextOptions) {
1926
+ const helper = this.createHelp();
1927
+ const context = this._getOutputContext(contextOptions);
1928
+ helper.prepareContext({
1929
+ error: context.error,
1930
+ helpWidth: context.helpWidth,
1931
+ outputHasColors: context.hasColors
1932
+ });
1933
+ const text = helper.formatHelp(this, helper);
1934
+ if (context.hasColors)
1935
+ return text;
1936
+ return this._outputConfiguration.stripColor(text);
1937
+ }
1938
+ _getOutputContext(contextOptions) {
1939
+ contextOptions = contextOptions || {};
1940
+ const error = !!contextOptions.error;
1941
+ let baseWrite;
1942
+ let hasColors;
1943
+ let helpWidth;
1944
+ if (error) {
1945
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
1946
+ hasColors = this._outputConfiguration.getErrHasColors();
1947
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
1948
+ } else {
1949
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
1950
+ hasColors = this._outputConfiguration.getOutHasColors();
1951
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
1952
+ }
1953
+ const write = (str) => {
1954
+ if (!hasColors)
1955
+ str = this._outputConfiguration.stripColor(str);
1956
+ return baseWrite(str);
1957
+ };
1958
+ return { error, write, hasColors, helpWidth };
1959
+ }
1960
+ outputHelp(contextOptions) {
1961
+ let deprecatedCallback;
1962
+ if (typeof contextOptions === "function") {
1963
+ deprecatedCallback = contextOptions;
1964
+ contextOptions = undefined;
1965
+ }
1966
+ const outputContext = this._getOutputContext(contextOptions);
1967
+ const eventContext = {
1968
+ error: outputContext.error,
1969
+ write: outputContext.write,
1970
+ command: this
1971
+ };
1972
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
1973
+ this.emit("beforeHelp", eventContext);
1974
+ let helpInformation = this.helpInformation({ error: outputContext.error });
1975
+ if (deprecatedCallback) {
1976
+ helpInformation = deprecatedCallback(helpInformation);
1977
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
1978
+ throw new Error("outputHelp callback must return a string or a Buffer");
1979
+ }
1980
+ }
1981
+ outputContext.write(helpInformation);
1982
+ if (this._getHelpOption()?.long) {
1983
+ this.emit(this._getHelpOption().long);
1984
+ }
1985
+ this.emit("afterHelp", eventContext);
1986
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
1987
+ }
1988
+ helpOption(flags, description) {
1989
+ if (typeof flags === "boolean") {
1990
+ if (flags) {
1991
+ if (this._helpOption === null)
1992
+ this._helpOption = undefined;
1993
+ if (this._defaultOptionGroup) {
1994
+ this._initOptionGroup(this._getHelpOption());
1995
+ }
1996
+ } else {
1997
+ this._helpOption = null;
1998
+ }
1999
+ return this;
2000
+ }
2001
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
2002
+ if (flags || description)
2003
+ this._initOptionGroup(this._helpOption);
2004
+ return this;
2005
+ }
2006
+ _getHelpOption() {
2007
+ if (this._helpOption === undefined) {
2008
+ this.helpOption(undefined, undefined);
2009
+ }
2010
+ return this._helpOption;
2011
+ }
2012
+ addHelpOption(option) {
2013
+ this._helpOption = option;
2014
+ this._initOptionGroup(option);
2015
+ return this;
2016
+ }
2017
+ help(contextOptions) {
2018
+ this.outputHelp(contextOptions);
2019
+ let exitCode = Number(process2.exitCode ?? 0);
2020
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2021
+ exitCode = 1;
2022
+ }
2023
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2024
+ }
2025
+ addHelpText(position, text) {
2026
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2027
+ if (!allowedValues.includes(position)) {
2028
+ throw new Error(`Unexpected value for position to addHelpText.
2029
+ Expecting one of '${allowedValues.join("', '")}'`);
2030
+ }
2031
+ const helpEvent = `${position}Help`;
2032
+ this.on(helpEvent, (context) => {
2033
+ let helpStr;
2034
+ if (typeof text === "function") {
2035
+ helpStr = text({ error: context.error, command: context.command });
2036
+ } else {
2037
+ helpStr = text;
2038
+ }
2039
+ if (helpStr) {
2040
+ context.write(`${helpStr}
2041
+ `);
2042
+ }
2043
+ });
2044
+ return this;
2045
+ }
2046
+ _outputHelpIfRequested(args) {
2047
+ const helpOption = this._getHelpOption();
2048
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2049
+ if (helpRequested) {
2050
+ this.outputHelp();
2051
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2052
+ }
2053
+ }
2054
+ }
2055
+ function incrementNodeInspectorPort(args) {
2056
+ return args.map((arg) => {
2057
+ if (!arg.startsWith("--inspect")) {
2058
+ return arg;
2059
+ }
2060
+ let debugOption;
2061
+ let debugHost = "127.0.0.1";
2062
+ let debugPort = "9229";
2063
+ let match;
2064
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2065
+ debugOption = match[1];
2066
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2067
+ debugOption = match[1];
2068
+ if (/^\d+$/.test(match[3])) {
2069
+ debugPort = match[3];
2070
+ } else {
2071
+ debugHost = match[3];
2072
+ }
2073
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2074
+ debugOption = match[1];
2075
+ debugHost = match[3];
2076
+ debugPort = match[4];
2077
+ }
2078
+ if (debugOption && debugPort !== "0") {
2079
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2080
+ }
2081
+ return arg;
2082
+ });
2083
+ }
2084
+ function useColor() {
2085
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
2086
+ return false;
2087
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== undefined)
2088
+ return true;
2089
+ return;
2090
+ }
2091
+ exports.Command = Command;
2092
+ exports.useColor = useColor;
2093
+ });
2094
+
2095
+ // ../../node_modules/commander/index.js
2096
+ var require_commander = __commonJS(function(exports) {
2097
+ var { Argument } = require_argument();
2098
+ var { Command } = require_command();
2099
+ var { CommanderError, InvalidArgumentError } = require_error();
2100
+ var { Help } = require_help();
2101
+ var { Option } = require_option();
2102
+ exports.program = new Command;
2103
+ exports.createCommand = (name) => new Command(name);
2104
+ exports.createOption = (flags, description) => new Option(flags, description);
2105
+ exports.createArgument = (name, description) => new Argument(name, description);
2106
+ exports.Command = Command;
2107
+ exports.Option = Option;
2108
+ exports.Argument = Argument;
2109
+ exports.Help = Help;
2110
+ exports.CommanderError = CommanderError;
2111
+ exports.InvalidArgumentError = InvalidArgumentError;
2112
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
2113
+ });
2114
+
2115
+ // ../filesystem/src/node.ts
2116
+ import { randomUUID } from "node:crypto";
2117
+ import { existsSync } from "node:fs";
2118
+ import * as fs from "node:fs/promises";
2119
+ import * as os from "node:os";
2120
+ import * as path from "node:path";
2121
+ var LOCK_HEARTBEAT_MS = 5000;
2122
+ var LOCK_STALE_MS = 15000;
2123
+ var LOCK_MAX_WAIT_MS = 20000;
2124
+ var LOCK_MAX_HOLD_MS = 60000;
2125
+ var LOCK_RETRY_MIN_MS = 100;
2126
+ var LOCK_RETRY_JITTER_MS = 200;
2127
+
2128
+ class NodeFileSystem {
2129
+ path = {
2130
+ join: path.join,
2131
+ resolve: path.resolve,
2132
+ relative: path.relative,
2133
+ dirname: path.dirname,
2134
+ isAbsolute: path.isAbsolute,
2135
+ basename: path.basename
2136
+ };
2137
+ env = {
2138
+ cwd: process.cwd,
2139
+ homedir: os.homedir,
2140
+ tmpdir: os.tmpdir,
2141
+ getenv: (key) => process.env[key]
2142
+ };
2143
+ utils = {
2144
+ open: async (url) => {
2145
+ const { default: open } = await import("./index-sby22td6.js");
2146
+ await open(url);
2147
+ }
2148
+ };
2149
+ async readFile(path2, options) {
2150
+ try {
2151
+ if (options) {
2152
+ return await fs.readFile(path2, "utf-8");
2153
+ }
2154
+ return await fs.readFile(path2);
2155
+ } catch (error) {
2156
+ if (this.isEnoent(error))
2157
+ return null;
2158
+ throw error;
2159
+ }
2160
+ }
2161
+ async writeFile(filePath, data) {
2162
+ const dir = path.dirname(filePath);
2163
+ if (dir) {
2164
+ await fs.mkdir(dir, { recursive: true });
2165
+ }
2166
+ await fs.writeFile(filePath, data);
2167
+ }
2168
+ async appendFile(filePath, data) {
2169
+ const dir = path.dirname(filePath);
2170
+ if (dir) {
2171
+ await fs.mkdir(dir, { recursive: true });
2172
+ }
2173
+ await fs.appendFile(filePath, data);
2174
+ }
2175
+ async readdir(dirPath) {
2176
+ try {
2177
+ return await fs.readdir(dirPath);
2178
+ } catch (error) {
2179
+ if (this.isEnoent(error))
2180
+ return [];
2181
+ throw error;
2182
+ }
2183
+ }
2184
+ async stat(filePath) {
2185
+ try {
2186
+ const stats = await fs.stat(filePath);
2187
+ return {
2188
+ isFile: () => stats.isFile(),
2189
+ isDirectory: () => stats.isDirectory(),
2190
+ size: stats.size,
2191
+ mtimeMs: stats.mtimeMs
2192
+ };
2193
+ } catch (error) {
2194
+ if (this.isEnoent(error))
2195
+ return null;
2196
+ throw error;
2197
+ }
2198
+ }
2199
+ async exists(filePath) {
2200
+ return existsSync(filePath);
2201
+ }
2202
+ async mkdir(dirPath) {
2203
+ await fs.mkdir(dirPath, { recursive: true });
2204
+ }
2205
+ async acquireLock(lockPath) {
2206
+ const canonicalPath = await this.canonicalizeLockTarget(lockPath);
2207
+ const lockFile = `${canonicalPath}.lock`;
2208
+ const ownerId = randomUUID();
2209
+ const start = Date.now();
2210
+ while (true) {
2211
+ try {
2212
+ await fs.writeFile(lockFile, ownerId, { flag: "wx" });
2213
+ return this.createLockRelease(lockFile, ownerId);
2214
+ } catch (error) {
2215
+ if (!this.hasErrnoCode(error, "EEXIST")) {
2216
+ throw error;
2217
+ }
2218
+ const stats = await fs.stat(lockFile).catch(() => null);
2219
+ if (stats && Date.now() - stats.mtimeMs > LOCK_STALE_MS) {
2220
+ const reclaimed = await fs.rm(lockFile, { force: true }).then(() => true).catch(() => false);
2221
+ if (reclaimed)
2222
+ continue;
2223
+ }
2224
+ if (Date.now() - start > LOCK_MAX_WAIT_MS) {
2225
+ throw new Error(`ELOCKED: timed out waiting for lock on ${canonicalPath}`);
2226
+ }
2227
+ await new Promise((resolve2) => setTimeout(resolve2, LOCK_RETRY_MIN_MS + Math.random() * LOCK_RETRY_JITTER_MS));
2228
+ }
2229
+ }
2230
+ }
2231
+ async canonicalizeLockTarget(lockPath) {
2232
+ const absolute = path.resolve(lockPath);
2233
+ const fullReal = await fs.realpath(absolute).catch(() => null);
2234
+ if (fullReal)
2235
+ return fullReal;
2236
+ const parent = path.dirname(absolute);
2237
+ const base = path.basename(absolute);
2238
+ const canonicalParent = await fs.realpath(parent).catch(() => parent);
2239
+ return path.join(canonicalParent, base);
2240
+ }
2241
+ createLockRelease(lockFile, ownerId) {
2242
+ const heartbeatStart = Date.now();
2243
+ let heartbeatTimer;
2244
+ let stopped = false;
2245
+ const stopHeartbeat = () => {
2246
+ stopped = true;
2247
+ if (heartbeatTimer)
2248
+ clearTimeout(heartbeatTimer);
2249
+ };
2250
+ const scheduleNextHeartbeat = () => {
2251
+ if (stopped)
2252
+ return;
2253
+ if (Date.now() - heartbeatStart >= LOCK_MAX_HOLD_MS) {
2254
+ stopped = true;
2255
+ return;
2256
+ }
2257
+ heartbeatTimer = setTimeout(() => {
2258
+ runHeartbeat();
2259
+ }, LOCK_HEARTBEAT_MS);
2260
+ heartbeatTimer.unref?.();
2261
+ };
2262
+ const runHeartbeat = async () => {
2263
+ if (stopped)
2264
+ return;
2265
+ const current = await fs.readFile(lockFile, "utf-8").catch(() => null);
2266
+ if (stopped)
2267
+ return;
2268
+ if (current !== ownerId) {
2269
+ stopped = true;
2270
+ return;
2271
+ }
2272
+ const now = Date.now() / 1000;
2273
+ await fs.utimes(lockFile, now, now).catch(() => {});
2274
+ scheduleNextHeartbeat();
2275
+ };
2276
+ scheduleNextHeartbeat();
2277
+ let released = false;
2278
+ return async () => {
2279
+ if (released)
2280
+ return;
2281
+ released = true;
2282
+ stopHeartbeat();
2283
+ const current = await fs.readFile(lockFile, "utf-8").catch(() => null);
2284
+ if (current === ownerId) {
2285
+ await fs.rm(lockFile, { force: true });
2286
+ }
2287
+ };
2288
+ }
2289
+ async rm(filePath) {
2290
+ await fs.rm(filePath, { recursive: true, force: true });
2291
+ }
2292
+ async rename(oldPath, newPath) {
2293
+ await fs.rename(oldPath, newPath);
2294
+ }
2295
+ async realpath(filePath) {
2296
+ try {
2297
+ return await fs.realpath(filePath);
2298
+ } catch (error) {
2299
+ if (this.isEnoent(error))
2300
+ return filePath;
2301
+ throw error;
2302
+ }
2303
+ }
2304
+ async getTempDir() {
2305
+ return await fs.mkdtemp(path.join(os.tmpdir(), "uipath-fs-"));
2306
+ }
2307
+ async copyDirectory(sourcePath, destPath) {
2308
+ const sourceStats = await this.stat(sourcePath);
2309
+ if (!sourceStats) {
2310
+ throw new Error(`Source directory does not exist: ${sourcePath}`);
2311
+ }
2312
+ if (!sourceStats.isDirectory()) {
2313
+ throw new Error(`Source path is not a directory: ${sourcePath}`);
2314
+ }
2315
+ await this.mkdir(destPath);
2316
+ const entries = await this.readdir(sourcePath);
2317
+ for (const entry of entries) {
2318
+ const srcEntry = path.join(sourcePath, entry);
2319
+ const destEntry = path.join(destPath, entry);
2320
+ const entryStats = await this.stat(srcEntry);
2321
+ if (!entryStats)
2322
+ continue;
2323
+ if (entryStats.isDirectory()) {
2324
+ await this.copyDirectory(srcEntry, destEntry);
2325
+ } else if (entryStats.isFile()) {
2326
+ const content = await this.readFile(srcEntry);
2327
+ if (content !== null) {
2328
+ await this.writeFile(destEntry, content);
2329
+ }
2330
+ }
2331
+ }
2332
+ }
2333
+ isEnoent(error) {
2334
+ return this.hasErrnoCode(error, "ENOENT");
2335
+ }
2336
+ hasErrnoCode(error, code) {
2337
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
2338
+ }
2339
+ }
2340
+
2341
+ // ../filesystem/src/index.ts
2342
+ var fsInstance = new NodeFileSystem;
2343
+ var getFileSystem = () => fsInstance;
2344
+
2345
+ // ../common/src/output-context.ts
2346
+ function createStorage() {
2347
+ const [error, mod] = catchError(() => __require("node:async_hooks"));
2348
+ if (error || typeof mod?.AsyncLocalStorage !== "function") {
2349
+ return {
2350
+ getStore: () => {
2351
+ return;
2352
+ },
2353
+ run: (_store, fn) => fn()
2354
+ };
2355
+ }
2356
+ return new mod.AsyncLocalStorage;
2357
+ }
2358
+ var storageSingleton = singleton("OutputStorage");
2359
+ var sinkSlot = singleton("OutputSink");
2360
+ var outputStorage = storageSingleton.getOrInit(createStorage, (v) => ("getStore" in v));
2361
+ var CONSOLE_FALLBACK = {
2362
+ writeOut: (str) => process.stdout.write(str),
2363
+ writeErr: (str) => process.stderr.write(str),
2364
+ writeLog: (str) => process.stdout.write(str),
2365
+ capabilities: {
2366
+ isInteractive: false,
2367
+ canReadInput: false,
2368
+ supportsColor: false,
2369
+ outputWidth: 80
2370
+ }
2371
+ };
2372
+ function getOutputSink() {
2373
+ return outputStorage.getStore() ?? sinkSlot.get() ?? CONSOLE_FALLBACK;
2374
+ }
2375
+
2376
+ // ../common/src/logger.ts
2377
+ var logFilePathSlot = singleton("logFilePath");
2378
+ function setGlobalLogFilePath(path2) {
2379
+ logFilePathSlot.set(path2);
2380
+ }
2381
+ function getGlobalLogFilePath() {
2382
+ return logFilePathSlot.get("");
2383
+ }
2384
+ var DEFAULT_LOG_LEVEL = 3 /* ERROR */;
2385
+
2386
+ class SimpleLogger {
2387
+ __brand = "SimpleLogger";
2388
+ level;
2389
+ logFilePath;
2390
+ fileLoggingEnabled;
2391
+ pendingWrites = Promise.resolve();
2392
+ pendingInit = Promise.resolve();
2393
+ constructor() {
2394
+ this.level = SimpleLogger.resolveLevel();
2395
+ this.logFilePath = "";
2396
+ this.fileLoggingEnabled = false;
2397
+ }
2398
+ static getInstance() {
2399
+ return loggerSingleton.getOrInit(() => new SimpleLogger, (v) => ("__brand" in v) && v.__brand === "SimpleLogger");
2400
+ }
2401
+ static resetInstance() {
2402
+ loggerSingleton.clear();
2403
+ }
2404
+ static isNode = typeof process !== "undefined" && !!process.versions?.node;
2405
+ static resolveLevel() {
2406
+ if (SimpleLogger.isNode) {
2407
+ const explicitLevel = SimpleLogger.parseLevel(process.env?.UIP_LOG_LEVEL ?? "");
2408
+ if (explicitLevel !== undefined)
2409
+ return explicitLevel;
2410
+ const debugVal = process.env?.DEBUG;
2411
+ if (debugVal === "true" || debugVal === "1") {
2412
+ return 0 /* DEBUG */;
2413
+ }
2414
+ return DEFAULT_LOG_LEVEL;
2415
+ }
2416
+ const [localStorageError, hasDebug] = catchError(() => typeof localStorage !== "undefined" && !!localStorage.getItem("debug"));
2417
+ if (!localStorageError && hasDebug) {
2418
+ return 0 /* DEBUG */;
2419
+ }
2420
+ return DEFAULT_LOG_LEVEL;
2421
+ }
2422
+ static parseLevel(value) {
2423
+ switch (value.toLowerCase()) {
2424
+ case "debug":
2425
+ return 0 /* DEBUG */;
2426
+ case "info":
2427
+ return 1 /* INFO */;
2428
+ case "warn":
2429
+ return 2 /* WARN */;
2430
+ case "error":
2431
+ return 3 /* ERROR */;
2432
+ default:
2433
+ return;
2434
+ }
2435
+ }
2436
+ format(message, args) {
2437
+ if (args.length === 0)
2438
+ return `${message}
2439
+ `;
2440
+ return `${message} ${args.map(String).join(" ")}
2441
+ `;
2442
+ }
2443
+ isFileLoggingActive() {
2444
+ return this.fileLoggingEnabled || !!getGlobalLogFilePath();
2445
+ }
2446
+ writeToFile(formatted) {
2447
+ const path2 = this.logFilePath || getGlobalLogFilePath();
2448
+ if (!path2)
2449
+ return;
2450
+ const timestamp = new Date().toISOString();
2451
+ this.pendingWrites = Promise.all([
2452
+ this.pendingWrites,
2453
+ this.pendingInit
2454
+ ]).then(() => getFileSystem().appendFile(path2, `${timestamp} ${formatted}`).catch(() => {}));
2455
+ }
2456
+ write(formatted) {
2457
+ if (this.isFileLoggingActive()) {
2458
+ this.writeToFile(formatted);
2459
+ } else {
2460
+ getOutputSink().writeErr(formatted);
2461
+ }
2462
+ }
2463
+ debug(message, ...args) {
2464
+ if (this.level > 0 /* DEBUG */)
2465
+ return;
2466
+ const formatted = this.format(`[DEBUG] ${message}`, args);
2467
+ this.write(formatted);
2468
+ }
2469
+ info(message, ...args) {
2470
+ if (this.level > 1 /* INFO */)
2471
+ return;
2472
+ const formatted = this.format(message, args);
2473
+ this.write(formatted);
2474
+ }
2475
+ warn(message, ...args) {
2476
+ if (this.level > 2 /* WARN */)
2477
+ return;
2478
+ const formatted = this.format(`[WARN] ${message}`, args);
2479
+ this.write(formatted);
2480
+ }
2481
+ error(message, ...args) {
2482
+ if (this.level > 3 /* ERROR */)
2483
+ return;
2484
+ const formatted = this.format(`[ERROR] ${message}`, args);
2485
+ this.write(formatted);
2486
+ }
2487
+ report(message) {
2488
+ const formatted = this.format(message, []);
2489
+ this.write(formatted);
2490
+ }
2491
+ getLevel() {
2492
+ return this.level;
2493
+ }
2494
+ setLevel(level) {
2495
+ this.level = level;
2496
+ }
2497
+ setFileLogging(enabled) {
2498
+ this.fileLoggingEnabled = enabled;
2499
+ if (!enabled) {
2500
+ this.logFilePath = "";
2501
+ setGlobalLogFilePath("");
2502
+ }
2503
+ }
2504
+ setLogFile(path2) {
2505
+ this.logFilePath = path2;
2506
+ setGlobalLogFilePath(path2);
2507
+ if (!path2)
2508
+ return;
2509
+ this.fileLoggingEnabled = true;
2510
+ const fs2 = getFileSystem();
2511
+ this.pendingInit = (async () => {
2512
+ const [error] = await catchError((async () => {
2513
+ await fs2.mkdir(fs2.path.dirname(path2));
2514
+ await fs2.writeFile(path2, "");
2515
+ })());
2516
+ if (error)
2517
+ this.fileLoggingEnabled = false;
2518
+ })();
2519
+ }
2520
+ async flushFile() {
2521
+ await this.pendingInit;
2522
+ await this.pendingWrites;
2523
+ }
2524
+ getLogFilePath() {
2525
+ return this.logFilePath || getGlobalLogFilePath();
2526
+ }
2527
+ handleLog = (logMessage) => {
2528
+ const parts = [];
2529
+ if (logMessage.source) {
2530
+ parts.push(`[${logMessage.source}]`);
2531
+ }
2532
+ if (logMessage.sourceTarget) {
2533
+ parts.push(`[${logMessage.sourceTarget}]`);
2534
+ }
2535
+ parts.push(logMessage.message);
2536
+ const msg = parts.join(" ");
2537
+ switch (logMessage.logLevel) {
2538
+ case "Debug":
2539
+ this.debug(msg);
2540
+ break;
2541
+ case "Information":
2542
+ this.info(msg);
2543
+ break;
2544
+ case "Warning":
2545
+ this.warn(msg);
2546
+ break;
2547
+ case "Error":
2548
+ this.error(msg);
2549
+ break;
2550
+ default:
2551
+ this.info(msg);
2552
+ break;
2553
+ }
2554
+ };
2555
+ }
2556
+ var loggerSingleton = singleton(SimpleLogger);
2557
+ var logger = SimpleLogger.getInstance();
2558
+ function getLogFilePath() {
2559
+ return logger.getLogFilePath();
2560
+ }
2561
+
2562
+ // ../common/src/telemetry/debug-telemetry-provider.ts
2563
+ class DebugTelemetryProvider {
2564
+ async trackEvent({ name }) {
2565
+ logger.debug(`[Telemetry] Event: ${name}`);
2566
+ }
2567
+ async trackException({ error }) {
2568
+ logger.error(`[Telemetry] Exception: ${error.message}`);
2569
+ }
2570
+ async trackRequest({
2571
+ name,
2572
+ durationMs,
2573
+ success
2574
+ }) {
2575
+ logger.debug(`[Telemetry] Request: ${name} (${durationMs}ms, ${success ? "ok" : "fail"})`);
2576
+ }
2577
+ async trackDependency({
2578
+ name,
2579
+ type,
2580
+ durationMs,
2581
+ success
2582
+ }) {
2583
+ logger.debug(`[Telemetry] Dependency: ${name} [${type}] (${durationMs}ms, ${success ? "ok" : "fail"})`);
2584
+ }
2585
+ }
2586
+
2587
+ // ../common/src/telemetry/node-context-storage.ts
2588
+ import { AsyncLocalStorage } from "node:async_hooks";
2589
+
2590
+ class NodeContextStorage {
2591
+ storage = new AsyncLocalStorage;
2592
+ run(context, fn) {
2593
+ return this.storage.run(context, fn);
2594
+ }
2595
+ getContext() {
2596
+ return this.storage.getStore();
2597
+ }
2598
+ }
2599
+ // ../common/src/timings.ts
2600
+ var TIMINGS_ENV_VAR = "UIP_TIMINGS";
2601
+ function createStorage2() {
2602
+ const [error, mod] = catchError(() => __require("node:async_hooks"));
2603
+ if (error || typeof mod?.AsyncLocalStorage !== "function") {
2604
+ return {
2605
+ getStore: () => {
2606
+ return;
2607
+ },
2608
+ run: (_store, fn) => fn()
2609
+ };
2610
+ }
2611
+ return new mod.AsyncLocalStorage;
2612
+ }
2613
+ var storageSlot = singleton("TimingStorage");
2614
+ var stateSlot = singleton("Timings");
2615
+ var rootStartedSlot = singleton("TimingsRootStarted");
2616
+ var longLivedHostSlot = singleton("TimingsLongLivedHost");
2617
+ var storage = storageSlot.getOrInit(createStorage2, (value) => ("getStore" in value));
2618
+ function newState(baseline) {
2619
+ return { baseline, httpMs: 0, httpCalls: 0 };
2620
+ }
2621
+ function getState() {
2622
+ const scoped = storage.getStore();
2623
+ if (scoped) {
2624
+ return scoped;
2625
+ }
2626
+ const pinned = livePinnedState();
2627
+ if (pinned !== undefined) {
2628
+ return pinned;
2629
+ }
2630
+ return newState(processStartIsInvocationStart() ? 0 : performance.now());
2631
+ }
2632
+ function livePinnedState() {
2633
+ const pinned = stateSlot.get();
2634
+ return pinned !== undefined && "httpCalls" in pinned && !pinned.finished ? pinned : undefined;
2635
+ }
2636
+ function processStartIsInvocationStart() {
2637
+ return !rootStartedSlot.get(false) && !longLivedHostSlot.get(false);
2638
+ }
2639
+ function timingsEnabled() {
2640
+ if (typeof process === "undefined") {
2641
+ return false;
2642
+ }
2643
+ const value = process.env?.[TIMINGS_ENV_VAR];
2644
+ if (value === undefined) {
2645
+ return false;
2646
+ }
2647
+ const normalized = value.trim().toLowerCase();
2648
+ return normalized === "1" || normalized === "true";
2649
+ }
2650
+ function recordExitCode(exitCode) {
2651
+ if (!timingsEnabled()) {
2652
+ return;
2653
+ }
2654
+ getState().exitCode = exitCode;
2655
+ }
2656
+ function invocationStartedAt() {
2657
+ return new Date(performance.timeOrigin + getState().baseline);
2658
+ }
2659
+ function invocationElapsedMs() {
2660
+ return performance.now() - getState().baseline;
2661
+ }
2662
+ function markCommandStart() {
2663
+ if (!timingsEnabled()) {
2664
+ return;
2665
+ }
2666
+ getState().commandStart = performance.now();
2667
+ }
2668
+ function recordCommandDuration(durationMs) {
2669
+ if (!timingsEnabled()) {
2670
+ return;
2671
+ }
2672
+ getState().commandMs = durationMs;
2673
+ }
2674
+
2675
+ // ../common/src/registry.ts
2676
+ import { execFileSync } from "node:child_process";
2677
+ function readRegistryValue(keyPath, valueName) {
2678
+ if (process.platform !== "win32") {
2679
+ return "";
2680
+ }
2681
+ const [error, output] = catchError(() => execFileSync("reg", ["query", keyPath, "/v", valueName], {
2682
+ encoding: "utf-8",
2683
+ stdio: ["pipe", "pipe", "pipe"],
2684
+ windowsHide: true
2685
+ }));
2686
+ if (error) {
2687
+ return "";
2688
+ }
2689
+ const match = output.match(new RegExp(`${valueName}\\s+REG_SZ\\s+(.+)`));
2690
+ return match?.[1]?.trim() ?? "";
2691
+ }
2692
+
2693
+ // ../common/src/telemetry/logger-telemetry-provider.ts
2694
+ class LoggerTelemetryProvider {
2695
+ analyticsUniqueId;
2696
+ constructor() {
2697
+ this.analyticsUniqueId = readRegistryValue("HKCU\\Software\\UiPath", "AnalyticsUniqueId");
2698
+ }
2699
+ enrich(properties) {
2700
+ return {
2701
+ ...properties,
2702
+ ...this.analyticsUniqueId ? { analyticsUniqueId: this.analyticsUniqueId } : {}
2703
+ };
2704
+ }
2705
+ async trackEvent({ name, properties }) {
2706
+ logger.debug(formatMessage("Event", name, this.enrich(properties)));
2707
+ }
2708
+ async trackException({
2709
+ error,
2710
+ properties
2711
+ }) {
2712
+ logger.error(formatMessage("Exception", error.message, this.enrich({
2713
+ ...properties,
2714
+ stack: error.stack
2715
+ })));
2716
+ }
2717
+ async trackRequest({
2718
+ name,
2719
+ durationMs,
2720
+ success,
2721
+ properties
2722
+ }) {
2723
+ logger.debug(formatMessage("Request", name, this.enrich({
2724
+ ...properties,
2725
+ duration: `${durationMs}ms`,
2726
+ success
2727
+ })));
2728
+ }
2729
+ async trackDependency({
2730
+ name,
2731
+ type,
2732
+ durationMs,
2733
+ success,
2734
+ properties
2735
+ }) {
2736
+ logger.debug(formatMessage("Dependency", name, this.enrich({
2737
+ ...properties,
2738
+ type,
2739
+ duration: `${durationMs}ms`,
2740
+ success
2741
+ })));
2742
+ }
2743
+ }
2744
+ function formatMessage(category, name, properties) {
2745
+ let message = `[Telemetry] [${category}] ${name}`;
2746
+ if (properties && Object.keys(properties).length > 0) {
2747
+ const propsStr = Object.entries(properties).filter(([_, value]) => value !== undefined).map(([key, value]) => `${key}=${value}`).join(", ");
2748
+ if (propsStr) {
2749
+ message += ` | ${propsStr}`;
2750
+ }
2751
+ }
2752
+ return message;
2753
+ }
2754
+
2755
+ // ../common/src/telemetry/proxy-http-agent.ts
2756
+ var slot = singleton("ProxyAuthHttpsAgent");
2757
+
2758
+ // ../common/src/telemetry/node-appinsights-telemetry-provider.ts
2759
+ var providerSlot = singleton("TelemetryProvider");
2760
+
2761
+ // ../common/src/telemetry/telemetry-spool.ts
2762
+ var sidecarEntrySlot = singleton("TelemetrySidecarEntry");
2763
+ var MAX_SPOOL_AGE_MS = 72 * 60 * 60 * 1000;
2764
+
2765
+ // ../common/src/telemetry/telemetry-init.ts
2766
+ var telemetryInstanceSlot = singleton("TelemetryService");
2767
+ var DEFAULT_AI_CONNECTION_STRING = atob("SW5zdHJ1bWVudGF0aW9uS2V5PTliZDM3NDgyLTgxMGUtNDQyYS1hYWE2LWQzOGVmNjVjNjY3NDtJbmdlc3Rpb25FbmRwb2ludD1odHRwczovL3dlc3RldXJvcGUtNS5pbi5hcHBsaWNhdGlvbmluc2lnaHRzLmF6dXJlLmNvbS87TGl2ZUVuZHBvaW50PWh0dHBzOi8vd2VzdGV1cm9wZS5saXZlZGlhZ25vc3RpY3MubW9uaXRvci5henVyZS5jb20vO0FwcGxpY2F0aW9uSWQ9MzU2OTdlZjEtOGJkMC00ZjE5LWEyN2MtZDg3Y2NhYzY2ZDJj");
2768
+ function getGlobalTelemetryInstance() {
2769
+ const existing = telemetryInstanceSlot.get();
2770
+ if (existing && typeof existing === "object" && "trackEvent" in existing && typeof existing.trackEvent === "function") {
2771
+ return existing;
2772
+ }
2773
+ return;
2774
+ }
2775
+ function setGlobalTelemetryInstance(instance) {
2776
+ telemetryInstanceSlot.set(instance);
2777
+ }
2778
+ var _localTelemetryInstance;
2779
+ function getTelemetryInstance() {
2780
+ const global = getGlobalTelemetryInstance();
2781
+ if (global)
2782
+ return global;
2783
+ if (!_localTelemetryInstance) {
2784
+ _localTelemetryInstance = new TelemetryService(new LoggerTelemetryProvider, new NodeContextStorage);
2785
+ setGlobalTelemetryInstance(_localTelemetryInstance);
2786
+ }
2787
+ return _localTelemetryInstance;
2788
+ }
2789
+ var telemetry = new Proxy({}, {
2790
+ get(_, prop) {
2791
+ const instance = getTelemetryInstance();
2792
+ const value = instance[prop];
2793
+ return typeof value === "function" ? value.bind(instance) : value;
2794
+ }
2795
+ });
2796
+ // ../../node_modules/commander/esm.mjs
2797
+ var import__ = __toESM(require_commander(), 1);
2798
+ var {
2799
+ program,
2800
+ createCommand,
2801
+ createArgument,
2802
+ createOption,
2803
+ CommanderError,
2804
+ InvalidArgumentError,
2805
+ InvalidOptionArgumentError,
2806
+ Command,
2807
+ Argument,
2808
+ Option,
2809
+ Help
2810
+ } = import__.default;
2811
+ // ../common/src/exit-code.ts
2812
+ function setExitCode(code) {
2813
+ process.exitCode = code;
2814
+ }
2815
+
2816
+ // ../common/src/output-codecs.ts
2817
+ var yamlSlot = singleton("YamlCodec");
2818
+ var jmespathSlot = singleton("JmespathCodec");
2819
+ async function loadOutputCodecsAsync(needed) {
2820
+ const loads = [];
2821
+ if (needed.yaml && yamlSlot.get() === undefined) {
2822
+ loads.push(import("./js-yaml-rtdrjz2v.js").then((mod) => {
2823
+ yamlSlot.set(mod);
2824
+ }));
2825
+ }
2826
+ if (needed.filter && jmespathSlot.get() === undefined) {
2827
+ loads.push(import("./jmespath-231m3hyn.js").then((m)=>__toESM(m.default,1)).then((mod) => {
2828
+ jmespathSlot.set(mod);
2829
+ }));
2830
+ }
2831
+ await Promise.all(loads);
2832
+ }
2833
+ function getYamlCodec() {
2834
+ return yamlSlot.get();
2835
+ }
2836
+ function getJmespathCodec() {
2837
+ return jmespathSlot.get();
2838
+ }
2839
+
2840
+ // ../common/src/output-format-context.ts
2841
+ var formatSlot = singleton("OutputFormat");
2842
+ var formatExplicitSlot = singleton("OutputFormatExplicit");
2843
+ var helpRequestedSlot = singleton("HelpRequested");
2844
+ var filterSlot = singleton("OutputFilter");
2845
+ function getOutputFormat() {
2846
+ return formatSlot.get("json");
2847
+ }
2848
+ function getOutputFilter() {
2849
+ return filterSlot.get();
2850
+ }
2851
+
2852
+ // ../common/src/telemetry/command-terminal.ts
2853
+ var recordedFailureSlot = singleton("CommandTelemetryFailure");
2854
+ var AUTH_ERROR_CODES = new Set([
2855
+ "authentication_required",
2856
+ "permission_denied"
2857
+ ]);
2858
+ var LOCAL_PERMISSION_CLI_ERROR_CODES = new Set([
2859
+ "local_permission_denied"
2860
+ ]);
2861
+ var VALIDATION_ERROR_CODES = new Set(["invalid_argument"]);
2862
+ var NETWORK_HTTP_ERROR_CODES = new Set([
2863
+ "network_error",
2864
+ "rate_limited",
2865
+ "server_error",
2866
+ "not_found",
2867
+ "method_not_allowed"
2868
+ ]);
2869
+ var TIMEOUT_ERROR_CODES = new Set(["timeout"]);
2870
+ var NETWORK_OS_ERROR_CODES = new Set([
2871
+ "ECONNREFUSED",
2872
+ "ECONNRESET",
2873
+ "ENOTFOUND",
2874
+ "EAI_AGAIN",
2875
+ "EPIPE",
2876
+ "EHOSTUNREACH",
2877
+ "ENETUNREACH",
2878
+ "EAI_FAIL"
2879
+ ]);
2880
+ var TIMEOUT_OS_ERROR_CODES = new Set(["ETIMEDOUT", "ESOCKETTIMEDOUT"]);
2881
+ var TLS_ERROR_CODES = new Set([
2882
+ "SELF_SIGNED_CERT_IN_CHAIN",
2883
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
2884
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
2885
+ "UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
2886
+ "UNABLE_TO_GET_ISSUER_CERT",
2887
+ "CERT_HAS_EXPIRED",
2888
+ "CERT_UNTRUSTED",
2889
+ "ERR_TLS_CERT_ALTNAME_INVALID"
2890
+ ]);
2891
+ var MISSING_DEPENDENCY_CODES = new Set([
2892
+ "MODULE_NOT_FOUND",
2893
+ "ERR_MODULE_NOT_FOUND"
2894
+ ]);
2895
+ var INTERNAL_ERROR_NAMES = new Set([
2896
+ "TypeError",
2897
+ "ReferenceError",
2898
+ "SyntaxError",
2899
+ "RangeError"
2900
+ ]);
2901
+ function isRecord(value) {
2902
+ return value !== null && typeof value === "object";
2903
+ }
2904
+ function stringField(value, field) {
2905
+ if (!isRecord(value)) {
2906
+ return;
2907
+ }
2908
+ const raw = value[field];
2909
+ return typeof raw === "string" ? raw : undefined;
2910
+ }
2911
+ function numberField(value, field) {
2912
+ if (!isRecord(value)) {
2913
+ return;
2914
+ }
2915
+ const raw = value[field];
2916
+ return typeof raw === "number" ? raw : undefined;
2917
+ }
2918
+ function findStringInCauseChain(error, field) {
2919
+ let current = error;
2920
+ for (let depth = 0;depth < 5 && current !== null && typeof current === "object"; depth++) {
2921
+ const value = stringField(current, field);
2922
+ if (value) {
2923
+ return value;
2924
+ }
2925
+ current = current.cause;
2926
+ }
2927
+ return;
2928
+ }
2929
+ function findCodeInCauseChain(error) {
2930
+ return findStringInCauseChain(error, "code");
2931
+ }
2932
+ function isSpawnEnoent(error) {
2933
+ const code = findCodeInCauseChain(error);
2934
+ if (code !== "ENOENT") {
2935
+ return false;
2936
+ }
2937
+ const syscall = findStringInCauseChain(error, "syscall");
2938
+ return syscall?.startsWith("spawn") === true;
2939
+ }
2940
+ function isCancellationError(error, exitCode, pollSignal) {
2941
+ if (exitCode === 130) {
2942
+ return true;
2943
+ }
2944
+ if (!isRecord(error)) {
2945
+ return false;
2946
+ }
2947
+ if (numberField(error, "exitCode") === 130) {
2948
+ return true;
2949
+ }
2950
+ const name = stringField(error, "name");
2951
+ if (name === "ExitPromptError") {
2952
+ return true;
2953
+ }
2954
+ if (name === "AbortError" && pollSignal?.aborted) {
2955
+ return true;
2956
+ }
2957
+ const message = stringField(error, "message");
2958
+ return message?.includes("SIGINT") === true;
2959
+ }
2960
+ function terminalSignalFor(input, outcome) {
2961
+ if (input.recordedFailure?.terminalSignal) {
2962
+ return input.recordedFailure.terminalSignal;
2963
+ }
2964
+ const explicit = findStringInCauseChain(input.error, "terminalSignal") ?? findStringInCauseChain(input.error, "signal");
2965
+ if (explicit) {
2966
+ return explicit;
2967
+ }
2968
+ return outcome === "cancelled" ? "SIGINT" : undefined;
2969
+ }
2970
+ function classifyHttpStatus(status) {
2971
+ if (status === 401 || status === 403) {
2972
+ return "auth";
2973
+ }
2974
+ if (status === 400 || status === 409 || status === 422) {
2975
+ return "validation";
2976
+ }
2977
+ if (status === 408) {
2978
+ return "timeout";
2979
+ }
2980
+ return "network_http";
2981
+ }
2982
+ function classifyFromResult(result) {
2983
+ switch (result) {
2984
+ case "AuthenticationError":
2985
+ return "auth";
2986
+ case "ValidationError":
2987
+ return "validation";
2988
+ case "TimeoutError":
2989
+ return "timeout";
2990
+ default:
2991
+ return;
2992
+ }
2993
+ }
2994
+ function classifyFromErrorCode(errorCode) {
2995
+ if (!errorCode) {
2996
+ return;
2997
+ }
2998
+ if (AUTH_ERROR_CODES.has(errorCode)) {
2999
+ return "auth";
3000
+ }
3001
+ if (LOCAL_PERMISSION_CLI_ERROR_CODES.has(errorCode)) {
3002
+ return "local_permission";
3003
+ }
3004
+ if (VALIDATION_ERROR_CODES.has(errorCode)) {
3005
+ return "validation";
3006
+ }
3007
+ if (TIMEOUT_ERROR_CODES.has(errorCode)) {
3008
+ return "timeout";
3009
+ }
3010
+ if (NETWORK_HTTP_ERROR_CODES.has(errorCode)) {
3011
+ return "network_http";
3012
+ }
3013
+ return;
3014
+ }
3015
+ function hasLocalPermissionCode(error) {
3016
+ for (const node of walkErrorGraph(error)) {
3017
+ const code = node.code;
3018
+ if (typeof code === "string" && LOCAL_PERMISSION_ERROR_CODES.has(code)) {
3019
+ return true;
3020
+ }
3021
+ }
3022
+ return false;
3023
+ }
3024
+ function classifyFromError(error) {
3025
+ const code = findCodeInCauseChain(error);
3026
+ if (code) {
3027
+ if (code.startsWith("commander.")) {
3028
+ return "validation";
3029
+ }
3030
+ if (NETWORK_OS_ERROR_CODES.has(code) || TLS_ERROR_CODES.has(code)) {
3031
+ return "network_http";
3032
+ }
3033
+ if (TIMEOUT_OS_ERROR_CODES.has(code)) {
3034
+ return "timeout";
3035
+ }
3036
+ if (MISSING_DEPENDENCY_CODES.has(code) || isSpawnEnoent(error)) {
3037
+ return "missing_dependency";
3038
+ }
3039
+ }
3040
+ if (hasLocalPermissionCode(error)) {
3041
+ return "local_permission";
3042
+ }
3043
+ const message = stringField(error, "message");
3044
+ if (message?.includes("fetch failed") === true) {
3045
+ return "network_http";
3046
+ }
3047
+ const name = stringField(error, "name");
3048
+ if (name && INTERNAL_ERROR_NAMES.has(name)) {
3049
+ return "internal";
3050
+ }
3051
+ return;
3052
+ }
3053
+ function classifyError(input) {
3054
+ const recorded = input.recordedFailure;
3055
+ if (recorded?.errorClass) {
3056
+ return recorded.errorClass;
3057
+ }
3058
+ const status = recorded?.context?.httpStatus ?? findHttpStatusInGraph(input.error);
3059
+ if (status !== undefined) {
3060
+ return classifyHttpStatus(status);
3061
+ }
3062
+ return classifyFromResult(recorded?.result) ?? classifyFromErrorCode(recorded?.errorCode) ?? classifyFromError(input.error) ?? "unknown";
3063
+ }
3064
+ function recordCommandFailureTelemetry(failure) {
3065
+ recordedFailureSlot.set(failure);
3066
+ }
3067
+ function clearRecordedCommandFailureTelemetry() {
3068
+ recordedFailureSlot.clear();
3069
+ }
3070
+ function takeRecordedCommandFailureTelemetry() {
3071
+ const failure = recordedFailureSlot.get();
3072
+ recordedFailureSlot.clear();
3073
+ return failure;
3074
+ }
3075
+ function buildCommandTerminalTelemetryProperties(input) {
3076
+ const cancelled = isCancellationError(input.error, input.exitCode, input.pollSignal);
3077
+ const outcome = input.recordedFailure?.terminalOutcome ?? (input.exitCode === 0 ? "success" : cancelled ? "cancelled" : "failure");
3078
+ const errorClass = outcome === "success" || outcome === "no_op" ? undefined : outcome === "cancelled" ? "user_cancelled" : classifyError(input);
3079
+ const terminalSignal = terminalSignalFor(input, outcome);
3080
+ return {
3081
+ [CommandDimensions.ExitCode]: input.exitCode,
3082
+ [CommandDimensions.TerminalOutcome]: outcome,
3083
+ ...errorClass ? { [CommandDimensions.ErrorClass]: errorClass } : {},
3084
+ ...terminalSignal ? { [CommandDimensions.TerminalSignal]: terminalSignal } : {}
3085
+ };
3086
+ }
3087
+
3088
+ // ../common/src/telemetry/telemetry-events.ts
3089
+ var CommonTelemetryEvents = {
3090
+ Start: "Application.Start",
3091
+ Error: "Application.Error",
3092
+ ShipSucceeded: "Cli.ShipSucceeded"
3093
+ };
3094
+
3095
+ // ../common/src/formatter.ts
3096
+ var ANSI_STYLES = {
3097
+ red: "\x1B[31m",
3098
+ dim: "\x1B[2m"
3099
+ };
3100
+ var ANSI_RESET = "\x1B[0m";
3101
+ function styleLine(line, style) {
3102
+ return style ? `${ANSI_STYLES[style]}${line}${ANSI_RESET}` : line;
3103
+ }
3104
+ var CLI_ERROR_CODES = [
3105
+ "invalid_argument",
3106
+ "authentication_required",
3107
+ "permission_denied",
3108
+ "local_permission_denied",
3109
+ "not_found",
3110
+ "rate_limited",
3111
+ "network_error",
3112
+ "timeout",
3113
+ "server_error",
3114
+ "method_not_allowed",
3115
+ "configuration_error",
3116
+ "unknown_error"
3117
+ ];
3118
+ var RETRY_HINTS = [
3119
+ "RetryWillNotFix",
3120
+ "RetryLater",
3121
+ "RetryAfter1Second",
3122
+ "RetryAfter10Seconds",
3123
+ "RetryAfter30Seconds",
3124
+ "RetryAfter60Seconds"
3125
+ ];
3126
+ var CLI_ERROR_CODE_VALUES = new Set(CLI_ERROR_CODES);
3127
+ var RETRY_HINT_VALUES = new Set(RETRY_HINTS);
3128
+ function isCliErrorCode(value) {
3129
+ return typeof value === "string" && CLI_ERROR_CODE_VALUES.has(value);
3130
+ }
3131
+ function isRetryHint(value) {
3132
+ return typeof value === "string" && RETRY_HINT_VALUES.has(value);
3133
+ }
3134
+ var RESULTS = {
3135
+ Success: "Success",
3136
+ Failure: "Failure",
3137
+ ConfigError: "ConfigError",
3138
+ AuthenticationError: "AuthenticationError",
3139
+ ValidationError: "ValidationError",
3140
+ TimeoutError: "TimeoutError"
3141
+ };
3142
+ var EXIT_CODES = {
3143
+ Success: 0,
3144
+ Failure: 1,
3145
+ ConfigError: 1,
3146
+ AuthenticationError: 2,
3147
+ ValidationError: 3,
3148
+ TimeoutError: 4
3149
+ };
3150
+ class SuccessOutput {
3151
+ Result = RESULTS.Success;
3152
+ Code;
3153
+ Data;
3154
+ Pagination;
3155
+ Instructions;
3156
+ Warning;
3157
+ Log;
3158
+ constructor(code, data) {
3159
+ this.Code = code;
3160
+ this.Data = data;
3161
+ const logPath = getLogFilePath();
3162
+ if (logPath) {
3163
+ this.Log = logPath;
3164
+ }
3165
+ }
3166
+ }
3167
+
3168
+ class FailureOutput {
3169
+ Result;
3170
+ Code;
3171
+ ErrorCode;
3172
+ Message;
3173
+ Instructions;
3174
+ Retry;
3175
+ Context;
3176
+ Log;
3177
+ Data;
3178
+ SuppressTelemetry;
3179
+ TelemetryErrorClass;
3180
+ TelemetryTerminalOutcome;
3181
+ TelemetryTerminalSignal;
3182
+ constructor(result, message, instructions, context, errorCode, retry) {
3183
+ this.Result = result;
3184
+ this.Message = message;
3185
+ this.Instructions = instructions;
3186
+ if (errorCode) {
3187
+ this.ErrorCode = errorCode;
3188
+ }
3189
+ if (retry) {
3190
+ this.Retry = retry;
3191
+ }
3192
+ if (context) {
3193
+ this.Context = context;
3194
+ }
3195
+ const logPath = getLogFilePath();
3196
+ if (logPath) {
3197
+ this.Log = logPath;
3198
+ }
3199
+ }
3200
+ }
3201
+ function escapeNonAscii(jsonText) {
3202
+ return jsonText.replace(/[\u0080-\uffff]/g, (c) => {
3203
+ const hex = c.charCodeAt(0).toString(16).padStart(4, "0");
3204
+ return `\\u${hex}`;
3205
+ });
3206
+ }
3207
+ function needsAsciiSafeJson(sink) {
3208
+ return process.platform === "win32" && !sink.capabilities.isInteractive;
3209
+ }
3210
+ function isPlainRecord(value) {
3211
+ if (value === null || typeof value !== "object")
3212
+ return false;
3213
+ const prototype = Object.getPrototypeOf(value);
3214
+ return prototype === Object.prototype || prototype === null;
3215
+ }
3216
+ function splitPagedEnvelope(value) {
3217
+ if (Array.isArray(value) || !isPlainRecord(value))
3218
+ return null;
3219
+ const entries = Object.entries(value);
3220
+ if (entries.length === 0)
3221
+ return null;
3222
+ let found = null;
3223
+ const meta = Object.create(null);
3224
+ for (const [key, entry] of entries) {
3225
+ if (Array.isArray(entry)) {
3226
+ if (found !== null)
3227
+ return null;
3228
+ found = { key, rows: entry };
3229
+ } else if (entry !== null && typeof entry === "object") {
3230
+ return null;
3231
+ } else {
3232
+ meta[key] = entry;
3233
+ }
3234
+ }
3235
+ if (found === null || Object.keys(meta).length === 0)
3236
+ return null;
3237
+ return { ...found, meta };
3238
+ }
3239
+ function extractPagedRows(value) {
3240
+ const paged = splitPagedEnvelope(value);
3241
+ return paged === null ? null : paged.rows;
3242
+ }
3243
+ function toLowerCamelCaseKey(key) {
3244
+ if (!key)
3245
+ return key;
3246
+ if (/[_\-\s]/.test(key)) {
3247
+ const [firstPart, ...restParts] = key.split(/[_\-\s]+/).filter(Boolean);
3248
+ if (!firstPart)
3249
+ return key;
3250
+ return [
3251
+ toLowerCamelCaseSimpleKey(firstPart),
3252
+ ...restParts.map((part) => {
3253
+ const normalized = toLowerCamelCaseSimpleKey(part);
3254
+ return normalized.charAt(0).toUpperCase() + normalized.slice(1);
3255
+ })
3256
+ ].join("");
3257
+ }
3258
+ return toLowerCamelCaseSimpleKey(key);
3259
+ }
3260
+ function toLowerCamelCaseSimpleKey(key) {
3261
+ if (/^[A-Z0-9]+$/.test(key))
3262
+ return key.toLowerCase();
3263
+ return key.replace(/^[A-Z]+(?=[A-Z][a-z]|\d|$)|^[A-Z]/, (match) => match.toLowerCase());
3264
+ }
3265
+ function toPascalCaseKey(key) {
3266
+ const lowerCamelKey = toLowerCamelCaseKey(key);
3267
+ return lowerCamelKey ? lowerCamelKey.charAt(0).toUpperCase() + lowerCamelKey.slice(1) : lowerCamelKey;
3268
+ }
3269
+ function collectVerbatimRefs(value, into) {
3270
+ if (typeof value !== "object" || value === null)
3271
+ return;
3272
+ if (into.has(value))
3273
+ return;
3274
+ into.add(value);
3275
+ for (const nested of Array.isArray(value) ? value : Object.values(value)) {
3276
+ collectVerbatimRefs(nested, into);
3277
+ }
3278
+ }
3279
+ function toPascalCaseData(value, verbatimKeys, subtrees) {
3280
+ if (subtrees?.mode === "skip" && typeof value === "object" && value !== null && subtrees.refs.has(value)) {
3281
+ return value;
3282
+ }
3283
+ if (Array.isArray(value))
3284
+ return value.map((entry) => toPascalCaseData(entry, verbatimKeys, subtrees));
3285
+ if (!isPlainRecord(value))
3286
+ return value;
3287
+ const result = {};
3288
+ for (const [key, nestedValue] of Object.entries(value)) {
3289
+ const pascalKey = toPascalCaseKey(key);
3290
+ if (verbatimKeys?.has(pascalKey)) {
3291
+ result[pascalKey] = nestedValue;
3292
+ if (subtrees?.mode === "collect") {
3293
+ collectVerbatimRefs(nestedValue, subtrees.refs);
3294
+ }
3295
+ continue;
3296
+ }
3297
+ result[pascalKey] = toPascalCaseData(nestedValue, verbatimKeys, subtrees);
3298
+ }
3299
+ return result;
3300
+ }
3301
+ function normalizeDataKeys(data, verbatimKeys, subtrees) {
3302
+ return toPascalCaseData(data, verbatimKeys, subtrees);
3303
+ }
3304
+ function toVerbatimKeySet(preserve) {
3305
+ if (!Array.isArray(preserve))
3306
+ return;
3307
+ return new Set(preserve.map(toPascalCaseKey));
3308
+ }
3309
+ function normalizeOutputKeys(data) {
3310
+ const result = {};
3311
+ for (const [key, value] of Object.entries(data)) {
3312
+ const pascalKey = toPascalCaseKey(key);
3313
+ result[pascalKey] = pascalKey === "Data" ? value : toPascalCaseData(value);
3314
+ }
3315
+ return result;
3316
+ }
3317
+ function printOutput(data, format = "json", logFn, asciiSafe = false, tableRowStyle) {
3318
+ if (!data) {
3319
+ logFn("Empty response object. No data to display.");
3320
+ return;
3321
+ }
3322
+ switch (format) {
3323
+ case "json": {
3324
+ const json = JSON.stringify(data, null, 2);
3325
+ logFn(asciiSafe ? escapeNonAscii(json) : json);
3326
+ break;
3327
+ }
3328
+ case "yaml":
3329
+ logFn(toYaml(data));
3330
+ break;
3331
+ case "plain": {
3332
+ if ("Data" in data && data.Data != null) {
3333
+ const pagedRows = extractPagedRows(data.Data);
3334
+ const items = pagedRows ?? (Array.isArray(data.Data) ? data.Data : [data.Data]);
3335
+ items.forEach((item) => {
3336
+ const values = Object.values(item).map((v) => v ?? "").join("\t");
3337
+ logFn(values);
3338
+ });
3339
+ } else {
3340
+ const values = Object.values(data).map((v) => v ?? "").join("\t");
3341
+ logFn(values);
3342
+ }
3343
+ break;
3344
+ }
3345
+ case "markdown":
3346
+ logFn(renderMarkdown(data));
3347
+ break;
3348
+ default: {
3349
+ const hasData = "Data" in data && data.Data != null;
3350
+ const pagedRows = hasData ? extractPagedRows(data.Data) : null;
3351
+ const rows = pagedRows ? pagedRows : Array.isArray(data.Data) ? data.Data : null;
3352
+ if (hasData && !(rows !== null && rows.length === 0)) {
3353
+ const logValue = data.Log;
3354
+ if (rows !== null) {
3355
+ printResizableTable(rows, logFn, logValue, undefined, tableRowStyle);
3356
+ } else {
3357
+ printVerticalTable(data.Data, logFn, logValue);
3358
+ }
3359
+ } else {
3360
+ printTable([{ ...data }], logFn);
3361
+ }
3362
+ break;
3363
+ }
3364
+ }
3365
+ }
3366
+ function logOutput(data, format = "json", tableRowStyle) {
3367
+ const sink = getOutputSink();
3368
+ const styleFn = sink.capabilities.isInteractive && sink.capabilities.supportsColor ? tableRowStyle : undefined;
3369
+ printOutput(data, format, (msg) => sink.writeOut(`${msg}
3370
+ `), needsAsciiSafeJson(sink), styleFn);
3371
+ }
3372
+ var PLUMBING_KEYS = new Set(["code", "log"]);
3373
+ function isPlumbingKey(key) {
3374
+ return PLUMBING_KEYS.has(key.toLowerCase());
3375
+ }
3376
+ function cellToString(val) {
3377
+ return val != null && typeof val === "object" ? JSON.stringify(val) : String(val ?? "");
3378
+ }
3379
+ function wrapText(text, width) {
3380
+ if (text.length <= width)
3381
+ return [text];
3382
+ const lines = [];
3383
+ for (let pos = 0;pos < text.length; pos += width) {
3384
+ lines.push(text.substring(pos, pos + width));
3385
+ }
3386
+ return lines;
3387
+ }
3388
+ function printTable(data, logFn, externalLogValue, tableRowStyle) {
3389
+ if (data.length === 0)
3390
+ return;
3391
+ const keys = Object.keys(data[0]).filter((key) => !isPlumbingKey(key));
3392
+ const maxWidths = keys.map((key) => Math.max(key.length, ...data.map((item) => cellToString(item[key]).length)));
3393
+ const header = keys.map((key, i) => key.padEnd(maxWidths[i])).join(" | ");
3394
+ logFn(header);
3395
+ logFn(keys.map((_, i) => "-".repeat(maxWidths[i])).join("-|-"));
3396
+ data.forEach((item) => {
3397
+ const row = keys.map((key, i) => cellToString(item[key]).padEnd(maxWidths[i])).join(" | ");
3398
+ logFn(styleLine(row, tableRowStyle?.(item)));
3399
+ });
3400
+ if (externalLogValue) {
3401
+ logFn("");
3402
+ logFn(`Log: ${externalLogValue}`);
3403
+ }
3404
+ }
3405
+ function isPlainObjectArray(value) {
3406
+ return Array.isArray(value) && value.length > 0 && value.every(isPlainRecord);
3407
+ }
3408
+ function isNonEmptyPlainObject(value) {
3409
+ return isPlainRecord(value) && Object.keys(value).length > 0;
3410
+ }
3411
+ var NESTED_INDENT = " ";
3412
+ function printVerticalTable(data, logFn = console.log, externalLogValue) {
3413
+ const keys = Object.keys(data).filter((key) => !isPlumbingKey(key));
3414
+ if (keys.length === 0)
3415
+ return;
3416
+ const isBlockValue = (value) => isPlainObjectArray(value) || isNonEmptyPlainObject(value);
3417
+ const scalarKeys = keys.filter((key) => !isBlockValue(data[key]));
3418
+ const maxKeyWidth = scalarKeys.length > 0 ? Math.max(...scalarKeys.map((key) => key.length)) : 0;
3419
+ const termWidth = process.stdout.columns || 120;
3420
+ const nestedWidth = Math.max(termWidth - NESTED_INDENT.length, 1);
3421
+ keys.forEach((key) => {
3422
+ const value = data[key];
3423
+ if (isPlainObjectArray(value)) {
3424
+ logFn(`${key}:`);
3425
+ printResizableTable(value, (line) => logFn(`${NESTED_INDENT}${line}`), undefined, nestedWidth);
3426
+ return;
3427
+ }
3428
+ if (isNonEmptyPlainObject(value)) {
3429
+ logFn(`${key}:`);
3430
+ printVerticalTable(value, (line) => logFn(`${NESTED_INDENT}${line}`));
3431
+ return;
3432
+ }
3433
+ const keyCol = key.padEnd(maxKeyWidth);
3434
+ logFn(`${keyCol} | ${cellToString(value)}`);
3435
+ });
3436
+ if (externalLogValue) {
3437
+ logFn("");
3438
+ logFn(`Log: ${externalLogValue}`);
3439
+ }
3440
+ }
3441
+ function printResizableTable(data, logFn = console.log, externalLogValue, availableWidth, tableRowStyle) {
3442
+ if (data.length === 0)
3443
+ return;
3444
+ const keys = Object.keys(data[0]).filter((key) => !isPlumbingKey(key));
3445
+ if (keys.length === 0)
3446
+ return;
3447
+ if (!process.stdout.isTTY) {
3448
+ printTable(data, logFn, externalLogValue, tableRowStyle);
3449
+ return;
3450
+ }
3451
+ const naturalWidths = keys.map((key) => Math.max(key.length, ...data.map((item) => cellToString(item[key]).length)));
3452
+ const separatorTotal = (keys.length - 1) * 3;
3453
+ const totalWidth = naturalWidths.reduce((a, b) => a + b, 0) + separatorTotal;
3454
+ const termWidth = availableWidth ?? (process.stdout.columns || 120);
3455
+ if (totalWidth <= termWidth) {
3456
+ printTable(data, logFn, externalLogValue, tableRowStyle);
3457
+ return;
3458
+ }
3459
+ const overflow = totalWidth - termWidth;
3460
+ const MIN_COL_WIDTH = 10;
3461
+ const minWidths = keys.map((key) => Math.max(key.length, MIN_COL_WIDTH));
3462
+ let bestCol = -1;
3463
+ let bestCost = Infinity;
3464
+ for (let i = 0;i < keys.length; i++) {
3465
+ const maxShrink = naturalWidths[i] - minWidths[i];
3466
+ if (maxShrink < overflow)
3467
+ continue;
3468
+ const newWidth = naturalWidths[i] - overflow;
3469
+ let extraRows = 0;
3470
+ for (const item of data) {
3471
+ const cellLen = cellToString(item[keys[i]]).length;
3472
+ if (cellLen > newWidth) {
3473
+ extraRows += Math.ceil(cellLen / newWidth) - 1;
3474
+ }
3475
+ }
3476
+ if (extraRows < bestCost) {
3477
+ bestCost = extraRows;
3478
+ bestCol = i;
3479
+ }
3480
+ }
3481
+ const finalWidths = [...naturalWidths];
3482
+ if (bestCol !== -1) {
3483
+ finalWidths[bestCol] = naturalWidths[bestCol] - overflow;
3484
+ } else {
3485
+ let remaining = overflow;
3486
+ const colsByShrinkPotential = keys.map((_, i) => ({
3487
+ index: i,
3488
+ potential: naturalWidths[i] - minWidths[i]
3489
+ })).filter((c) => c.potential > 0).sort((a, b) => b.potential - a.potential);
3490
+ for (const col of colsByShrinkPotential) {
3491
+ if (remaining <= 0)
3492
+ break;
3493
+ const shrink = Math.min(remaining, col.potential);
3494
+ finalWidths[col.index] -= shrink;
3495
+ remaining -= shrink;
3496
+ }
3497
+ }
3498
+ const header = keys.map((key, i) => key.padEnd(finalWidths[i])).join(" | ");
3499
+ logFn(header);
3500
+ logFn(keys.map((_, i) => "-".repeat(finalWidths[i])).join("-|-"));
3501
+ data.forEach((item) => {
3502
+ const style = tableRowStyle?.(item);
3503
+ const cellLines = keys.map((key, i) => wrapText(cellToString(item[key]), finalWidths[i]));
3504
+ const lineCount = Math.max(...cellLines.map((l) => l.length));
3505
+ for (let line = 0;line < lineCount; line++) {
3506
+ const row = keys.map((_, i) => {
3507
+ const val = line < cellLines[i].length ? cellLines[i][line] : "";
3508
+ return val.padEnd(finalWidths[i]);
3509
+ }).join(" | ");
3510
+ logFn(styleLine(row, style));
3511
+ }
3512
+ });
3513
+ if (externalLogValue) {
3514
+ logFn("");
3515
+ logFn(`Log: ${externalLogValue}`);
3516
+ }
3517
+ }
3518
+ var MARKDOWN_MAX_CELL = 200;
3519
+ var MARKDOWN_MAX_DEPTH = 3;
3520
+ function markdownHeading(depth) {
3521
+ return "#".repeat(Math.min(3 + depth, 6));
3522
+ }
3523
+ var BACKTICK_RUN = /`+/g;
3524
+ function fencedBlock(text) {
3525
+ const first = text.trimStart()[0];
3526
+ const language = first === "<" ? "xml" : first === "{" || first === "[" ? "json" : "";
3527
+ const longestRun = Math.max(0, ...Array.from(text.matchAll(BACKTICK_RUN), (match) => match[0].length));
3528
+ const fence = "`".repeat(Math.max(3, longestRun + 1));
3529
+ return `${fence}${language}
3530
+ ${text}
3531
+ ${fence}`;
3532
+ }
3533
+ function collapseNewlineRuns(text) {
3534
+ return text.split(/(\s+)/).map((part, index) => index % 2 === 1 && part.includes(`
3535
+ `) ? " " : part).join("");
3536
+ }
3537
+ function markdownCell(value) {
3538
+ const text = value instanceof Date ? value.toISOString() : cellToString(value);
3539
+ return collapseNewlineRuns(text).replace(/\|/g, "\\|");
3540
+ }
3541
+ function markdownLabel(key) {
3542
+ return collapseNewlineRuns(key).replace(/[\\`*|]/g, "\\$&");
3543
+ }
3544
+ function withoutPlumbing(record) {
3545
+ const kept = Object.create(null);
3546
+ for (const [key, value] of Object.entries(record)) {
3547
+ if (!isPlumbingKey(key))
3548
+ kept[key] = value;
3549
+ }
3550
+ return kept;
3551
+ }
3552
+ function rowsWithoutPlumbing(rows) {
3553
+ return rows.map((row) => isPlainRecord(row) ? withoutPlumbing(row) : row);
3554
+ }
3555
+ function markdownTable(rows) {
3556
+ const columns = [];
3557
+ const seen = new Set;
3558
+ for (const row of rows) {
3559
+ for (const key of Object.keys(row)) {
3560
+ if (!seen.has(key)) {
3561
+ seen.add(key);
3562
+ columns.push(key);
3563
+ }
3564
+ }
3565
+ }
3566
+ if (columns.length === 0)
3567
+ return null;
3568
+ const cells = rows.map((row) => columns.map((key) => markdownCell(row[key])));
3569
+ if (cells.some((row) => row.some((c) => c.length > MARKDOWN_MAX_CELL))) {
3570
+ return null;
3571
+ }
3572
+ return [
3573
+ `| ${columns.map(markdownLabel).join(" | ")} |`,
3574
+ `| ${columns.map(() => "---").join(" | ")} |`,
3575
+ ...cells.map((row) => `| ${row.join(" | ")} |`)
3576
+ ].join(`
3577
+ `);
3578
+ }
3579
+ function extractMessageSequence(rows) {
3580
+ const messages = [];
3581
+ for (const row of rows) {
3582
+ const message = extractSingleMessage(row);
3583
+ if (message === null)
3584
+ return null;
3585
+ messages.push(message);
3586
+ }
3587
+ return messages.join(`
3588
+
3589
+ `);
3590
+ }
3591
+ function markdownRows(rows, depth) {
3592
+ if (rows.length === 0)
3593
+ return "(none)";
3594
+ if (!isPlainObjectArray(rows)) {
3595
+ return rows.map((item) => `- ${markdownCell(item)}`).join(`
3596
+ `);
3597
+ }
3598
+ const prose = extractMessageSequence(rows);
3599
+ if (prose !== null)
3600
+ return prose;
3601
+ const table = markdownTable(rows);
3602
+ if (table !== null)
3603
+ return table;
3604
+ if (depth >= MARKDOWN_MAX_DEPTH) {
3605
+ return fencedBlock(JSON.stringify(rows, null, 2));
3606
+ }
3607
+ return rows.map((row, index) => [
3608
+ `${markdownHeading(depth)} ${index + 1}`,
3609
+ markdownObject(row, depth + 1)
3610
+ ].join(`
3611
+
3612
+ `)).join(`
3613
+
3614
+ `);
3615
+ }
3616
+ function markdownObject(obj, depth) {
3617
+ const scalars = [];
3618
+ const blocks = [];
3619
+ for (const [key, value] of Object.entries(obj)) {
3620
+ if (value === undefined)
3621
+ continue;
3622
+ const label = markdownLabel(key);
3623
+ if (Array.isArray(value)) {
3624
+ blocks.push(`${markdownHeading(depth)} ${label}
3625
+
3626
+ ${markdownRows(value, depth + 1)}`);
3627
+ } else if (isNonEmptyPlainObject(value)) {
3628
+ const nested = depth < MARKDOWN_MAX_DEPTH ? markdownObject(value, depth + 1) : fencedBlock(JSON.stringify(value, null, 2));
3629
+ if (nested !== "") {
3630
+ blocks.push(`${markdownHeading(depth)} ${label}
3631
+
3632
+ ${nested}`);
3633
+ }
3634
+ } else if (typeof value === "string" && value.includes(`
3635
+ `)) {
3636
+ blocks.push(`**${label}:**
3637
+
3638
+ ${fencedBlock(value)}`);
3639
+ } else {
3640
+ scalars.push(`**${label}:** ${markdownCell(value)}`);
3641
+ }
3642
+ }
3643
+ const sections = scalars.length > 0 ? [scalars.join(`
3644
+ `)] : [];
3645
+ sections.push(...blocks);
3646
+ return sections.join(`
3647
+
3648
+ `);
3649
+ }
3650
+ function extractSingleMessage(payload) {
3651
+ if (!isPlainRecord(payload))
3652
+ return null;
3653
+ const keys = Object.keys(payload);
3654
+ if (keys.length !== 1 || keys[0].toLowerCase() !== "message")
3655
+ return null;
3656
+ const value = payload[keys[0]];
3657
+ return typeof value === "string" ? value : null;
3658
+ }
3659
+ function markdownPayload(payload) {
3660
+ const message = extractSingleMessage(payload);
3661
+ if (message !== null)
3662
+ return message;
3663
+ if (Array.isArray(payload)) {
3664
+ return markdownRows(rowsWithoutPlumbing(payload), 0);
3665
+ }
3666
+ const visible = withoutPlumbing(payload);
3667
+ const paged = splitPagedEnvelope(visible);
3668
+ if (paged !== null) {
3669
+ const meta = markdownObject(paged.meta, 0);
3670
+ const rows = `${markdownHeading(0)} ${markdownLabel(paged.key)}
3671
+
3672
+ ${markdownRows(rowsWithoutPlumbing(paged.rows), 1)}`;
3673
+ return meta === "" ? rows : `${meta}
3674
+
3675
+ ${rows}`;
3676
+ }
3677
+ return markdownObject(visible, 0);
3678
+ }
3679
+ function isPaginationWorthShowing(value) {
3680
+ if (typeof value !== "object" || value === null)
3681
+ return false;
3682
+ const page = value;
3683
+ return page.HasMore === true || typeof page.Offset === "number" && page.Offset > 0;
3684
+ }
3685
+ function markdownEnvelopeNotes(data) {
3686
+ const envelope = data;
3687
+ const notes = [];
3688
+ const warning = envelope.Warning;
3689
+ if (typeof warning === "string" && warning !== "") {
3690
+ notes.push(`> **Warning:** ${warning}`);
3691
+ }
3692
+ const instructions = envelope.Instructions;
3693
+ if (typeof instructions === "string" && instructions !== "") {
3694
+ notes.push(`> ${instructions}`);
3695
+ }
3696
+ const pagination = envelope.Pagination;
3697
+ if (isPaginationWorthShowing(pagination)) {
3698
+ const body = markdownObject(pagination, 1);
3699
+ if (body !== "") {
3700
+ notes.push(`${markdownHeading(0)} Pagination
3701
+
3702
+ ${body}`);
3703
+ }
3704
+ }
3705
+ const log = envelope.Log;
3706
+ if (typeof log === "string" && log !== "") {
3707
+ notes.push(`**Log:** ${log}`);
3708
+ }
3709
+ return notes;
3710
+ }
3711
+ function renderMarkdown(data) {
3712
+ if (data.Result !== RESULTS.Success) {
3713
+ const failure = data;
3714
+ const sections = [`**Failed:** ${failure.Message}`];
3715
+ if (failure.Data != null) {
3716
+ sections.push(markdownPayload(failure.Data));
3717
+ }
3718
+ if (failure.Instructions) {
3719
+ sections.push(`> ${failure.Instructions}`);
3720
+ }
3721
+ return sections.filter((section) => section !== "").join(`
3722
+
3723
+ `);
3724
+ }
3725
+ if (!("Data" in data) || data.Data == null) {
3726
+ return markdownObject(withoutPlumbing(data), 0);
3727
+ }
3728
+ return [markdownPayload(data.Data), ...markdownEnvelopeNotes(data)].filter((section) => section !== "").join(`
3729
+
3730
+ `);
3731
+ }
3732
+ function toYaml(data) {
3733
+ const codec = getYamlCodec();
3734
+ if (!codec) {
3735
+ throw new Error("YAML output requested before the YAML codec was loaded. " + "Call loadOutputCodecsAsync({ yaml: true }) first.");
3736
+ }
3737
+ return codec.dump(data);
3738
+ }
3739
+ function requireJmespath() {
3740
+ const codec = getJmespathCodec();
3741
+ if (!codec) {
3742
+ throw new Error("An --output-filter was applied before the JMESPath codec was loaded. " + "Call loadOutputCodecsAsync({ filter: true }) first.");
3743
+ }
3744
+ return codec;
3745
+ }
3746
+
3747
+ class FilterEvaluationError extends Error {
3748
+ __brand = "FilterEvaluationError";
3749
+ filter;
3750
+ errorCode = "invalid_argument";
3751
+ instructions;
3752
+ retry = "RetryWillNotFix";
3753
+ result = RESULTS.ValidationError;
3754
+ constructor(filter, cause) {
3755
+ const underlying = cause instanceof Error ? cause.message : String(cause);
3756
+ super(`Filter '${filter}' failed to evaluate: ${underlying}`);
3757
+ this.name = "FilterEvaluationError";
3758
+ this.filter = filter;
3759
+ this.instructions = `The --output-filter expression '${filter}' failed at evaluation time. ` + "Note that --output-filter operates on the 'Data' field of the envelope, not the full object. " + "For example, on a list result use 'length(@)' instead of 'Data | length(@)'.";
3760
+ }
3761
+ }
3762
+
3763
+ class FilterImplicitLimitError extends Error {
3764
+ __brand = "FilterImplicitLimitError";
3765
+ errorCode = "invalid_argument";
3766
+ instructions;
3767
+ retry = "RetryWillNotFix";
3768
+ result = RESULTS.ValidationError;
3769
+ constructor(defaultLimit) {
3770
+ super(`--output-filter requires an explicit --limit: this command defaults to --limit ${defaultLimit}, ` + `so the filter would silently apply to only the first ${defaultLimit} records.`);
3771
+ this.name = "FilterImplicitLimitError";
3772
+ this.instructions = "Pass --limit <n> to choose how many records the filter applies to. " + "To filter over all records, pass the command's maximum accepted --limit (see the option's description in --help).";
3773
+ }
3774
+ }
3775
+ function countRecords(data) {
3776
+ if (Array.isArray(data))
3777
+ return data.length;
3778
+ return data == null ? 0 : 1;
3779
+ }
3780
+ function availableFields(data) {
3781
+ const records = Array.isArray(data) ? data : [data];
3782
+ const keys = new Set;
3783
+ for (const record of records) {
3784
+ if (record && typeof record === "object" && !Array.isArray(record)) {
3785
+ for (const key of Object.keys(record))
3786
+ keys.add(key);
3787
+ }
3788
+ }
3789
+ return [...keys];
3790
+ }
3791
+ function decodeQuotedIdentifier(whole, inner) {
3792
+ const [error, decoded] = catchError(() => JSON.parse(whole));
3793
+ if (!error && typeof decoded === "string")
3794
+ return decoded;
3795
+ return inner.replace(/\\(.)/g, "$1");
3796
+ }
3797
+ function referencedFields(filter) {
3798
+ const top = new Set;
3799
+ const nested = new Set;
3800
+ const withoutValueLiterals = filter.replace(/'(?:\\.|[^'\\])*'/g, " ").replace(/`(?:\\.|[^`\\])*`/g, " ");
3801
+ const isPathTail = (text, index) => text[index - 1] === "." && /[A-Za-z0-9_"]/.test(text[index - 2] ?? "");
3802
+ const quoted = [];
3803
+ const withoutLiterals = withoutValueLiterals.replace(/"((?:\\.|[^"\\])*)"/g, (whole, name, index) => {
3804
+ const isAlias = /^\s*:/.test(withoutValueLiterals.slice(index + whole.length));
3805
+ if (!isAlias) {
3806
+ quoted.push({
3807
+ name: decodeQuotedIdentifier(whole, name),
3808
+ index,
3809
+ tail: isPathTail(withoutValueLiterals, index)
3810
+ });
3811
+ }
3812
+ return `"${" ".repeat(whole.length - 2)}"`;
3813
+ });
3814
+ const descent = /[A-Za-z0-9_"]\s*[.[]/.exec(withoutLiterals);
3815
+ const rootEnd = descent ? descent.index + 1 : Number.POSITIVE_INFINITY;
3816
+ const place = (name, index, tail) => {
3817
+ if (tail || index >= rootEnd)
3818
+ nested.add(name);
3819
+ else
3820
+ top.add(name);
3821
+ };
3822
+ for (const entry of quoted)
3823
+ place(entry.name, entry.index, entry.tail);
3824
+ const identifiers = withoutLiterals.matchAll(/([A-Za-z_][A-Za-z0-9_]*)(\s*[:(])?/g);
3825
+ const reserved = new Set(["true", "false", "null", "and", "or", "not"]);
3826
+ for (const match of identifiers) {
3827
+ const [, name, trailing] = match;
3828
+ if (trailing || reserved.has(name))
3829
+ continue;
3830
+ place(name, match.index, isPathTail(withoutLiterals, match.index));
3831
+ }
3832
+ return {
3833
+ top: [...top],
3834
+ nested: [...nested].filter((name) => !top.has(name)),
3835
+ hasPredicate: /\[\s*\?/.test(withoutValueLiterals)
3836
+ };
3837
+ }
3838
+ function appearsBelowTopLevel(data, name) {
3839
+ let budget = 2000;
3840
+ const visit = (value, depth) => {
3841
+ if (budget-- <= 0 || depth > 4)
3842
+ return false;
3843
+ if (value === null || typeof value !== "object")
3844
+ return false;
3845
+ if (Array.isArray(value))
3846
+ return value.some((entry) => visit(entry, depth));
3847
+ const record = value;
3848
+ if (depth > 0 && Object.hasOwn(record, name))
3849
+ return true;
3850
+ return Object.values(record).some((entry) => visit(entry, depth + 1));
3851
+ };
3852
+ return visit(data, 0);
3853
+ }
3854
+ function alwaysNullKeys(records) {
3855
+ const objects = records.filter((r) => r != null && typeof r === "object" && !Array.isArray(r));
3856
+ if (objects.length === 0 || objects.length !== records.length)
3857
+ return [];
3858
+ const keys = [...new Set(objects.flatMap((o) => Object.keys(o)))];
3859
+ if (keys.length === 0)
3860
+ return [];
3861
+ const nullKeys = keys.filter((key) => objects.every((record) => record[key] === null));
3862
+ return nullKeys.length === keys.length ? nullKeys : [];
3863
+ }
3864
+ function carriesOnlyNulls(value) {
3865
+ if (value === null)
3866
+ return true;
3867
+ if (Array.isArray(value)) {
3868
+ return value.length > 0 && value.every(carriesOnlyNulls);
3869
+ }
3870
+ if (typeof value === "object" && value !== undefined) {
3871
+ const values = Object.values(value);
3872
+ return values.length > 0 && values.every(carriesOnlyNulls);
3873
+ }
3874
+ return false;
3875
+ }
3876
+ function nameList(names, cap = 12) {
3877
+ const shown = names.slice(0, cap).map((n) => `\`${n}\``);
3878
+ const rest = names.length - shown.length;
3879
+ return shown.join(", ") + (rest > 0 ? `, and ${rest} more` : "");
3880
+ }
3881
+ function buildFilterWarning(filter, data, outcome) {
3882
+ const present = availableFields(data);
3883
+ const refs = referencedFields(filter);
3884
+ const unknown = refs.top.filter((name) => !present.includes(name) && !appearsBelowTopLevel(data, name));
3885
+ const unchecked = refs.nested.filter((name) => !present.includes(name));
3886
+ const count = countRecords(data);
3887
+ const scope = `${count} record(s)`;
3888
+ const isNotAField = (names) => `${nameList(names)} ${names.length === 1 ? "is not a field" : "are not fields"} on the ${scope} it read`;
3889
+ const soundness = unchecked.length > 0 ? `${nameList(unchecked)} ${unchecked.length === 1 ? "reads" : "read"} below the top level, so ${unchecked.length === 1 ? "it was" : "they were"} not checked against the record keys` : refs.top.length > 0 ? "every field it names exists" : "";
3890
+ const withSoundness = (base) => soundness ? `${base}, and ${soundness}` : base;
3891
+ let detail;
3892
+ let lede;
3893
+ if (outcome.kind === "null-elements") {
3894
+ lede = "returned only null values";
3895
+ const projected = `all ${outcome.count} of the elements it projected are null`;
3896
+ if (unknown.length > 0) {
3897
+ detail = `${projected}, because ${isNotAField(unknown)}`;
3898
+ } else if (unchecked.length > 0) {
3899
+ detail = withSoundness(projected);
3900
+ } else {
3901
+ detail = `${projected}, and every field it names exists — a multi-select list ` + `(\`[A, B]\`) reads each entry against \`Data\` itself, so on a list ` + `result use \`[].[A, B]\` or \`[].{a: A, b: B}\` to read the records`;
3902
+ }
3903
+ } else if (outcome.kind === "null-rows") {
3904
+ lede = "returned only null values";
3905
+ const projected = `every value it projected is null on all ${outcome.count} row(s)`;
3906
+ detail = unknown.length > 0 ? `${projected}, because ${isNotAField(unknown)}` : withSoundness(projected);
3907
+ } else if (outcome.kind === "null-values") {
3908
+ lede = "returned only null values";
3909
+ const projected = `every key it projected (${nameList(outcome.keys)}) is null`;
3910
+ const sameSet = unknown.length === outcome.keys.length && outcome.keys.every((k) => unknown.includes(k));
3911
+ if (sameSet) {
3912
+ detail = `${isNotAField(outcome.keys)}, so every key it projected is null`;
3913
+ } else if (unknown.length > 0) {
3914
+ detail = `${projected}, because ${isNotAField(unknown)}`;
3915
+ } else {
3916
+ detail = withSoundness(`${projected} on all ${scope}`);
3917
+ }
3918
+ } else {
3919
+ lede = "returned nothing";
3920
+ if (unknown.length > 0) {
3921
+ detail = isNotAField(unknown);
3922
+ } else {
3923
+ const selection = refs.hasPredicate ? "no record matched" : "the expression resolved to no value";
3924
+ detail = withSoundness(`${selection} — it read ${scope}`);
3925
+ }
3926
+ }
3927
+ const fields = present.length > 0 ? ` Available fields: ${nameList(present)}.` : "";
3928
+ return `--output-filter ${JSON.stringify(filter)} ${lede}: ${detail}.${fields}`;
3929
+ }
3930
+ function appendWarning(existing, note) {
3931
+ return existing ? `${existing} ${note}` : note;
3932
+ }
3933
+ function applyFilter(data, filter, onWarning) {
3934
+ const codec = requireJmespath();
3935
+ let result;
3936
+ try {
3937
+ result = codec.search(data, filter);
3938
+ } catch (err) {
3939
+ throw new FilterEvaluationError(filter, err);
3940
+ }
3941
+ const inputCount = countRecords(data);
3942
+ const warn = (outcome) => {
3943
+ if (inputCount === 0)
3944
+ return;
3945
+ const note = buildFilterWarning(filter, data, outcome);
3946
+ getOutputSink().writeErr(`[WARN] ${note}
3947
+ `);
3948
+ onWarning?.(note);
3949
+ };
3950
+ const warnIfAllNull = (records) => {
3951
+ const keys = alwaysNullKeys(records);
3952
+ if (keys.length > 0)
3953
+ warn({ kind: "null-values", keys });
3954
+ };
3955
+ if (result == null) {
3956
+ warn({ kind: "empty" });
3957
+ return [];
3958
+ }
3959
+ if (Array.isArray(result)) {
3960
+ if (result.length === 0) {
3961
+ warn({ kind: "empty" });
3962
+ } else if (result.every((entry) => entry === null)) {
3963
+ warn({ kind: "null-elements", count: result.length });
3964
+ } else if (result.every((entry) => Array.isArray(entry)) && carriesOnlyNulls(result)) {
3965
+ warn({ kind: "null-rows", count: result.length });
3966
+ } else {
3967
+ warnIfAllNull(result);
3968
+ }
3969
+ if (result.length > 0 && typeof result[0] !== "object") {
3970
+ const fieldMatch = filter.match(/\.(\w+)$/);
3971
+ const key = fieldMatch ? fieldMatch[1] : "Value";
3972
+ return result.map((v) => ({ [key]: v }));
3973
+ }
3974
+ return result;
3975
+ }
3976
+ if (typeof result === "object") {
3977
+ warnIfAllNull([result]);
3978
+ return result;
3979
+ }
3980
+ return { Value: result };
3981
+ }
3982
+ function filterFailureData(envelope) {
3983
+ const filter = getOutputFilter();
3984
+ const data = envelope.Data;
3985
+ if (!filter || data == null)
3986
+ return;
3987
+ let note;
3988
+ const [filterError, filtered] = catchError(() => applyFilter(data, filter, (n) => {
3989
+ note = n;
3990
+ }));
3991
+ if (filterError) {
3992
+ envelope.Warning = appendWarning(envelope.Warning, `--output-filter was not applied, so Data is shown in full: ${filterError.message}`);
3993
+ return;
3994
+ }
3995
+ envelope.Data = filtered;
3996
+ if (note) {
3997
+ envelope.Warning = appendWarning(envelope.Warning, note);
3998
+ }
3999
+ }
4000
+ function defaultErrorCodeForResult(result) {
4001
+ switch (result) {
4002
+ case RESULTS.AuthenticationError:
4003
+ return "authentication_required";
4004
+ case RESULTS.ConfigError:
4005
+ return "configuration_error";
4006
+ case RESULTS.ValidationError:
4007
+ return "invalid_argument";
4008
+ case RESULTS.TimeoutError:
4009
+ return "timeout";
4010
+ default:
4011
+ return "unknown_error";
4012
+ }
4013
+ }
4014
+ function parseHttpStatusFromMessage(message) {
4015
+ const match = /^HTTP\s+(\d{3})(?::|\s|-|$)/i.exec(message.trim());
4016
+ if (!match)
4017
+ return;
4018
+ const status = Number(match[1]);
4019
+ return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
4020
+ }
4021
+ function defaultErrorCodeForHttpStatus(status) {
4022
+ if (status === undefined)
4023
+ return;
4024
+ if (status === 400 || status === 409 || status === 422) {
4025
+ return "invalid_argument";
4026
+ }
4027
+ if (status === 401)
4028
+ return "authentication_required";
4029
+ if (status === 403)
4030
+ return "permission_denied";
4031
+ if (status === 404)
4032
+ return "not_found";
4033
+ if (status === 405)
4034
+ return "method_not_allowed";
4035
+ if (status === 408)
4036
+ return "timeout";
4037
+ if (status === 429)
4038
+ return "rate_limited";
4039
+ if (status >= 500 && status < 600)
4040
+ return "server_error";
4041
+ return;
4042
+ }
4043
+ var LOCAL_PERMISSION_TEXT_PATTERN = new RegExp(`(?:\\b|\\()(?:${[...LOCAL_PERMISSION_ERROR_CODES].join("|")})(?::\\s|\\))`);
4044
+ function defaultErrorCodeForFailure(data) {
4045
+ if (data.Result === RESULTS.Failure) {
4046
+ const status = data.Context?.httpStatus ?? parseHttpStatusFromMessage(data.Message);
4047
+ const errorCode = defaultErrorCodeForHttpStatus(status);
4048
+ if (errorCode)
4049
+ return errorCode;
4050
+ if (status === undefined && (LOCAL_PERMISSION_TEXT_PATTERN.test(data.Message) || LOCAL_PERMISSION_TEXT_PATTERN.test(data.Instructions))) {
4051
+ return "local_permission_denied";
4052
+ }
4053
+ }
4054
+ return defaultErrorCodeForResult(data.Result);
4055
+ }
4056
+ function defaultRetryForErrorCode(errorCode) {
4057
+ switch (errorCode) {
4058
+ case "network_error":
4059
+ case "rate_limited":
4060
+ case "server_error":
4061
+ case "timeout":
4062
+ return "RetryLater";
4063
+ default:
4064
+ return "RetryWillNotFix";
4065
+ }
4066
+ }
4067
+ var OutputFormatter;
4068
+ ((OutputFormatter) => {
4069
+ function success(data, options) {
4070
+ data.Log ??= getLogFilePath() || undefined;
4071
+ const normalize = options?.preserveDataKeys !== true;
4072
+ const verbatim = toVerbatimKeySet(options?.preserveDataKeys);
4073
+ const subtrees = verbatim && {
4074
+ refs: new Set,
4075
+ mode: "collect"
4076
+ };
4077
+ if (normalize) {
4078
+ data.Data = normalizeDataKeys(data.Data, verbatim, subtrees);
4079
+ }
4080
+ const filter = getOutputFilter();
4081
+ if (filter) {
4082
+ let note;
4083
+ const filtered = applyFilter(data.Data, filter, (n) => {
4084
+ note = n;
4085
+ });
4086
+ data.Data = normalize ? normalizeDataKeys(filtered, verbatim, subtrees && { refs: subtrees.refs, mode: "skip" }) : filtered;
4087
+ if (note) {
4088
+ data.Warning = appendWarning(data.Warning, note);
4089
+ }
4090
+ }
4091
+ logOutput(normalizeOutputKeys(data), getOutputFormat(), options?.tableRowStyle);
4092
+ }
4093
+ OutputFormatter.success = success;
4094
+ function error(data) {
4095
+ data.Log ??= getLogFilePath() || undefined;
4096
+ data.ErrorCode ??= defaultErrorCodeForFailure(data);
4097
+ data.Retry ??= defaultRetryForErrorCode(data.ErrorCode);
4098
+ const exitCode = EXIT_CODES[data.Result] ?? 1;
4099
+ setExitCode(exitCode);
4100
+ recordCommandFailureTelemetry({
4101
+ result: data.Result,
4102
+ errorCode: data.ErrorCode,
4103
+ retry: data.Retry,
4104
+ message: data.Message,
4105
+ context: data.Context,
4106
+ exitCode,
4107
+ errorClass: data.TelemetryErrorClass,
4108
+ terminalOutcome: data.TelemetryTerminalOutcome,
4109
+ terminalSignal: data.TelemetryTerminalSignal
4110
+ });
4111
+ const suppressTelemetry = data.SuppressTelemetry === true;
4112
+ const envelope = { ...data };
4113
+ delete envelope.SuppressTelemetry;
4114
+ delete envelope.TelemetryErrorClass;
4115
+ delete envelope.TelemetryTerminalOutcome;
4116
+ delete envelope.TelemetryTerminalSignal;
4117
+ filterFailureData(envelope);
4118
+ if (!suppressTelemetry) {
4119
+ telemetry.trackEvent(CommonTelemetryEvents.Error, {
4120
+ [ErrorDimensions.Result]: data.Result,
4121
+ [ErrorDimensions.ErrorCode]: data.ErrorCode,
4122
+ [ErrorDimensions.Retry]: data.Retry,
4123
+ [ErrorDimensions.ErrorMessage]: data.Message
4124
+ });
4125
+ }
4126
+ logOutput(normalizeOutputKeys(envelope), getOutputFormat());
4127
+ }
4128
+ OutputFormatter.error = error;
4129
+ function emitList(code, items, opts) {
4130
+ const data = {
4131
+ Result: RESULTS.Success,
4132
+ Code: code,
4133
+ Data: items
4134
+ };
4135
+ if (items.length === 0 && opts?.emptyInstructions) {
4136
+ data.Instructions = opts.emptyInstructions;
4137
+ }
4138
+ if (opts?.warning) {
4139
+ data.Warning = opts.warning;
4140
+ }
4141
+ if (opts?.pagination) {
4142
+ data.Pagination = opts.pagination;
4143
+ }
4144
+ success(data);
4145
+ }
4146
+ OutputFormatter.emitList = emitList;
4147
+ function log(data) {
4148
+ const format = getOutputFormat();
4149
+ const sink = getOutputSink();
4150
+ const normalized = toPascalCaseData(data);
4151
+ if (format === "json") {
4152
+ const json = JSON.stringify(normalized);
4153
+ const safe = needsAsciiSafeJson(sink) ? escapeNonAscii(json) : json;
4154
+ sink.writeErr(`${safe}
4155
+ `);
4156
+ } else {
4157
+ for (const [key, value] of Object.entries(normalized)) {
4158
+ sink.writeErr(`${key}: ${value}
4159
+ `);
4160
+ }
4161
+ }
4162
+ }
4163
+ OutputFormatter.log = log;
4164
+ function formatToString(data) {
4165
+ const filter = getOutputFilter();
4166
+ const envelope = data;
4167
+ if ("Data" in data && data.Data != null) {
4168
+ data.Data = normalizeDataKeys(data.Data);
4169
+ if (filter) {
4170
+ let note;
4171
+ data.Data = normalizeDataKeys(applyFilter(data.Data, filter, (n) => {
4172
+ note = n;
4173
+ }));
4174
+ if (note) {
4175
+ envelope.Warning = appendWarning(envelope.Warning, note);
4176
+ }
4177
+ }
4178
+ }
4179
+ const output = normalizeOutputKeys(envelope);
4180
+ const lines = [];
4181
+ const sink = getOutputSink();
4182
+ printOutput(output, getOutputFormat(), (msg) => {
4183
+ lines.push(msg);
4184
+ }, needsAsciiSafeJson(sink));
4185
+ return lines.join(`
4186
+ `);
4187
+ }
4188
+ OutputFormatter.formatToString = formatToString;
4189
+ })(OutputFormatter ||= {});
4190
+ // ../common/src/command-examples.ts
4191
+ var examplesByCommand = new WeakMap;
4192
+ Command.prototype.examples = function(examples) {
4193
+ examplesByCommand.set(this, examples);
4194
+ return this;
4195
+ };
4196
+ // ../common/src/preview.ts
4197
+ var previewSlot = singleton("PreviewBuild");
4198
+ function isPreviewBuild() {
4199
+ return previewSlot.get(false) ?? false;
4200
+ }
4201
+ Command.prototype.previewCommand = function(nameAndArgs, opts) {
4202
+ if (isPreviewBuild()) {
4203
+ return this.command(nameAndArgs, opts);
4204
+ }
4205
+ return new Command(nameAndArgs.split(/\s+/)[0] ?? nameAndArgs);
4206
+ };
4207
+
4208
+ // ../common/src/telemetry/command-name.ts
4209
+ var TELEMETRY_NAME_ROOT = "Cli";
4210
+ var CLI_COMMAND_ROOT = "uip";
4211
+ var TELEMETRY_NAME_BARE_ACTION = "Invoke";
4212
+ function commandTelemetryName(parts) {
4213
+ const action = vetCommandTokens(parts).map(pascalizeToken).join("");
4214
+ return `${TELEMETRY_NAME_ROOT}.${action || TELEMETRY_NAME_BARE_ACTION}`;
4215
+ }
4216
+ function commandInvocationPath(parts) {
4217
+ return [CLI_COMMAND_ROOT, ...vetCommandTokens(parts)].join(" ");
4218
+ }
4219
+ function vetCommandTokens(parts) {
4220
+ const tokens = [];
4221
+ for (const part of parts) {
4222
+ const pieces = String(part ?? "").split(/\s+/).filter((token) => token && !token.startsWith("-") && token !== CLI_COMMAND_ROOT);
4223
+ if (pieces.every(isCommandToken)) {
4224
+ tokens.push(...pieces);
4225
+ continue;
4226
+ }
4227
+ tokens.push(UNKNOWN_TOKEN);
4228
+ }
4229
+ return tokens;
4230
+ }
4231
+ function pascalizeToken(token) {
4232
+ return token.split("-").filter(Boolean).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
4233
+ }
4234
+ var COMMAND_TOKEN_PATTERN = /^[a-z][a-z0-9-]*$/;
4235
+ var MAX_COMMAND_TOKEN_LENGTH = 32;
4236
+ var GUID_TOKEN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
4237
+ function isCommandToken(token) {
4238
+ return token.length <= MAX_COMMAND_TOKEN_LENGTH && COMMAND_TOKEN_PATTERN.test(token) && !GUID_TOKEN.test(token);
4239
+ }
4240
+ var UNKNOWN_TOKEN = "unknown";
4241
+
4242
+ // ../common/src/telemetry/invocation-request.ts
4243
+ var requestContextSlot = singleton("TelemetryInvocationRequestContext");
4244
+ function activeContext() {
4245
+ return telemetry.getActiveContext?.();
4246
+ }
4247
+ function runWithInvocationRequest(fn) {
4248
+ const context = telemetry.createRequestContext();
4249
+ context.startedAt = invocationStartedAt();
4250
+ requestContextSlot.set(context);
4251
+ return telemetry.runWithContext(context, fn);
4252
+ }
4253
+ function ensureInvocationRequestScope(fn) {
4254
+ if (activeContext() !== undefined) {
4255
+ return fn();
4256
+ }
4257
+ const kept = requestContextSlot.get();
4258
+ return kept === undefined ? runWithInvocationRequest(fn) : telemetry.runWithContext(kept, fn);
4259
+ }
4260
+ function getInvocationRequestContext() {
4261
+ return activeContext() ?? requestContextSlot.get();
4262
+ }
4263
+ function emitInvocationRequest(name, success, properties) {
4264
+ const context = getInvocationRequestContext();
4265
+ telemetry.trackRequestResult(name, invocationElapsedMs(), success, properties, context);
4266
+ if (context !== undefined && requestContextSlot.get() === context) {
4267
+ requestContextSlot.clear();
4268
+ }
4269
+ }
4270
+
4271
+ // ../common/src/trackedAction.ts
4272
+ var pollSignalSlot = singleton("PollSignal");
4273
+ var TELEMETRY_COMMAND_ARG_PREFIX = "uip.cmd.arg.";
4274
+ var processContext = {
4275
+ exit: (code) => {
4276
+ recordExitCode(code);
4277
+ setExitCode(code);
4278
+ },
4279
+ get pollSignal() {
4280
+ return pollSignalSlot.get();
4281
+ }
4282
+ };
4283
+ var TELEMETRY_ARG_VALUE_WITHHELD = "<provided>";
4284
+ var TELEMETRY_ARG_VALUE_DEFAULTED = "<default>";
4285
+ function recordableArgValue(value, choices) {
4286
+ if (typeof value === "boolean" || typeof value === "number") {
4287
+ return value;
4288
+ }
4289
+ if (choices && choices.length > 0) {
4290
+ if (typeof value === "string" && choices.includes(value)) {
4291
+ return value;
4292
+ }
4293
+ if (Array.isArray(value) && value.length > 0 && value.every((entry) => typeof entry === "string" && choices.includes(entry))) {
4294
+ return value.join(",");
4295
+ }
4296
+ }
4297
+ return TELEMETRY_ARG_VALUE_WITHHELD;
4298
+ }
4299
+ function extractCommandParams(cmd) {
4300
+ const params = {};
4301
+ forEachSuppliedArgument(cmd, (name, value, choices, defaulted) => {
4302
+ const recordable = recordableArgValue(value, choices);
4303
+ params[`${TELEMETRY_COMMAND_ARG_PREFIX}${name}`] = recordable === TELEMETRY_ARG_VALUE_WITHHELD && defaulted ? TELEMETRY_ARG_VALUE_DEFAULTED : recordable;
4304
+ });
4305
+ return params;
4306
+ }
4307
+ function isDefaultedOption(cmd, name) {
4308
+ const source = cmd.getOptionValueSource?.(name);
4309
+ return source === "default" || source === "implied";
4310
+ }
4311
+ function isDefaultedPositional(cmd, index) {
4312
+ return index >= (cmd.args?.length ?? 0);
4313
+ }
4314
+ function forEachSuppliedArgument(cmd, visit) {
4315
+ const registered = cmd.registeredArguments ?? [];
4316
+ const processed = cmd.processedArgs ?? [];
4317
+ for (let i = 0;i < registered.length; i++) {
4318
+ const name = registered[i].name();
4319
+ if (name && processed[i] !== undefined) {
4320
+ visit(name, processed[i], registered[i].argChoices, isDefaultedPositional(cmd, i));
4321
+ }
4322
+ }
4323
+ const choicesByAttribute = new Map;
4324
+ for (const option of cmd.options) {
4325
+ choicesByAttribute.set(option.attributeName(), option.argChoices);
4326
+ }
4327
+ for (const [key, value] of Object.entries(cmd.opts())) {
4328
+ if (key && value !== undefined) {
4329
+ visit(key, value, choicesByAttribute.get(key), isDefaultedOption(cmd, key));
4330
+ }
4331
+ }
4332
+ }
4333
+ function withheldArgumentValues(cmd) {
4334
+ const values = [];
4335
+ forEachSuppliedArgument(cmd, (_name, value, choices, defaulted) => {
4336
+ if (defaulted) {
4337
+ return;
4338
+ }
4339
+ if (recordableArgValue(value, choices) === TELEMETRY_ARG_VALUE_WITHHELD) {
4340
+ values.push(value);
4341
+ }
4342
+ });
4343
+ return values;
4344
+ }
4345
+ function deriveCommandParts(cmd) {
4346
+ const parts = [];
4347
+ let current = cmd;
4348
+ while (current) {
4349
+ const name = current.name();
4350
+ if (name) {
4351
+ parts.unshift(name);
4352
+ }
4353
+ current = current.parent;
4354
+ }
4355
+ if (parts.length > 1) {
4356
+ parts.shift();
4357
+ }
4358
+ return parts;
4359
+ }
4360
+ function isErrorContext(value) {
4361
+ return value !== null && typeof value === "object";
4362
+ }
4363
+ function commandHelpHint(commandPath) {
4364
+ return `An unexpected error occurred. Run '${commandPath} --help' to verify command syntax, or run with --log-level debug for details.`;
4365
+ }
4366
+ function isPromptCancellation(error) {
4367
+ return error instanceof Error && error.name === "ExitPromptError";
4368
+ }
4369
+ function implicitLimitViolation(cmd) {
4370
+ if (getOutputFilter() === undefined) {
4371
+ return;
4372
+ }
4373
+ const hasLimit = cmd.options.some((o) => o.attributeName() === "limit");
4374
+ if (!hasLimit || cmd.getOptionValueSource("limit") !== "default") {
4375
+ return;
4376
+ }
4377
+ return new FilterImplicitLimitError(String(cmd.opts().limit));
4378
+ }
4379
+ function exitCodeFromProcess(fallback) {
4380
+ return typeof process.exitCode === "number" ? process.exitCode : fallback;
4381
+ }
4382
+ Command.prototype.trackedAction = function(context, fn, properties) {
4383
+ const command = this;
4384
+ return this.action(async (...args) => {
4385
+ await loadOutputCodecsAsync({
4386
+ yaml: getOutputFormat() === "yaml",
4387
+ filter: getOutputFilter() !== undefined
4388
+ });
4389
+ const commandParts = deriveCommandParts(command);
4390
+ const telemetryName = commandTelemetryName(commandParts);
4391
+ const commandPath = commandInvocationPath(commandParts);
4392
+ const props = typeof properties === "function" ? properties(...args) : properties;
4393
+ markCommandStart();
4394
+ const supplied = recordSuppliedArgumentValues(withheldArgumentValues(command));
4395
+ try {
4396
+ const startTime = performance.now();
4397
+ let errorMessage;
4398
+ let fallbackExitCode = EXIT_CODES.Success;
4399
+ clearRecordedCommandFailureTelemetry();
4400
+ const [error] = await catchError(ensureInvocationRequestScope(() => {
4401
+ const violation = implicitLimitViolation(command);
4402
+ if (violation) {
4403
+ return Promise.reject(violation);
4404
+ }
4405
+ return fn(...args);
4406
+ }));
4407
+ if (error) {
4408
+ errorMessage = error instanceof Error ? error.message : String(error);
4409
+ logger.debug(`[trackedAction] ${telemetryName} failed: ${errorMessage}`);
4410
+ const typed = error;
4411
+ const customInstructions = typeof typed.instructions === "string" ? typed.instructions : undefined;
4412
+ const customResult = typeof typed.result === "string" && typed.result !== RESULTS.Success && Object.values(RESULTS).includes(typed.result) ? typed.result : undefined;
4413
+ const finalResult = customResult ?? RESULTS.Failure;
4414
+ const typedErrorCode = typed.errorCode ?? typed.ErrorCode;
4415
+ const customErrorCode = isCliErrorCode(typedErrorCode) ? typedErrorCode : undefined;
4416
+ const typedRetry = typed.retry ?? typed.Retry;
4417
+ const customRetry = isRetryHint(typedRetry) ? typedRetry : undefined;
4418
+ const typedContext = typed.context ?? typed.Context;
4419
+ const customContext = isErrorContext(typedContext) ? typedContext : undefined;
4420
+ const cancellationExitCode = typed.exitCode === 130 || isPromptCancellation(error) ? 130 : undefined;
4421
+ fallbackExitCode = cancellationExitCode ?? EXIT_CODES[finalResult];
4422
+ OutputFormatter.error({
4423
+ Result: finalResult,
4424
+ ...customErrorCode ? { ErrorCode: customErrorCode } : {},
4425
+ Message: errorMessage,
4426
+ Instructions: customInstructions ?? commandHelpHint(commandPath),
4427
+ ...customRetry ? { Retry: customRetry } : {},
4428
+ ...customContext ? { Context: customContext } : {}
4429
+ });
4430
+ context.exit(fallbackExitCode);
4431
+ }
4432
+ const durationMs = performance.now() - startTime;
4433
+ recordCommandDuration(durationMs);
4434
+ const exitCode = fallbackExitCode === 130 ? fallbackExitCode : exitCodeFromProcess(fallbackExitCode);
4435
+ const recordedFailure = takeRecordedCommandFailureTelemetry();
4436
+ const success = !error && exitCode === 0;
4437
+ const terminalTelemetry = buildCommandTerminalTelemetryProperties({
4438
+ error,
4439
+ exitCode,
4440
+ recordedFailure,
4441
+ pollSignal: context.pollSignal
4442
+ });
4443
+ if (terminalTelemetry[CommandDimensions.ErrorClass] === "internal" && error) {
4444
+ telemetry.trackException(error instanceof Error ? error : new Error(String(error)), { [CommandDimensions.CommandName]: commandPath }, getInvocationRequestContext());
4445
+ }
4446
+ const commandParams = extractCommandParams(command);
4447
+ if (props) {
4448
+ for (const key of Object.keys(props)) {
4449
+ delete commandParams[`${TELEMETRY_COMMAND_ARG_PREFIX}${key}`];
4450
+ }
4451
+ }
4452
+ const baseProperties = redactProperties({
4453
+ ...commandParams,
4454
+ ...props,
4455
+ ...buildCommandTelemetryAttribution(commandPath, process.env.UIPATH_SKILL),
4456
+ ...buildAgentSessionTelemetry(process.env),
4457
+ [CommandDimensions.CommandName]: commandPath,
4458
+ [CommandDimensions.IsCommand]: "true",
4459
+ ...terminalTelemetry,
4460
+ ...errorMessage ? { [CommandDimensions.ErrorMessage]: errorMessage } : {}
4461
+ });
4462
+ emitInvocationRequest(telemetryName, success, baseProperties);
4463
+ } finally {
4464
+ releaseSuppliedArgumentValues(supplied);
4465
+ }
4466
+ });
4467
+ };
4468
+ // ../common/src/completer.ts
4469
+ var COMPLETER_SYMBOL = Symbol.for("@uipath/common/completer");
4470
+ // ../common/src/console-guard.ts
4471
+ var guardInstalledSlot = singleton("ConsoleGuardInstalled");
4472
+ var savedOriginalsSlot = singleton("ConsoleGuardOriginals");
4473
+ // ../common/src/constants.ts
4474
+ var DEFAULT_AUTH_TIMEOUT_MS = 5 * 60 * 1000;
4475
+ // ../common/src/entity-name-rules.ts
4476
+ var RESERVED_SQL_KEYWORDS_LOWER = new Set(["group", "order"]);
4477
+ var RESERVED_FIELD_NAMES_LOWER = new Set([
4478
+ "id",
4479
+ "createdby",
4480
+ "createtime",
4481
+ "updatedby",
4482
+ "updatetime",
4483
+ "recordowner",
4484
+ "version"
4485
+ ]);
4486
+ var RESERVED_KEYWORDS_LOWER = new Set([
4487
+ "abstract",
4488
+ "as",
4489
+ "base",
4490
+ "bool",
4491
+ "break",
4492
+ "byte",
4493
+ "case",
4494
+ "catch",
4495
+ "char",
4496
+ "checked",
4497
+ "class",
4498
+ "const",
4499
+ "continue",
4500
+ "decimal",
4501
+ "default",
4502
+ "delegate",
4503
+ "do",
4504
+ "double",
4505
+ "else",
4506
+ "enum",
4507
+ "event",
4508
+ "explicit",
4509
+ "extern",
4510
+ "false",
4511
+ "finally",
4512
+ "fixed",
4513
+ "float",
4514
+ "for",
4515
+ "foreach",
4516
+ "goto",
4517
+ "if",
4518
+ "implicit",
4519
+ "in",
4520
+ "int",
4521
+ "interface",
4522
+ "internal",
4523
+ "is",
4524
+ "lock",
4525
+ "long",
4526
+ "namespace",
4527
+ "new",
4528
+ "null",
4529
+ "object",
4530
+ "operator",
4531
+ "out",
4532
+ "override",
4533
+ "params",
4534
+ "private",
4535
+ "protected",
4536
+ "public",
4537
+ "readonly",
4538
+ "ref",
4539
+ "return",
4540
+ "sbyte",
4541
+ "sealed",
4542
+ "short",
4543
+ "sizeof",
4544
+ "stackalloc",
4545
+ "static",
4546
+ "string",
4547
+ "struct",
4548
+ "switch",
4549
+ "this",
4550
+ "throw",
4551
+ "true",
4552
+ "try",
4553
+ "typeof",
4554
+ "uint",
4555
+ "ulong",
4556
+ "unchecked",
4557
+ "unsafe",
4558
+ "ushort",
4559
+ "using",
4560
+ "virtual",
4561
+ "void",
4562
+ "volatile",
4563
+ "while",
4564
+ "addhandler",
4565
+ "addressof",
4566
+ "alias",
4567
+ "and",
4568
+ "andalso",
4569
+ "boolean",
4570
+ "byref",
4571
+ "byval",
4572
+ "call",
4573
+ "cbool",
4574
+ "cbyte",
4575
+ "cchar",
4576
+ "cdate",
4577
+ "cdbl",
4578
+ "cdec",
4579
+ "cint",
4580
+ "clng",
4581
+ "cobj",
4582
+ "csbyte",
4583
+ "cshort",
4584
+ "csng",
4585
+ "cstr",
4586
+ "ctype",
4587
+ "cuint",
4588
+ "culng",
4589
+ "cushort",
4590
+ "date",
4591
+ "declare",
4592
+ "dim",
4593
+ "directcast",
4594
+ "each",
4595
+ "elseif",
4596
+ "end",
4597
+ "endif",
4598
+ "erase",
4599
+ "error",
4600
+ "exit",
4601
+ "friend",
4602
+ "function",
4603
+ "get",
4604
+ "gettype",
4605
+ "getxmlnamespace",
4606
+ "global",
4607
+ "gosub",
4608
+ "goto",
4609
+ "handles",
4610
+ "implements",
4611
+ "imports",
4612
+ "inherits",
4613
+ "integer",
4614
+ "isnot",
4615
+ "let",
4616
+ "lib",
4617
+ "like",
4618
+ "loop",
4619
+ "me",
4620
+ "mod",
4621
+ "module",
4622
+ "mustinherit",
4623
+ "mustoverride",
4624
+ "mybase",
4625
+ "myclass",
4626
+ "narrowing",
4627
+ "next",
4628
+ "not",
4629
+ "nothing",
4630
+ "notinheritable",
4631
+ "notoverridable",
4632
+ "of",
4633
+ "on",
4634
+ "option",
4635
+ "optional",
4636
+ "or",
4637
+ "orelse",
4638
+ "overloads",
4639
+ "overridable",
4640
+ "overrides",
4641
+ "paramarray",
4642
+ "partial",
4643
+ "property",
4644
+ "raiseevent",
4645
+ "redim",
4646
+ "rem",
4647
+ "removehandler",
4648
+ "resume",
4649
+ "select",
4650
+ "set",
4651
+ "shadows",
4652
+ "shared",
4653
+ "single",
4654
+ "step",
4655
+ "stop",
4656
+ "structure",
4657
+ "sub",
4658
+ "synclock",
4659
+ "then",
4660
+ "to",
4661
+ "trycast",
4662
+ "uinteger",
4663
+ "ushort",
4664
+ "variant",
4665
+ "wend",
4666
+ "when",
4667
+ "widening",
4668
+ "with",
4669
+ "withevents",
4670
+ "writeonly",
4671
+ "xor"
4672
+ ]);
4673
+ // ../common/src/host-global-options.ts
4674
+ var HOST_GLOBAL_OPTIONS_WITH_VALUE = [
4675
+ "--output",
4676
+ "--output-filter",
4677
+ "--log-level",
4678
+ "--log-file",
4679
+ "--profile"
4680
+ ];
4681
+ var HOST_GLOBAL_FLAGS = [
4682
+ "--json",
4683
+ "--interactive",
4684
+ "--no-interactive"
4685
+ ];
4686
+ var VALUE_OPTIONS = new Set(HOST_GLOBAL_OPTIONS_WITH_VALUE);
4687
+ var BOOLEAN_FLAGS = new Set(HOST_GLOBAL_FLAGS);
4688
+ // ../common/src/interactivity-context.ts
4689
+ var modeSlot = singleton("InteractivityMode");
4690
+ var interactiveFlagSlot = singleton("InteractiveFlag");
4691
+ // ../common/src/mime-types.ts
4692
+ var MIME_TYPES_BY_EXTENSION = Object.freeze({
4693
+ pdf: "application/pdf",
4694
+ png: "image/png",
4695
+ jpg: "image/jpeg",
4696
+ jpeg: "image/jpeg",
4697
+ gif: "image/gif",
4698
+ webp: "image/webp",
4699
+ bmp: "image/bmp",
4700
+ tif: "image/tiff",
4701
+ tiff: "image/tiff",
4702
+ svg: "image/svg+xml",
4703
+ txt: "text/plain",
4704
+ log: "text/plain",
4705
+ md: "text/markdown",
4706
+ csv: "text/csv",
4707
+ tsv: "text/tab-separated-values",
4708
+ json: "application/json",
4709
+ xml: "application/xml",
4710
+ html: "text/html",
4711
+ htm: "text/html",
4712
+ yaml: "application/yaml",
4713
+ yml: "application/yaml",
4714
+ doc: "application/msword",
4715
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
4716
+ xls: "application/vnd.ms-excel",
4717
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
4718
+ ppt: "application/vnd.ms-powerpoint",
4719
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
4720
+ zip: "application/zip",
4721
+ mp3: "audio/mpeg",
4722
+ wav: "audio/wav",
4723
+ mp4: "video/mp4"
4724
+ });
4725
+ // ../common/src/package-metadata-options.ts
4726
+ function registerPackageMetadataOptions(command) {
4727
+ return command.option("--author <author>", "Package author").option("--description <text>", "Package description").option("--repository-url <url>", "Source repository URL (recorded in the package for traceability)").option("--repository-commit <sha>", "Source repository commit hash (recorded in the package for traceability)").option("--repository-branch <branch>", "Source repository branch").option("--repository-type <type>", "Source repository type (defaults to 'git' when --repository-url is set)").option("--release-notes <text>", "Release notes for the package").option("--project-url <url>", "Automation Hub idea URL");
4728
+ }
4729
+ function mapPackageMetadataOptions(opts) {
4730
+ const fields = {};
4731
+ if (opts.author !== undefined)
4732
+ fields.author = opts.author;
4733
+ if (opts.description !== undefined)
4734
+ fields.description = opts.description;
4735
+ if (opts.releaseNotes !== undefined)
4736
+ fields.releaseNotes = opts.releaseNotes;
4737
+ if (opts.projectUrl !== undefined)
4738
+ fields.projectUrl = opts.projectUrl;
4739
+ if (opts.repositoryUrl !== undefined)
4740
+ fields.repositoryUrl = opts.repositoryUrl;
4741
+ if (opts.repositoryCommit !== undefined)
4742
+ fields.repositoryCommit = opts.repositoryCommit;
4743
+ if (opts.repositoryBranch !== undefined)
4744
+ fields.repositoryBranch = opts.repositoryBranch;
4745
+ if (opts.repositoryType !== undefined)
4746
+ fields.repositoryType = opts.repositoryType;
4747
+ if (fields.repositoryUrl !== undefined && fields.repositoryType === undefined) {
4748
+ fields.repositoryType = "git";
4749
+ }
4750
+ return fields;
4751
+ }
4752
+ // ../common/src/polling/types.ts
4753
+ var PollOutcome = {
4754
+ Completed: "completed",
4755
+ Timeout: "timeout",
4756
+ Interrupted: "interrupted",
4757
+ Aborted: "aborted",
4758
+ Failed: "failed"
4759
+ };
4760
+
4761
+ // ../common/src/polling/poll-failure-mapping.ts
4762
+ var REASON_BY_OUTCOME = {
4763
+ [PollOutcome.Timeout]: "poll_timeout",
4764
+ [PollOutcome.Failed]: "poll_failed",
4765
+ [PollOutcome.Interrupted]: "poll_failed",
4766
+ [PollOutcome.Aborted]: "poll_aborted"
4767
+ };
4768
+ // ../common/src/polling/terminal-statuses.ts
4769
+ var TERMINAL_STATUSES = new Set([
4770
+ "completed",
4771
+ "successful",
4772
+ "faulted",
4773
+ "failed",
4774
+ "cancelled",
4775
+ "canceled",
4776
+ "stopped",
4777
+ "finished"
4778
+ ]);
4779
+ var FAILURE_STATUSES = new Set([
4780
+ "faulted",
4781
+ "failed",
4782
+ "cancelled",
4783
+ "canceled",
4784
+ "stopped"
4785
+ ]);
4786
+ // ../common/src/screen-logger.ts
4787
+ var ScreenLogger;
4788
+ ((ScreenLogger) => {
4789
+ function progress(message) {
4790
+ getOutputSink().writeErr(`${message}
4791
+ `);
4792
+ }
4793
+ ScreenLogger.progress = progress;
4794
+ })(ScreenLogger ||= {});
4795
+ // ../common/src/solution-project-types.ts
4796
+ var LIBRARY_NOT_A_PROJECT = "A library cannot be a project inside a solution — it is a reusable .nupkg that other projects consume as a NuGet dependency, not a deployable unit. Build and publish it on its own ('uip rpa pack <project-dir> <output-path>', then 'uip or libraries upload --file <nupkg-path>'), and reference it from a project's dependencies. To make the published library part of this solution, add it as a resource instead: 'uip solution resources add --source remote --kind Library --name <library-name>'.";
4797
+ function unsupportedSolutionProjectType(projectType) {
4798
+ if (typeof projectType !== "string") {
4799
+ return null;
4800
+ }
4801
+ return projectType.toLowerCase() === "library" ? LIBRARY_NOT_A_PROJECT : null;
4802
+ }
4803
+ // ../common/src/telemetry/ship-succeeded.ts
4804
+ var shippedKeysSlot = singleton("ShipSucceededDedupeKeys");
4805
+ // ../common/src/tool-provider.ts
4806
+ var factorySlot = singleton("PackagerFactoryProvider");
4807
+ export { NodeFileSystem, getFileSystem, logger, DebugTelemetryProvider, NodeContextStorage, RESULTS, SuccessOutput, FailureOutput, OutputFormatter, Command, processContext, registerPackageMetadataOptions, mapPackageMetadataOptions, unsupportedSolutionProjectType };
4808
+
4809
+ //# debugId=D2B7020EA6B59C3E64756E2164756E21