@bagdock/cli 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +90 -0
  2. package/dist/bagdock.js +3950 -0
  3. package/package.json +36 -0
@@ -0,0 +1,3950 @@
1
+ #!/usr/bin/env node
2
+ #!/usr/bin/env bun
3
+ // @bun
4
+ import { createRequire } from "node:module";
5
+ var __create = Object.create;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropNames = Object.getOwnPropertyNames;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ function __accessProp(key) {
11
+ return this[key];
12
+ }
13
+ var __toESMCache_node;
14
+ var __toESMCache_esm;
15
+ var __toESM = (mod, isNodeMode, target) => {
16
+ var canCache = mod != null && typeof mod === "object";
17
+ if (canCache) {
18
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
19
+ var cached = cache.get(mod);
20
+ if (cached)
21
+ return cached;
22
+ }
23
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
24
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
25
+ for (let key of __getOwnPropNames(mod))
26
+ if (!__hasOwnProp.call(to, key))
27
+ __defProp(to, key, {
28
+ get: __accessProp.bind(mod, key),
29
+ enumerable: true
30
+ });
31
+ if (canCache)
32
+ cache.set(mod, to);
33
+ return to;
34
+ };
35
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
36
+ var __returnValue = (v) => v;
37
+ function __exportSetter(name, newValue) {
38
+ this[name] = __returnValue.bind(null, newValue);
39
+ }
40
+ var __export = (target, all) => {
41
+ for (var name in all)
42
+ __defProp(target, name, {
43
+ get: all[name],
44
+ enumerable: true,
45
+ configurable: true,
46
+ set: __exportSetter.bind(all, name)
47
+ });
48
+ };
49
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
50
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
51
+
52
+ // ../../node_modules/commander/lib/error.js
53
+ var require_error = __commonJS((exports) => {
54
+ class CommanderError extends Error {
55
+ constructor(exitCode, code, message) {
56
+ super(message);
57
+ Error.captureStackTrace(this, this.constructor);
58
+ this.name = this.constructor.name;
59
+ this.code = code;
60
+ this.exitCode = exitCode;
61
+ this.nestedError = undefined;
62
+ }
63
+ }
64
+
65
+ class InvalidArgumentError extends CommanderError {
66
+ constructor(message) {
67
+ super(1, "commander.invalidArgument", message);
68
+ Error.captureStackTrace(this, this.constructor);
69
+ this.name = this.constructor.name;
70
+ }
71
+ }
72
+ exports.CommanderError = CommanderError;
73
+ exports.InvalidArgumentError = InvalidArgumentError;
74
+ });
75
+
76
+ // ../../node_modules/commander/lib/argument.js
77
+ var require_argument = __commonJS((exports) => {
78
+ var { InvalidArgumentError } = require_error();
79
+
80
+ class Argument {
81
+ constructor(name, description) {
82
+ this.description = description || "";
83
+ this.variadic = false;
84
+ this.parseArg = undefined;
85
+ this.defaultValue = undefined;
86
+ this.defaultValueDescription = undefined;
87
+ this.argChoices = undefined;
88
+ switch (name[0]) {
89
+ case "<":
90
+ this.required = true;
91
+ this._name = name.slice(1, -1);
92
+ break;
93
+ case "[":
94
+ this.required = false;
95
+ this._name = name.slice(1, -1);
96
+ break;
97
+ default:
98
+ this.required = true;
99
+ this._name = name;
100
+ break;
101
+ }
102
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
103
+ this.variadic = true;
104
+ this._name = this._name.slice(0, -3);
105
+ }
106
+ }
107
+ name() {
108
+ return this._name;
109
+ }
110
+ _concatValue(value, previous) {
111
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
112
+ return [value];
113
+ }
114
+ return previous.concat(value);
115
+ }
116
+ default(value, description) {
117
+ this.defaultValue = value;
118
+ this.defaultValueDescription = description;
119
+ return this;
120
+ }
121
+ argParser(fn) {
122
+ this.parseArg = fn;
123
+ return this;
124
+ }
125
+ choices(values) {
126
+ this.argChoices = values.slice();
127
+ this.parseArg = (arg, previous) => {
128
+ if (!this.argChoices.includes(arg)) {
129
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
130
+ }
131
+ if (this.variadic) {
132
+ return this._concatValue(arg, previous);
133
+ }
134
+ return arg;
135
+ };
136
+ return this;
137
+ }
138
+ argRequired() {
139
+ this.required = true;
140
+ return this;
141
+ }
142
+ argOptional() {
143
+ this.required = false;
144
+ return this;
145
+ }
146
+ }
147
+ function humanReadableArgName(arg) {
148
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
149
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
150
+ }
151
+ exports.Argument = Argument;
152
+ exports.humanReadableArgName = humanReadableArgName;
153
+ });
154
+
155
+ // ../../node_modules/commander/lib/help.js
156
+ var require_help = __commonJS((exports) => {
157
+ var { humanReadableArgName } = require_argument();
158
+
159
+ class Help {
160
+ constructor() {
161
+ this.helpWidth = undefined;
162
+ this.minWidthToWrap = 40;
163
+ this.sortSubcommands = false;
164
+ this.sortOptions = false;
165
+ this.showGlobalOptions = false;
166
+ }
167
+ prepareContext(contextOptions) {
168
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
169
+ }
170
+ visibleCommands(cmd) {
171
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
172
+ const helpCommand = cmd._getHelpCommand();
173
+ if (helpCommand && !helpCommand._hidden) {
174
+ visibleCommands.push(helpCommand);
175
+ }
176
+ if (this.sortSubcommands) {
177
+ visibleCommands.sort((a, b) => {
178
+ return a.name().localeCompare(b.name());
179
+ });
180
+ }
181
+ return visibleCommands;
182
+ }
183
+ compareOptions(a, b) {
184
+ const getSortKey = (option) => {
185
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
186
+ };
187
+ return getSortKey(a).localeCompare(getSortKey(b));
188
+ }
189
+ visibleOptions(cmd) {
190
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
191
+ const helpOption = cmd._getHelpOption();
192
+ if (helpOption && !helpOption.hidden) {
193
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
194
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
195
+ if (!removeShort && !removeLong) {
196
+ visibleOptions.push(helpOption);
197
+ } else if (helpOption.long && !removeLong) {
198
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
199
+ } else if (helpOption.short && !removeShort) {
200
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
201
+ }
202
+ }
203
+ if (this.sortOptions) {
204
+ visibleOptions.sort(this.compareOptions);
205
+ }
206
+ return visibleOptions;
207
+ }
208
+ visibleGlobalOptions(cmd) {
209
+ if (!this.showGlobalOptions)
210
+ return [];
211
+ const globalOptions = [];
212
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
213
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
214
+ globalOptions.push(...visibleOptions);
215
+ }
216
+ if (this.sortOptions) {
217
+ globalOptions.sort(this.compareOptions);
218
+ }
219
+ return globalOptions;
220
+ }
221
+ visibleArguments(cmd) {
222
+ if (cmd._argsDescription) {
223
+ cmd.registeredArguments.forEach((argument) => {
224
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
225
+ });
226
+ }
227
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
228
+ return cmd.registeredArguments;
229
+ }
230
+ return [];
231
+ }
232
+ subcommandTerm(cmd) {
233
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
234
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
235
+ }
236
+ optionTerm(option) {
237
+ return option.flags;
238
+ }
239
+ argumentTerm(argument) {
240
+ return argument.name();
241
+ }
242
+ longestSubcommandTermLength(cmd, helper) {
243
+ return helper.visibleCommands(cmd).reduce((max, command) => {
244
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
245
+ }, 0);
246
+ }
247
+ longestOptionTermLength(cmd, helper) {
248
+ return helper.visibleOptions(cmd).reduce((max, option) => {
249
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
250
+ }, 0);
251
+ }
252
+ longestGlobalOptionTermLength(cmd, helper) {
253
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
254
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
255
+ }, 0);
256
+ }
257
+ longestArgumentTermLength(cmd, helper) {
258
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
259
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
260
+ }, 0);
261
+ }
262
+ commandUsage(cmd) {
263
+ let cmdName = cmd._name;
264
+ if (cmd._aliases[0]) {
265
+ cmdName = cmdName + "|" + cmd._aliases[0];
266
+ }
267
+ let ancestorCmdNames = "";
268
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
269
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
270
+ }
271
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
272
+ }
273
+ commandDescription(cmd) {
274
+ return cmd.description();
275
+ }
276
+ subcommandDescription(cmd) {
277
+ return cmd.summary() || cmd.description();
278
+ }
279
+ optionDescription(option) {
280
+ const extraInfo = [];
281
+ if (option.argChoices) {
282
+ extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
283
+ }
284
+ if (option.defaultValue !== undefined) {
285
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
286
+ if (showDefault) {
287
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
288
+ }
289
+ }
290
+ if (option.presetArg !== undefined && option.optional) {
291
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
292
+ }
293
+ if (option.envVar !== undefined) {
294
+ extraInfo.push(`env: ${option.envVar}`);
295
+ }
296
+ if (extraInfo.length > 0) {
297
+ return `${option.description} (${extraInfo.join(", ")})`;
298
+ }
299
+ return option.description;
300
+ }
301
+ argumentDescription(argument) {
302
+ const extraInfo = [];
303
+ if (argument.argChoices) {
304
+ extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
305
+ }
306
+ if (argument.defaultValue !== undefined) {
307
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
308
+ }
309
+ if (extraInfo.length > 0) {
310
+ const extraDescription = `(${extraInfo.join(", ")})`;
311
+ if (argument.description) {
312
+ return `${argument.description} ${extraDescription}`;
313
+ }
314
+ return extraDescription;
315
+ }
316
+ return argument.description;
317
+ }
318
+ formatHelp(cmd, helper) {
319
+ const termWidth = helper.padWidth(cmd, helper);
320
+ const helpWidth = helper.helpWidth ?? 80;
321
+ function callFormatItem(term, description) {
322
+ return helper.formatItem(term, termWidth, description, helper);
323
+ }
324
+ let output = [
325
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
326
+ ""
327
+ ];
328
+ const commandDescription = helper.commandDescription(cmd);
329
+ if (commandDescription.length > 0) {
330
+ output = output.concat([
331
+ helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth),
332
+ ""
333
+ ]);
334
+ }
335
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
336
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
337
+ });
338
+ if (argumentList.length > 0) {
339
+ output = output.concat([
340
+ helper.styleTitle("Arguments:"),
341
+ ...argumentList,
342
+ ""
343
+ ]);
344
+ }
345
+ const optionList = helper.visibleOptions(cmd).map((option) => {
346
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
347
+ });
348
+ if (optionList.length > 0) {
349
+ output = output.concat([
350
+ helper.styleTitle("Options:"),
351
+ ...optionList,
352
+ ""
353
+ ]);
354
+ }
355
+ if (helper.showGlobalOptions) {
356
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
357
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
358
+ });
359
+ if (globalOptionList.length > 0) {
360
+ output = output.concat([
361
+ helper.styleTitle("Global Options:"),
362
+ ...globalOptionList,
363
+ ""
364
+ ]);
365
+ }
366
+ }
367
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
368
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(cmd2)), helper.styleSubcommandDescription(helper.subcommandDescription(cmd2)));
369
+ });
370
+ if (commandList.length > 0) {
371
+ output = output.concat([
372
+ helper.styleTitle("Commands:"),
373
+ ...commandList,
374
+ ""
375
+ ]);
376
+ }
377
+ return output.join(`
378
+ `);
379
+ }
380
+ displayWidth(str) {
381
+ return stripColor(str).length;
382
+ }
383
+ styleTitle(str) {
384
+ return str;
385
+ }
386
+ styleUsage(str) {
387
+ return str.split(" ").map((word) => {
388
+ if (word === "[options]")
389
+ return this.styleOptionText(word);
390
+ if (word === "[command]")
391
+ return this.styleSubcommandText(word);
392
+ if (word[0] === "[" || word[0] === "<")
393
+ return this.styleArgumentText(word);
394
+ return this.styleCommandText(word);
395
+ }).join(" ");
396
+ }
397
+ styleCommandDescription(str) {
398
+ return this.styleDescriptionText(str);
399
+ }
400
+ styleOptionDescription(str) {
401
+ return this.styleDescriptionText(str);
402
+ }
403
+ styleSubcommandDescription(str) {
404
+ return this.styleDescriptionText(str);
405
+ }
406
+ styleArgumentDescription(str) {
407
+ return this.styleDescriptionText(str);
408
+ }
409
+ styleDescriptionText(str) {
410
+ return str;
411
+ }
412
+ styleOptionTerm(str) {
413
+ return this.styleOptionText(str);
414
+ }
415
+ styleSubcommandTerm(str) {
416
+ return str.split(" ").map((word) => {
417
+ if (word === "[options]")
418
+ return this.styleOptionText(word);
419
+ if (word[0] === "[" || word[0] === "<")
420
+ return this.styleArgumentText(word);
421
+ return this.styleSubcommandText(word);
422
+ }).join(" ");
423
+ }
424
+ styleArgumentTerm(str) {
425
+ return this.styleArgumentText(str);
426
+ }
427
+ styleOptionText(str) {
428
+ return str;
429
+ }
430
+ styleArgumentText(str) {
431
+ return str;
432
+ }
433
+ styleSubcommandText(str) {
434
+ return str;
435
+ }
436
+ styleCommandText(str) {
437
+ return str;
438
+ }
439
+ padWidth(cmd, helper) {
440
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
441
+ }
442
+ preformatted(str) {
443
+ return /\n[^\S\r\n]/.test(str);
444
+ }
445
+ formatItem(term, termWidth, description, helper) {
446
+ const itemIndent = 2;
447
+ const itemIndentStr = " ".repeat(itemIndent);
448
+ if (!description)
449
+ return itemIndentStr + term;
450
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
451
+ const spacerWidth = 2;
452
+ const helpWidth = this.helpWidth ?? 80;
453
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
454
+ let formattedDescription;
455
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
456
+ formattedDescription = description;
457
+ } else {
458
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
459
+ formattedDescription = wrappedDescription.replace(/\n/g, `
460
+ ` + " ".repeat(termWidth + spacerWidth));
461
+ }
462
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
463
+ ${itemIndentStr}`);
464
+ }
465
+ boxWrap(str, width) {
466
+ if (width < this.minWidthToWrap)
467
+ return str;
468
+ const rawLines = str.split(/\r\n|\n/);
469
+ const chunkPattern = /[\s]*[^\s]+/g;
470
+ const wrappedLines = [];
471
+ rawLines.forEach((line) => {
472
+ const chunks = line.match(chunkPattern);
473
+ if (chunks === null) {
474
+ wrappedLines.push("");
475
+ return;
476
+ }
477
+ let sumChunks = [chunks.shift()];
478
+ let sumWidth = this.displayWidth(sumChunks[0]);
479
+ chunks.forEach((chunk) => {
480
+ const visibleWidth = this.displayWidth(chunk);
481
+ if (sumWidth + visibleWidth <= width) {
482
+ sumChunks.push(chunk);
483
+ sumWidth += visibleWidth;
484
+ return;
485
+ }
486
+ wrappedLines.push(sumChunks.join(""));
487
+ const nextChunk = chunk.trimStart();
488
+ sumChunks = [nextChunk];
489
+ sumWidth = this.displayWidth(nextChunk);
490
+ });
491
+ wrappedLines.push(sumChunks.join(""));
492
+ });
493
+ return wrappedLines.join(`
494
+ `);
495
+ }
496
+ }
497
+ function stripColor(str) {
498
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
499
+ return str.replace(sgrPattern, "");
500
+ }
501
+ exports.Help = Help;
502
+ exports.stripColor = stripColor;
503
+ });
504
+
505
+ // ../../node_modules/commander/lib/option.js
506
+ var require_option = __commonJS((exports) => {
507
+ var { InvalidArgumentError } = require_error();
508
+
509
+ class Option {
510
+ constructor(flags, description) {
511
+ this.flags = flags;
512
+ this.description = description || "";
513
+ this.required = flags.includes("<");
514
+ this.optional = flags.includes("[");
515
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
516
+ this.mandatory = false;
517
+ const optionFlags = splitOptionFlags(flags);
518
+ this.short = optionFlags.shortFlag;
519
+ this.long = optionFlags.longFlag;
520
+ this.negate = false;
521
+ if (this.long) {
522
+ this.negate = this.long.startsWith("--no-");
523
+ }
524
+ this.defaultValue = undefined;
525
+ this.defaultValueDescription = undefined;
526
+ this.presetArg = undefined;
527
+ this.envVar = undefined;
528
+ this.parseArg = undefined;
529
+ this.hidden = false;
530
+ this.argChoices = undefined;
531
+ this.conflictsWith = [];
532
+ this.implied = undefined;
533
+ }
534
+ default(value, description) {
535
+ this.defaultValue = value;
536
+ this.defaultValueDescription = description;
537
+ return this;
538
+ }
539
+ preset(arg) {
540
+ this.presetArg = arg;
541
+ return this;
542
+ }
543
+ conflicts(names) {
544
+ this.conflictsWith = this.conflictsWith.concat(names);
545
+ return this;
546
+ }
547
+ implies(impliedOptionValues) {
548
+ let newImplied = impliedOptionValues;
549
+ if (typeof impliedOptionValues === "string") {
550
+ newImplied = { [impliedOptionValues]: true };
551
+ }
552
+ this.implied = Object.assign(this.implied || {}, newImplied);
553
+ return this;
554
+ }
555
+ env(name) {
556
+ this.envVar = name;
557
+ return this;
558
+ }
559
+ argParser(fn) {
560
+ this.parseArg = fn;
561
+ return this;
562
+ }
563
+ makeOptionMandatory(mandatory = true) {
564
+ this.mandatory = !!mandatory;
565
+ return this;
566
+ }
567
+ hideHelp(hide = true) {
568
+ this.hidden = !!hide;
569
+ return this;
570
+ }
571
+ _concatValue(value, previous) {
572
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
573
+ return [value];
574
+ }
575
+ return previous.concat(value);
576
+ }
577
+ choices(values) {
578
+ this.argChoices = values.slice();
579
+ this.parseArg = (arg, previous) => {
580
+ if (!this.argChoices.includes(arg)) {
581
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
582
+ }
583
+ if (this.variadic) {
584
+ return this._concatValue(arg, previous);
585
+ }
586
+ return arg;
587
+ };
588
+ return this;
589
+ }
590
+ name() {
591
+ if (this.long) {
592
+ return this.long.replace(/^--/, "");
593
+ }
594
+ return this.short.replace(/^-/, "");
595
+ }
596
+ attributeName() {
597
+ if (this.negate) {
598
+ return camelcase(this.name().replace(/^no-/, ""));
599
+ }
600
+ return camelcase(this.name());
601
+ }
602
+ is(arg) {
603
+ return this.short === arg || this.long === arg;
604
+ }
605
+ isBoolean() {
606
+ return !this.required && !this.optional && !this.negate;
607
+ }
608
+ }
609
+
610
+ class DualOptions {
611
+ constructor(options) {
612
+ this.positiveOptions = new Map;
613
+ this.negativeOptions = new Map;
614
+ this.dualOptions = new Set;
615
+ options.forEach((option) => {
616
+ if (option.negate) {
617
+ this.negativeOptions.set(option.attributeName(), option);
618
+ } else {
619
+ this.positiveOptions.set(option.attributeName(), option);
620
+ }
621
+ });
622
+ this.negativeOptions.forEach((value, key) => {
623
+ if (this.positiveOptions.has(key)) {
624
+ this.dualOptions.add(key);
625
+ }
626
+ });
627
+ }
628
+ valueFromOption(value, option) {
629
+ const optionKey = option.attributeName();
630
+ if (!this.dualOptions.has(optionKey))
631
+ return true;
632
+ const preset = this.negativeOptions.get(optionKey).presetArg;
633
+ const negativeValue = preset !== undefined ? preset : false;
634
+ return option.negate === (negativeValue === value);
635
+ }
636
+ }
637
+ function camelcase(str) {
638
+ return str.split("-").reduce((str2, word) => {
639
+ return str2 + word[0].toUpperCase() + word.slice(1);
640
+ });
641
+ }
642
+ function splitOptionFlags(flags) {
643
+ let shortFlag;
644
+ let longFlag;
645
+ const shortFlagExp = /^-[^-]$/;
646
+ const longFlagExp = /^--[^-]/;
647
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
648
+ if (shortFlagExp.test(flagParts[0]))
649
+ shortFlag = flagParts.shift();
650
+ if (longFlagExp.test(flagParts[0]))
651
+ longFlag = flagParts.shift();
652
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
653
+ shortFlag = flagParts.shift();
654
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
655
+ shortFlag = longFlag;
656
+ longFlag = flagParts.shift();
657
+ }
658
+ if (flagParts[0].startsWith("-")) {
659
+ const unsupportedFlag = flagParts[0];
660
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
661
+ if (/^-[^-][^-]/.test(unsupportedFlag))
662
+ throw new Error(`${baseError}
663
+ - a short flag is a single dash and a single character
664
+ - either use a single dash and a single character (for a short flag)
665
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
666
+ if (shortFlagExp.test(unsupportedFlag))
667
+ throw new Error(`${baseError}
668
+ - too many short flags`);
669
+ if (longFlagExp.test(unsupportedFlag))
670
+ throw new Error(`${baseError}
671
+ - too many long flags`);
672
+ throw new Error(`${baseError}
673
+ - unrecognised flag format`);
674
+ }
675
+ if (shortFlag === undefined && longFlag === undefined)
676
+ throw new Error(`option creation failed due to no flags found in '${flags}'.`);
677
+ return { shortFlag, longFlag };
678
+ }
679
+ exports.Option = Option;
680
+ exports.DualOptions = DualOptions;
681
+ });
682
+
683
+ // ../../node_modules/commander/lib/suggestSimilar.js
684
+ var require_suggestSimilar = __commonJS((exports) => {
685
+ var maxDistance = 3;
686
+ function editDistance(a, b) {
687
+ if (Math.abs(a.length - b.length) > maxDistance)
688
+ return Math.max(a.length, b.length);
689
+ const d = [];
690
+ for (let i = 0;i <= a.length; i++) {
691
+ d[i] = [i];
692
+ }
693
+ for (let j = 0;j <= b.length; j++) {
694
+ d[0][j] = j;
695
+ }
696
+ for (let j = 1;j <= b.length; j++) {
697
+ for (let i = 1;i <= a.length; i++) {
698
+ let cost = 1;
699
+ if (a[i - 1] === b[j - 1]) {
700
+ cost = 0;
701
+ } else {
702
+ cost = 1;
703
+ }
704
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
705
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
706
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
707
+ }
708
+ }
709
+ }
710
+ return d[a.length][b.length];
711
+ }
712
+ function suggestSimilar(word, candidates) {
713
+ if (!candidates || candidates.length === 0)
714
+ return "";
715
+ candidates = Array.from(new Set(candidates));
716
+ const searchingOptions = word.startsWith("--");
717
+ if (searchingOptions) {
718
+ word = word.slice(2);
719
+ candidates = candidates.map((candidate) => candidate.slice(2));
720
+ }
721
+ let similar = [];
722
+ let bestDistance = maxDistance;
723
+ const minSimilarity = 0.4;
724
+ candidates.forEach((candidate) => {
725
+ if (candidate.length <= 1)
726
+ return;
727
+ const distance = editDistance(word, candidate);
728
+ const length = Math.max(word.length, candidate.length);
729
+ const similarity = (length - distance) / length;
730
+ if (similarity > minSimilarity) {
731
+ if (distance < bestDistance) {
732
+ bestDistance = distance;
733
+ similar = [candidate];
734
+ } else if (distance === bestDistance) {
735
+ similar.push(candidate);
736
+ }
737
+ }
738
+ });
739
+ similar.sort((a, b) => a.localeCompare(b));
740
+ if (searchingOptions) {
741
+ similar = similar.map((candidate) => `--${candidate}`);
742
+ }
743
+ if (similar.length > 1) {
744
+ return `
745
+ (Did you mean one of ${similar.join(", ")}?)`;
746
+ }
747
+ if (similar.length === 1) {
748
+ return `
749
+ (Did you mean ${similar[0]}?)`;
750
+ }
751
+ return "";
752
+ }
753
+ exports.suggestSimilar = suggestSimilar;
754
+ });
755
+
756
+ // ../../node_modules/commander/lib/command.js
757
+ var require_command = __commonJS((exports) => {
758
+ var EventEmitter = __require("node:events").EventEmitter;
759
+ var childProcess = __require("node:child_process");
760
+ var path = __require("node:path");
761
+ var fs = __require("node:fs");
762
+ var process2 = __require("node:process");
763
+ var { Argument, humanReadableArgName } = require_argument();
764
+ var { CommanderError } = require_error();
765
+ var { Help, stripColor } = require_help();
766
+ var { Option, DualOptions } = require_option();
767
+ var { suggestSimilar } = require_suggestSimilar();
768
+
769
+ class Command extends EventEmitter {
770
+ constructor(name) {
771
+ super();
772
+ this.commands = [];
773
+ this.options = [];
774
+ this.parent = null;
775
+ this._allowUnknownOption = false;
776
+ this._allowExcessArguments = false;
777
+ this.registeredArguments = [];
778
+ this._args = this.registeredArguments;
779
+ this.args = [];
780
+ this.rawArgs = [];
781
+ this.processedArgs = [];
782
+ this._scriptPath = null;
783
+ this._name = name || "";
784
+ this._optionValues = {};
785
+ this._optionValueSources = {};
786
+ this._storeOptionsAsProperties = false;
787
+ this._actionHandler = null;
788
+ this._executableHandler = false;
789
+ this._executableFile = null;
790
+ this._executableDir = null;
791
+ this._defaultCommandName = null;
792
+ this._exitCallback = null;
793
+ this._aliases = [];
794
+ this._combineFlagAndOptionalValue = true;
795
+ this._description = "";
796
+ this._summary = "";
797
+ this._argsDescription = undefined;
798
+ this._enablePositionalOptions = false;
799
+ this._passThroughOptions = false;
800
+ this._lifeCycleHooks = {};
801
+ this._showHelpAfterError = false;
802
+ this._showSuggestionAfterError = true;
803
+ this._savedState = null;
804
+ this._outputConfiguration = {
805
+ writeOut: (str) => process2.stdout.write(str),
806
+ writeErr: (str) => process2.stderr.write(str),
807
+ outputError: (str, write) => write(str),
808
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
809
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
810
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
811
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
812
+ stripColor: (str) => stripColor(str)
813
+ };
814
+ this._hidden = false;
815
+ this._helpOption = undefined;
816
+ this._addImplicitHelpCommand = undefined;
817
+ this._helpCommand = undefined;
818
+ this._helpConfiguration = {};
819
+ }
820
+ copyInheritedSettings(sourceCommand) {
821
+ this._outputConfiguration = sourceCommand._outputConfiguration;
822
+ this._helpOption = sourceCommand._helpOption;
823
+ this._helpCommand = sourceCommand._helpCommand;
824
+ this._helpConfiguration = sourceCommand._helpConfiguration;
825
+ this._exitCallback = sourceCommand._exitCallback;
826
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
827
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
828
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
829
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
830
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
831
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
832
+ return this;
833
+ }
834
+ _getCommandAndAncestors() {
835
+ const result = [];
836
+ for (let command = this;command; command = command.parent) {
837
+ result.push(command);
838
+ }
839
+ return result;
840
+ }
841
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
842
+ let desc = actionOptsOrExecDesc;
843
+ let opts = execOpts;
844
+ if (typeof desc === "object" && desc !== null) {
845
+ opts = desc;
846
+ desc = null;
847
+ }
848
+ opts = opts || {};
849
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
850
+ const cmd = this.createCommand(name);
851
+ if (desc) {
852
+ cmd.description(desc);
853
+ cmd._executableHandler = true;
854
+ }
855
+ if (opts.isDefault)
856
+ this._defaultCommandName = cmd._name;
857
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
858
+ cmd._executableFile = opts.executableFile || null;
859
+ if (args)
860
+ cmd.arguments(args);
861
+ this._registerCommand(cmd);
862
+ cmd.parent = this;
863
+ cmd.copyInheritedSettings(this);
864
+ if (desc)
865
+ return this;
866
+ return cmd;
867
+ }
868
+ createCommand(name) {
869
+ return new Command(name);
870
+ }
871
+ createHelp() {
872
+ return Object.assign(new Help, this.configureHelp());
873
+ }
874
+ configureHelp(configuration) {
875
+ if (configuration === undefined)
876
+ return this._helpConfiguration;
877
+ this._helpConfiguration = configuration;
878
+ return this;
879
+ }
880
+ configureOutput(configuration) {
881
+ if (configuration === undefined)
882
+ return this._outputConfiguration;
883
+ Object.assign(this._outputConfiguration, configuration);
884
+ return this;
885
+ }
886
+ showHelpAfterError(displayHelp = true) {
887
+ if (typeof displayHelp !== "string")
888
+ displayHelp = !!displayHelp;
889
+ this._showHelpAfterError = displayHelp;
890
+ return this;
891
+ }
892
+ showSuggestionAfterError(displaySuggestion = true) {
893
+ this._showSuggestionAfterError = !!displaySuggestion;
894
+ return this;
895
+ }
896
+ addCommand(cmd, opts) {
897
+ if (!cmd._name) {
898
+ throw new Error(`Command passed to .addCommand() must have a name
899
+ - specify the name in Command constructor or using .name()`);
900
+ }
901
+ opts = opts || {};
902
+ if (opts.isDefault)
903
+ this._defaultCommandName = cmd._name;
904
+ if (opts.noHelp || opts.hidden)
905
+ cmd._hidden = true;
906
+ this._registerCommand(cmd);
907
+ cmd.parent = this;
908
+ cmd._checkForBrokenPassThrough();
909
+ return this;
910
+ }
911
+ createArgument(name, description) {
912
+ return new Argument(name, description);
913
+ }
914
+ argument(name, description, fn, defaultValue) {
915
+ const argument = this.createArgument(name, description);
916
+ if (typeof fn === "function") {
917
+ argument.default(defaultValue).argParser(fn);
918
+ } else {
919
+ argument.default(fn);
920
+ }
921
+ this.addArgument(argument);
922
+ return this;
923
+ }
924
+ arguments(names) {
925
+ names.trim().split(/ +/).forEach((detail) => {
926
+ this.argument(detail);
927
+ });
928
+ return this;
929
+ }
930
+ addArgument(argument) {
931
+ const previousArgument = this.registeredArguments.slice(-1)[0];
932
+ if (previousArgument && previousArgument.variadic) {
933
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
934
+ }
935
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
936
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
937
+ }
938
+ this.registeredArguments.push(argument);
939
+ return this;
940
+ }
941
+ helpCommand(enableOrNameAndArgs, description) {
942
+ if (typeof enableOrNameAndArgs === "boolean") {
943
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
944
+ return this;
945
+ }
946
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
947
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
948
+ const helpDescription = description ?? "display help for command";
949
+ const helpCommand = this.createCommand(helpName);
950
+ helpCommand.helpOption(false);
951
+ if (helpArgs)
952
+ helpCommand.arguments(helpArgs);
953
+ if (helpDescription)
954
+ helpCommand.description(helpDescription);
955
+ this._addImplicitHelpCommand = true;
956
+ this._helpCommand = helpCommand;
957
+ return this;
958
+ }
959
+ addHelpCommand(helpCommand, deprecatedDescription) {
960
+ if (typeof helpCommand !== "object") {
961
+ this.helpCommand(helpCommand, deprecatedDescription);
962
+ return this;
963
+ }
964
+ this._addImplicitHelpCommand = true;
965
+ this._helpCommand = helpCommand;
966
+ return this;
967
+ }
968
+ _getHelpCommand() {
969
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
970
+ if (hasImplicitHelpCommand) {
971
+ if (this._helpCommand === undefined) {
972
+ this.helpCommand(undefined, undefined);
973
+ }
974
+ return this._helpCommand;
975
+ }
976
+ return null;
977
+ }
978
+ hook(event, listener) {
979
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
980
+ if (!allowedValues.includes(event)) {
981
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
982
+ Expecting one of '${allowedValues.join("', '")}'`);
983
+ }
984
+ if (this._lifeCycleHooks[event]) {
985
+ this._lifeCycleHooks[event].push(listener);
986
+ } else {
987
+ this._lifeCycleHooks[event] = [listener];
988
+ }
989
+ return this;
990
+ }
991
+ exitOverride(fn) {
992
+ if (fn) {
993
+ this._exitCallback = fn;
994
+ } else {
995
+ this._exitCallback = (err) => {
996
+ if (err.code !== "commander.executeSubCommandAsync") {
997
+ throw err;
998
+ } else {}
999
+ };
1000
+ }
1001
+ return this;
1002
+ }
1003
+ _exit(exitCode, code, message) {
1004
+ if (this._exitCallback) {
1005
+ this._exitCallback(new CommanderError(exitCode, code, message));
1006
+ }
1007
+ process2.exit(exitCode);
1008
+ }
1009
+ action(fn) {
1010
+ const listener = (args) => {
1011
+ const expectedArgsCount = this.registeredArguments.length;
1012
+ const actionArgs = args.slice(0, expectedArgsCount);
1013
+ if (this._storeOptionsAsProperties) {
1014
+ actionArgs[expectedArgsCount] = this;
1015
+ } else {
1016
+ actionArgs[expectedArgsCount] = this.opts();
1017
+ }
1018
+ actionArgs.push(this);
1019
+ return fn.apply(this, actionArgs);
1020
+ };
1021
+ this._actionHandler = listener;
1022
+ return this;
1023
+ }
1024
+ createOption(flags, description) {
1025
+ return new Option(flags, description);
1026
+ }
1027
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1028
+ try {
1029
+ return target.parseArg(value, previous);
1030
+ } catch (err) {
1031
+ if (err.code === "commander.invalidArgument") {
1032
+ const message = `${invalidArgumentMessage} ${err.message}`;
1033
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1034
+ }
1035
+ throw err;
1036
+ }
1037
+ }
1038
+ _registerOption(option) {
1039
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1040
+ if (matchingOption) {
1041
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1042
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1043
+ - already used by option '${matchingOption.flags}'`);
1044
+ }
1045
+ this.options.push(option);
1046
+ }
1047
+ _registerCommand(command) {
1048
+ const knownBy = (cmd) => {
1049
+ return [cmd.name()].concat(cmd.aliases());
1050
+ };
1051
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1052
+ if (alreadyUsed) {
1053
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1054
+ const newCmd = knownBy(command).join("|");
1055
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1056
+ }
1057
+ this.commands.push(command);
1058
+ }
1059
+ addOption(option) {
1060
+ this._registerOption(option);
1061
+ const oname = option.name();
1062
+ const name = option.attributeName();
1063
+ if (option.negate) {
1064
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1065
+ if (!this._findOption(positiveLongFlag)) {
1066
+ this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
1067
+ }
1068
+ } else if (option.defaultValue !== undefined) {
1069
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1070
+ }
1071
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1072
+ if (val == null && option.presetArg !== undefined) {
1073
+ val = option.presetArg;
1074
+ }
1075
+ const oldValue = this.getOptionValue(name);
1076
+ if (val !== null && option.parseArg) {
1077
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1078
+ } else if (val !== null && option.variadic) {
1079
+ val = option._concatValue(val, oldValue);
1080
+ }
1081
+ if (val == null) {
1082
+ if (option.negate) {
1083
+ val = false;
1084
+ } else if (option.isBoolean() || option.optional) {
1085
+ val = true;
1086
+ } else {
1087
+ val = "";
1088
+ }
1089
+ }
1090
+ this.setOptionValueWithSource(name, val, valueSource);
1091
+ };
1092
+ this.on("option:" + oname, (val) => {
1093
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1094
+ handleOptionValue(val, invalidValueMessage, "cli");
1095
+ });
1096
+ if (option.envVar) {
1097
+ this.on("optionEnv:" + oname, (val) => {
1098
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1099
+ handleOptionValue(val, invalidValueMessage, "env");
1100
+ });
1101
+ }
1102
+ return this;
1103
+ }
1104
+ _optionEx(config, flags, description, fn, defaultValue) {
1105
+ if (typeof flags === "object" && flags instanceof Option) {
1106
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1107
+ }
1108
+ const option = this.createOption(flags, description);
1109
+ option.makeOptionMandatory(!!config.mandatory);
1110
+ if (typeof fn === "function") {
1111
+ option.default(defaultValue).argParser(fn);
1112
+ } else if (fn instanceof RegExp) {
1113
+ const regex = fn;
1114
+ fn = (val, def) => {
1115
+ const m = regex.exec(val);
1116
+ return m ? m[0] : def;
1117
+ };
1118
+ option.default(defaultValue).argParser(fn);
1119
+ } else {
1120
+ option.default(fn);
1121
+ }
1122
+ return this.addOption(option);
1123
+ }
1124
+ option(flags, description, parseArg, defaultValue) {
1125
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1126
+ }
1127
+ requiredOption(flags, description, parseArg, defaultValue) {
1128
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1129
+ }
1130
+ combineFlagAndOptionalValue(combine = true) {
1131
+ this._combineFlagAndOptionalValue = !!combine;
1132
+ return this;
1133
+ }
1134
+ allowUnknownOption(allowUnknown = true) {
1135
+ this._allowUnknownOption = !!allowUnknown;
1136
+ return this;
1137
+ }
1138
+ allowExcessArguments(allowExcess = true) {
1139
+ this._allowExcessArguments = !!allowExcess;
1140
+ return this;
1141
+ }
1142
+ enablePositionalOptions(positional = true) {
1143
+ this._enablePositionalOptions = !!positional;
1144
+ return this;
1145
+ }
1146
+ passThroughOptions(passThrough = true) {
1147
+ this._passThroughOptions = !!passThrough;
1148
+ this._checkForBrokenPassThrough();
1149
+ return this;
1150
+ }
1151
+ _checkForBrokenPassThrough() {
1152
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1153
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1154
+ }
1155
+ }
1156
+ storeOptionsAsProperties(storeAsProperties = true) {
1157
+ if (this.options.length) {
1158
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1159
+ }
1160
+ if (Object.keys(this._optionValues).length) {
1161
+ throw new Error("call .storeOptionsAsProperties() before setting option values");
1162
+ }
1163
+ this._storeOptionsAsProperties = !!storeAsProperties;
1164
+ return this;
1165
+ }
1166
+ getOptionValue(key) {
1167
+ if (this._storeOptionsAsProperties) {
1168
+ return this[key];
1169
+ }
1170
+ return this._optionValues[key];
1171
+ }
1172
+ setOptionValue(key, value) {
1173
+ return this.setOptionValueWithSource(key, value, undefined);
1174
+ }
1175
+ setOptionValueWithSource(key, value, source) {
1176
+ if (this._storeOptionsAsProperties) {
1177
+ this[key] = value;
1178
+ } else {
1179
+ this._optionValues[key] = value;
1180
+ }
1181
+ this._optionValueSources[key] = source;
1182
+ return this;
1183
+ }
1184
+ getOptionValueSource(key) {
1185
+ return this._optionValueSources[key];
1186
+ }
1187
+ getOptionValueSourceWithGlobals(key) {
1188
+ let source;
1189
+ this._getCommandAndAncestors().forEach((cmd) => {
1190
+ if (cmd.getOptionValueSource(key) !== undefined) {
1191
+ source = cmd.getOptionValueSource(key);
1192
+ }
1193
+ });
1194
+ return source;
1195
+ }
1196
+ _prepareUserArgs(argv, parseOptions) {
1197
+ if (argv !== undefined && !Array.isArray(argv)) {
1198
+ throw new Error("first parameter to parse must be array or undefined");
1199
+ }
1200
+ parseOptions = parseOptions || {};
1201
+ if (argv === undefined && parseOptions.from === undefined) {
1202
+ if (process2.versions?.electron) {
1203
+ parseOptions.from = "electron";
1204
+ }
1205
+ const execArgv = process2.execArgv ?? [];
1206
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1207
+ parseOptions.from = "eval";
1208
+ }
1209
+ }
1210
+ if (argv === undefined) {
1211
+ argv = process2.argv;
1212
+ }
1213
+ this.rawArgs = argv.slice();
1214
+ let userArgs;
1215
+ switch (parseOptions.from) {
1216
+ case undefined:
1217
+ case "node":
1218
+ this._scriptPath = argv[1];
1219
+ userArgs = argv.slice(2);
1220
+ break;
1221
+ case "electron":
1222
+ if (process2.defaultApp) {
1223
+ this._scriptPath = argv[1];
1224
+ userArgs = argv.slice(2);
1225
+ } else {
1226
+ userArgs = argv.slice(1);
1227
+ }
1228
+ break;
1229
+ case "user":
1230
+ userArgs = argv.slice(0);
1231
+ break;
1232
+ case "eval":
1233
+ userArgs = argv.slice(1);
1234
+ break;
1235
+ default:
1236
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1237
+ }
1238
+ if (!this._name && this._scriptPath)
1239
+ this.nameFromFilename(this._scriptPath);
1240
+ this._name = this._name || "program";
1241
+ return userArgs;
1242
+ }
1243
+ parse(argv, parseOptions) {
1244
+ this._prepareForParse();
1245
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1246
+ this._parseCommand([], userArgs);
1247
+ return this;
1248
+ }
1249
+ async parseAsync(argv, parseOptions) {
1250
+ this._prepareForParse();
1251
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1252
+ await this._parseCommand([], userArgs);
1253
+ return this;
1254
+ }
1255
+ _prepareForParse() {
1256
+ if (this._savedState === null) {
1257
+ this.saveStateBeforeParse();
1258
+ } else {
1259
+ this.restoreStateBeforeParse();
1260
+ }
1261
+ }
1262
+ saveStateBeforeParse() {
1263
+ this._savedState = {
1264
+ _name: this._name,
1265
+ _optionValues: { ...this._optionValues },
1266
+ _optionValueSources: { ...this._optionValueSources }
1267
+ };
1268
+ }
1269
+ restoreStateBeforeParse() {
1270
+ if (this._storeOptionsAsProperties)
1271
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1272
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1273
+ this._name = this._savedState._name;
1274
+ this._scriptPath = null;
1275
+ this.rawArgs = [];
1276
+ this._optionValues = { ...this._savedState._optionValues };
1277
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1278
+ this.args = [];
1279
+ this.processedArgs = [];
1280
+ }
1281
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1282
+ if (fs.existsSync(executableFile))
1283
+ return;
1284
+ 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";
1285
+ const executableMissing = `'${executableFile}' does not exist
1286
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1287
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1288
+ - ${executableDirMessage}`;
1289
+ throw new Error(executableMissing);
1290
+ }
1291
+ _executeSubCommand(subcommand, args) {
1292
+ args = args.slice();
1293
+ let launchWithNode = false;
1294
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1295
+ function findFile(baseDir, baseName) {
1296
+ const localBin = path.resolve(baseDir, baseName);
1297
+ if (fs.existsSync(localBin))
1298
+ return localBin;
1299
+ if (sourceExt.includes(path.extname(baseName)))
1300
+ return;
1301
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1302
+ if (foundExt)
1303
+ return `${localBin}${foundExt}`;
1304
+ return;
1305
+ }
1306
+ this._checkForMissingMandatoryOptions();
1307
+ this._checkForConflictingOptions();
1308
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1309
+ let executableDir = this._executableDir || "";
1310
+ if (this._scriptPath) {
1311
+ let resolvedScriptPath;
1312
+ try {
1313
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1314
+ } catch {
1315
+ resolvedScriptPath = this._scriptPath;
1316
+ }
1317
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1318
+ }
1319
+ if (executableDir) {
1320
+ let localFile = findFile(executableDir, executableFile);
1321
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1322
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1323
+ if (legacyName !== this._name) {
1324
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1325
+ }
1326
+ }
1327
+ executableFile = localFile || executableFile;
1328
+ }
1329
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1330
+ let proc;
1331
+ if (process2.platform !== "win32") {
1332
+ if (launchWithNode) {
1333
+ args.unshift(executableFile);
1334
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1335
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1336
+ } else {
1337
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1338
+ }
1339
+ } else {
1340
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1341
+ args.unshift(executableFile);
1342
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1343
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1344
+ }
1345
+ if (!proc.killed) {
1346
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1347
+ signals.forEach((signal) => {
1348
+ process2.on(signal, () => {
1349
+ if (proc.killed === false && proc.exitCode === null) {
1350
+ proc.kill(signal);
1351
+ }
1352
+ });
1353
+ });
1354
+ }
1355
+ const exitCallback = this._exitCallback;
1356
+ proc.on("close", (code) => {
1357
+ code = code ?? 1;
1358
+ if (!exitCallback) {
1359
+ process2.exit(code);
1360
+ } else {
1361
+ exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1362
+ }
1363
+ });
1364
+ proc.on("error", (err) => {
1365
+ if (err.code === "ENOENT") {
1366
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1367
+ } else if (err.code === "EACCES") {
1368
+ throw new Error(`'${executableFile}' not executable`);
1369
+ }
1370
+ if (!exitCallback) {
1371
+ process2.exit(1);
1372
+ } else {
1373
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1374
+ wrappedError.nestedError = err;
1375
+ exitCallback(wrappedError);
1376
+ }
1377
+ });
1378
+ this.runningCommand = proc;
1379
+ }
1380
+ _dispatchSubcommand(commandName, operands, unknown) {
1381
+ const subCommand = this._findCommand(commandName);
1382
+ if (!subCommand)
1383
+ this.help({ error: true });
1384
+ subCommand._prepareForParse();
1385
+ let promiseChain;
1386
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1387
+ promiseChain = this._chainOrCall(promiseChain, () => {
1388
+ if (subCommand._executableHandler) {
1389
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1390
+ } else {
1391
+ return subCommand._parseCommand(operands, unknown);
1392
+ }
1393
+ });
1394
+ return promiseChain;
1395
+ }
1396
+ _dispatchHelpCommand(subcommandName) {
1397
+ if (!subcommandName) {
1398
+ this.help();
1399
+ }
1400
+ const subCommand = this._findCommand(subcommandName);
1401
+ if (subCommand && !subCommand._executableHandler) {
1402
+ subCommand.help();
1403
+ }
1404
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
1405
+ }
1406
+ _checkNumberOfArguments() {
1407
+ this.registeredArguments.forEach((arg, i) => {
1408
+ if (arg.required && this.args[i] == null) {
1409
+ this.missingArgument(arg.name());
1410
+ }
1411
+ });
1412
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1413
+ return;
1414
+ }
1415
+ if (this.args.length > this.registeredArguments.length) {
1416
+ this._excessArguments(this.args);
1417
+ }
1418
+ }
1419
+ _processArguments() {
1420
+ const myParseArg = (argument, value, previous) => {
1421
+ let parsedValue = value;
1422
+ if (value !== null && argument.parseArg) {
1423
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1424
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1425
+ }
1426
+ return parsedValue;
1427
+ };
1428
+ this._checkNumberOfArguments();
1429
+ const processedArgs = [];
1430
+ this.registeredArguments.forEach((declaredArg, index) => {
1431
+ let value = declaredArg.defaultValue;
1432
+ if (declaredArg.variadic) {
1433
+ if (index < this.args.length) {
1434
+ value = this.args.slice(index);
1435
+ if (declaredArg.parseArg) {
1436
+ value = value.reduce((processed, v) => {
1437
+ return myParseArg(declaredArg, v, processed);
1438
+ }, declaredArg.defaultValue);
1439
+ }
1440
+ } else if (value === undefined) {
1441
+ value = [];
1442
+ }
1443
+ } else if (index < this.args.length) {
1444
+ value = this.args[index];
1445
+ if (declaredArg.parseArg) {
1446
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1447
+ }
1448
+ }
1449
+ processedArgs[index] = value;
1450
+ });
1451
+ this.processedArgs = processedArgs;
1452
+ }
1453
+ _chainOrCall(promise, fn) {
1454
+ if (promise && promise.then && typeof promise.then === "function") {
1455
+ return promise.then(() => fn());
1456
+ }
1457
+ return fn();
1458
+ }
1459
+ _chainOrCallHooks(promise, event) {
1460
+ let result = promise;
1461
+ const hooks = [];
1462
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
1463
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1464
+ hooks.push({ hookedCommand, callback });
1465
+ });
1466
+ });
1467
+ if (event === "postAction") {
1468
+ hooks.reverse();
1469
+ }
1470
+ hooks.forEach((hookDetail) => {
1471
+ result = this._chainOrCall(result, () => {
1472
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1473
+ });
1474
+ });
1475
+ return result;
1476
+ }
1477
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1478
+ let result = promise;
1479
+ if (this._lifeCycleHooks[event] !== undefined) {
1480
+ this._lifeCycleHooks[event].forEach((hook) => {
1481
+ result = this._chainOrCall(result, () => {
1482
+ return hook(this, subCommand);
1483
+ });
1484
+ });
1485
+ }
1486
+ return result;
1487
+ }
1488
+ _parseCommand(operands, unknown) {
1489
+ const parsed = this.parseOptions(unknown);
1490
+ this._parseOptionsEnv();
1491
+ this._parseOptionsImplied();
1492
+ operands = operands.concat(parsed.operands);
1493
+ unknown = parsed.unknown;
1494
+ this.args = operands.concat(unknown);
1495
+ if (operands && this._findCommand(operands[0])) {
1496
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1497
+ }
1498
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
1499
+ return this._dispatchHelpCommand(operands[1]);
1500
+ }
1501
+ if (this._defaultCommandName) {
1502
+ this._outputHelpIfRequested(unknown);
1503
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1504
+ }
1505
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1506
+ this.help({ error: true });
1507
+ }
1508
+ this._outputHelpIfRequested(parsed.unknown);
1509
+ this._checkForMissingMandatoryOptions();
1510
+ this._checkForConflictingOptions();
1511
+ const checkForUnknownOptions = () => {
1512
+ if (parsed.unknown.length > 0) {
1513
+ this.unknownOption(parsed.unknown[0]);
1514
+ }
1515
+ };
1516
+ const commandEvent = `command:${this.name()}`;
1517
+ if (this._actionHandler) {
1518
+ checkForUnknownOptions();
1519
+ this._processArguments();
1520
+ let promiseChain;
1521
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
1522
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
1523
+ if (this.parent) {
1524
+ promiseChain = this._chainOrCall(promiseChain, () => {
1525
+ this.parent.emit(commandEvent, operands, unknown);
1526
+ });
1527
+ }
1528
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
1529
+ return promiseChain;
1530
+ }
1531
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
1532
+ checkForUnknownOptions();
1533
+ this._processArguments();
1534
+ this.parent.emit(commandEvent, operands, unknown);
1535
+ } else if (operands.length) {
1536
+ if (this._findCommand("*")) {
1537
+ return this._dispatchSubcommand("*", operands, unknown);
1538
+ }
1539
+ if (this.listenerCount("command:*")) {
1540
+ this.emit("command:*", operands, unknown);
1541
+ } else if (this.commands.length) {
1542
+ this.unknownCommand();
1543
+ } else {
1544
+ checkForUnknownOptions();
1545
+ this._processArguments();
1546
+ }
1547
+ } else if (this.commands.length) {
1548
+ checkForUnknownOptions();
1549
+ this.help({ error: true });
1550
+ } else {
1551
+ checkForUnknownOptions();
1552
+ this._processArguments();
1553
+ }
1554
+ }
1555
+ _findCommand(name) {
1556
+ if (!name)
1557
+ return;
1558
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
1559
+ }
1560
+ _findOption(arg) {
1561
+ return this.options.find((option) => option.is(arg));
1562
+ }
1563
+ _checkForMissingMandatoryOptions() {
1564
+ this._getCommandAndAncestors().forEach((cmd) => {
1565
+ cmd.options.forEach((anOption) => {
1566
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
1567
+ cmd.missingMandatoryOptionValue(anOption);
1568
+ }
1569
+ });
1570
+ });
1571
+ }
1572
+ _checkForConflictingLocalOptions() {
1573
+ const definedNonDefaultOptions = this.options.filter((option) => {
1574
+ const optionKey = option.attributeName();
1575
+ if (this.getOptionValue(optionKey) === undefined) {
1576
+ return false;
1577
+ }
1578
+ return this.getOptionValueSource(optionKey) !== "default";
1579
+ });
1580
+ const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
1581
+ optionsWithConflicting.forEach((option) => {
1582
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
1583
+ if (conflictingAndDefined) {
1584
+ this._conflictingOption(option, conflictingAndDefined);
1585
+ }
1586
+ });
1587
+ }
1588
+ _checkForConflictingOptions() {
1589
+ this._getCommandAndAncestors().forEach((cmd) => {
1590
+ cmd._checkForConflictingLocalOptions();
1591
+ });
1592
+ }
1593
+ parseOptions(argv) {
1594
+ const operands = [];
1595
+ const unknown = [];
1596
+ let dest = operands;
1597
+ const args = argv.slice();
1598
+ function maybeOption(arg) {
1599
+ return arg.length > 1 && arg[0] === "-";
1600
+ }
1601
+ let activeVariadicOption = null;
1602
+ while (args.length) {
1603
+ const arg = args.shift();
1604
+ if (arg === "--") {
1605
+ if (dest === unknown)
1606
+ dest.push(arg);
1607
+ dest.push(...args);
1608
+ break;
1609
+ }
1610
+ if (activeVariadicOption && !maybeOption(arg)) {
1611
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1612
+ continue;
1613
+ }
1614
+ activeVariadicOption = null;
1615
+ if (maybeOption(arg)) {
1616
+ const option = this._findOption(arg);
1617
+ if (option) {
1618
+ if (option.required) {
1619
+ const value = args.shift();
1620
+ if (value === undefined)
1621
+ this.optionMissingArgument(option);
1622
+ this.emit(`option:${option.name()}`, value);
1623
+ } else if (option.optional) {
1624
+ let value = null;
1625
+ if (args.length > 0 && !maybeOption(args[0])) {
1626
+ value = args.shift();
1627
+ }
1628
+ this.emit(`option:${option.name()}`, value);
1629
+ } else {
1630
+ this.emit(`option:${option.name()}`);
1631
+ }
1632
+ activeVariadicOption = option.variadic ? option : null;
1633
+ continue;
1634
+ }
1635
+ }
1636
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
1637
+ const option = this._findOption(`-${arg[1]}`);
1638
+ if (option) {
1639
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
1640
+ this.emit(`option:${option.name()}`, arg.slice(2));
1641
+ } else {
1642
+ this.emit(`option:${option.name()}`);
1643
+ args.unshift(`-${arg.slice(2)}`);
1644
+ }
1645
+ continue;
1646
+ }
1647
+ }
1648
+ if (/^--[^=]+=/.test(arg)) {
1649
+ const index = arg.indexOf("=");
1650
+ const option = this._findOption(arg.slice(0, index));
1651
+ if (option && (option.required || option.optional)) {
1652
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1653
+ continue;
1654
+ }
1655
+ }
1656
+ if (maybeOption(arg)) {
1657
+ dest = unknown;
1658
+ }
1659
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
1660
+ if (this._findCommand(arg)) {
1661
+ operands.push(arg);
1662
+ if (args.length > 0)
1663
+ unknown.push(...args);
1664
+ break;
1665
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
1666
+ operands.push(arg);
1667
+ if (args.length > 0)
1668
+ operands.push(...args);
1669
+ break;
1670
+ } else if (this._defaultCommandName) {
1671
+ unknown.push(arg);
1672
+ if (args.length > 0)
1673
+ unknown.push(...args);
1674
+ break;
1675
+ }
1676
+ }
1677
+ if (this._passThroughOptions) {
1678
+ dest.push(arg);
1679
+ if (args.length > 0)
1680
+ dest.push(...args);
1681
+ break;
1682
+ }
1683
+ dest.push(arg);
1684
+ }
1685
+ return { operands, unknown };
1686
+ }
1687
+ opts() {
1688
+ if (this._storeOptionsAsProperties) {
1689
+ const result = {};
1690
+ const len = this.options.length;
1691
+ for (let i = 0;i < len; i++) {
1692
+ const key = this.options[i].attributeName();
1693
+ result[key] = key === this._versionOptionName ? this._version : this[key];
1694
+ }
1695
+ return result;
1696
+ }
1697
+ return this._optionValues;
1698
+ }
1699
+ optsWithGlobals() {
1700
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
1701
+ }
1702
+ error(message, errorOptions) {
1703
+ this._outputConfiguration.outputError(`${message}
1704
+ `, this._outputConfiguration.writeErr);
1705
+ if (typeof this._showHelpAfterError === "string") {
1706
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
1707
+ `);
1708
+ } else if (this._showHelpAfterError) {
1709
+ this._outputConfiguration.writeErr(`
1710
+ `);
1711
+ this.outputHelp({ error: true });
1712
+ }
1713
+ const config = errorOptions || {};
1714
+ const exitCode = config.exitCode || 1;
1715
+ const code = config.code || "commander.error";
1716
+ this._exit(exitCode, code, message);
1717
+ }
1718
+ _parseOptionsEnv() {
1719
+ this.options.forEach((option) => {
1720
+ if (option.envVar && option.envVar in process2.env) {
1721
+ const optionKey = option.attributeName();
1722
+ if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
1723
+ if (option.required || option.optional) {
1724
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
1725
+ } else {
1726
+ this.emit(`optionEnv:${option.name()}`);
1727
+ }
1728
+ }
1729
+ }
1730
+ });
1731
+ }
1732
+ _parseOptionsImplied() {
1733
+ const dualHelper = new DualOptions(this.options);
1734
+ const hasCustomOptionValue = (optionKey) => {
1735
+ return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
1736
+ };
1737
+ this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
1738
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
1739
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
1740
+ });
1741
+ });
1742
+ }
1743
+ missingArgument(name) {
1744
+ const message = `error: missing required argument '${name}'`;
1745
+ this.error(message, { code: "commander.missingArgument" });
1746
+ }
1747
+ optionMissingArgument(option) {
1748
+ const message = `error: option '${option.flags}' argument missing`;
1749
+ this.error(message, { code: "commander.optionMissingArgument" });
1750
+ }
1751
+ missingMandatoryOptionValue(option) {
1752
+ const message = `error: required option '${option.flags}' not specified`;
1753
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
1754
+ }
1755
+ _conflictingOption(option, conflictingOption) {
1756
+ const findBestOptionFromValue = (option2) => {
1757
+ const optionKey = option2.attributeName();
1758
+ const optionValue = this.getOptionValue(optionKey);
1759
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1760
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1761
+ if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1762
+ return negativeOption;
1763
+ }
1764
+ return positiveOption || option2;
1765
+ };
1766
+ const getErrorMessage = (option2) => {
1767
+ const bestOption = findBestOptionFromValue(option2);
1768
+ const optionKey = bestOption.attributeName();
1769
+ const source = this.getOptionValueSource(optionKey);
1770
+ if (source === "env") {
1771
+ return `environment variable '${bestOption.envVar}'`;
1772
+ }
1773
+ return `option '${bestOption.flags}'`;
1774
+ };
1775
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
1776
+ this.error(message, { code: "commander.conflictingOption" });
1777
+ }
1778
+ unknownOption(flag) {
1779
+ if (this._allowUnknownOption)
1780
+ return;
1781
+ let suggestion = "";
1782
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
1783
+ let candidateFlags = [];
1784
+ let command = this;
1785
+ do {
1786
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
1787
+ candidateFlags = candidateFlags.concat(moreFlags);
1788
+ command = command.parent;
1789
+ } while (command && !command._enablePositionalOptions);
1790
+ suggestion = suggestSimilar(flag, candidateFlags);
1791
+ }
1792
+ const message = `error: unknown option '${flag}'${suggestion}`;
1793
+ this.error(message, { code: "commander.unknownOption" });
1794
+ }
1795
+ _excessArguments(receivedArgs) {
1796
+ if (this._allowExcessArguments)
1797
+ return;
1798
+ const expected = this.registeredArguments.length;
1799
+ const s = expected === 1 ? "" : "s";
1800
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
1801
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
1802
+ this.error(message, { code: "commander.excessArguments" });
1803
+ }
1804
+ unknownCommand() {
1805
+ const unknownName = this.args[0];
1806
+ let suggestion = "";
1807
+ if (this._showSuggestionAfterError) {
1808
+ const candidateNames = [];
1809
+ this.createHelp().visibleCommands(this).forEach((command) => {
1810
+ candidateNames.push(command.name());
1811
+ if (command.alias())
1812
+ candidateNames.push(command.alias());
1813
+ });
1814
+ suggestion = suggestSimilar(unknownName, candidateNames);
1815
+ }
1816
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
1817
+ this.error(message, { code: "commander.unknownCommand" });
1818
+ }
1819
+ version(str, flags, description) {
1820
+ if (str === undefined)
1821
+ return this._version;
1822
+ this._version = str;
1823
+ flags = flags || "-V, --version";
1824
+ description = description || "output the version number";
1825
+ const versionOption = this.createOption(flags, description);
1826
+ this._versionOptionName = versionOption.attributeName();
1827
+ this._registerOption(versionOption);
1828
+ this.on("option:" + versionOption.name(), () => {
1829
+ this._outputConfiguration.writeOut(`${str}
1830
+ `);
1831
+ this._exit(0, "commander.version", str);
1832
+ });
1833
+ return this;
1834
+ }
1835
+ description(str, argsDescription) {
1836
+ if (str === undefined && argsDescription === undefined)
1837
+ return this._description;
1838
+ this._description = str;
1839
+ if (argsDescription) {
1840
+ this._argsDescription = argsDescription;
1841
+ }
1842
+ return this;
1843
+ }
1844
+ summary(str) {
1845
+ if (str === undefined)
1846
+ return this._summary;
1847
+ this._summary = str;
1848
+ return this;
1849
+ }
1850
+ alias(alias) {
1851
+ if (alias === undefined)
1852
+ return this._aliases[0];
1853
+ let command = this;
1854
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
1855
+ command = this.commands[this.commands.length - 1];
1856
+ }
1857
+ if (alias === command._name)
1858
+ throw new Error("Command alias can't be the same as its name");
1859
+ const matchingCommand = this.parent?._findCommand(alias);
1860
+ if (matchingCommand) {
1861
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
1862
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
1863
+ }
1864
+ command._aliases.push(alias);
1865
+ return this;
1866
+ }
1867
+ aliases(aliases) {
1868
+ if (aliases === undefined)
1869
+ return this._aliases;
1870
+ aliases.forEach((alias) => this.alias(alias));
1871
+ return this;
1872
+ }
1873
+ usage(str) {
1874
+ if (str === undefined) {
1875
+ if (this._usage)
1876
+ return this._usage;
1877
+ const args = this.registeredArguments.map((arg) => {
1878
+ return humanReadableArgName(arg);
1879
+ });
1880
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
1881
+ }
1882
+ this._usage = str;
1883
+ return this;
1884
+ }
1885
+ name(str) {
1886
+ if (str === undefined)
1887
+ return this._name;
1888
+ this._name = str;
1889
+ return this;
1890
+ }
1891
+ nameFromFilename(filename) {
1892
+ this._name = path.basename(filename, path.extname(filename));
1893
+ return this;
1894
+ }
1895
+ executableDir(path2) {
1896
+ if (path2 === undefined)
1897
+ return this._executableDir;
1898
+ this._executableDir = path2;
1899
+ return this;
1900
+ }
1901
+ helpInformation(contextOptions) {
1902
+ const helper = this.createHelp();
1903
+ const context = this._getOutputContext(contextOptions);
1904
+ helper.prepareContext({
1905
+ error: context.error,
1906
+ helpWidth: context.helpWidth,
1907
+ outputHasColors: context.hasColors
1908
+ });
1909
+ const text = helper.formatHelp(this, helper);
1910
+ if (context.hasColors)
1911
+ return text;
1912
+ return this._outputConfiguration.stripColor(text);
1913
+ }
1914
+ _getOutputContext(contextOptions) {
1915
+ contextOptions = contextOptions || {};
1916
+ const error = !!contextOptions.error;
1917
+ let baseWrite;
1918
+ let hasColors;
1919
+ let helpWidth;
1920
+ if (error) {
1921
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
1922
+ hasColors = this._outputConfiguration.getErrHasColors();
1923
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
1924
+ } else {
1925
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
1926
+ hasColors = this._outputConfiguration.getOutHasColors();
1927
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
1928
+ }
1929
+ const write = (str) => {
1930
+ if (!hasColors)
1931
+ str = this._outputConfiguration.stripColor(str);
1932
+ return baseWrite(str);
1933
+ };
1934
+ return { error, write, hasColors, helpWidth };
1935
+ }
1936
+ outputHelp(contextOptions) {
1937
+ let deprecatedCallback;
1938
+ if (typeof contextOptions === "function") {
1939
+ deprecatedCallback = contextOptions;
1940
+ contextOptions = undefined;
1941
+ }
1942
+ const outputContext = this._getOutputContext(contextOptions);
1943
+ const eventContext = {
1944
+ error: outputContext.error,
1945
+ write: outputContext.write,
1946
+ command: this
1947
+ };
1948
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
1949
+ this.emit("beforeHelp", eventContext);
1950
+ let helpInformation = this.helpInformation({ error: outputContext.error });
1951
+ if (deprecatedCallback) {
1952
+ helpInformation = deprecatedCallback(helpInformation);
1953
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
1954
+ throw new Error("outputHelp callback must return a string or a Buffer");
1955
+ }
1956
+ }
1957
+ outputContext.write(helpInformation);
1958
+ if (this._getHelpOption()?.long) {
1959
+ this.emit(this._getHelpOption().long);
1960
+ }
1961
+ this.emit("afterHelp", eventContext);
1962
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
1963
+ }
1964
+ helpOption(flags, description) {
1965
+ if (typeof flags === "boolean") {
1966
+ if (flags) {
1967
+ this._helpOption = this._helpOption ?? undefined;
1968
+ } else {
1969
+ this._helpOption = null;
1970
+ }
1971
+ return this;
1972
+ }
1973
+ flags = flags ?? "-h, --help";
1974
+ description = description ?? "display help for command";
1975
+ this._helpOption = this.createOption(flags, description);
1976
+ return this;
1977
+ }
1978
+ _getHelpOption() {
1979
+ if (this._helpOption === undefined) {
1980
+ this.helpOption(undefined, undefined);
1981
+ }
1982
+ return this._helpOption;
1983
+ }
1984
+ addHelpOption(option) {
1985
+ this._helpOption = option;
1986
+ return this;
1987
+ }
1988
+ help(contextOptions) {
1989
+ this.outputHelp(contextOptions);
1990
+ let exitCode = Number(process2.exitCode ?? 0);
1991
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
1992
+ exitCode = 1;
1993
+ }
1994
+ this._exit(exitCode, "commander.help", "(outputHelp)");
1995
+ }
1996
+ addHelpText(position, text) {
1997
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
1998
+ if (!allowedValues.includes(position)) {
1999
+ throw new Error(`Unexpected value for position to addHelpText.
2000
+ Expecting one of '${allowedValues.join("', '")}'`);
2001
+ }
2002
+ const helpEvent = `${position}Help`;
2003
+ this.on(helpEvent, (context) => {
2004
+ let helpStr;
2005
+ if (typeof text === "function") {
2006
+ helpStr = text({ error: context.error, command: context.command });
2007
+ } else {
2008
+ helpStr = text;
2009
+ }
2010
+ if (helpStr) {
2011
+ context.write(`${helpStr}
2012
+ `);
2013
+ }
2014
+ });
2015
+ return this;
2016
+ }
2017
+ _outputHelpIfRequested(args) {
2018
+ const helpOption = this._getHelpOption();
2019
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2020
+ if (helpRequested) {
2021
+ this.outputHelp();
2022
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2023
+ }
2024
+ }
2025
+ }
2026
+ function incrementNodeInspectorPort(args) {
2027
+ return args.map((arg) => {
2028
+ if (!arg.startsWith("--inspect")) {
2029
+ return arg;
2030
+ }
2031
+ let debugOption;
2032
+ let debugHost = "127.0.0.1";
2033
+ let debugPort = "9229";
2034
+ let match;
2035
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2036
+ debugOption = match[1];
2037
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2038
+ debugOption = match[1];
2039
+ if (/^\d+$/.test(match[3])) {
2040
+ debugPort = match[3];
2041
+ } else {
2042
+ debugHost = match[3];
2043
+ }
2044
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2045
+ debugOption = match[1];
2046
+ debugHost = match[3];
2047
+ debugPort = match[4];
2048
+ }
2049
+ if (debugOption && debugPort !== "0") {
2050
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2051
+ }
2052
+ return arg;
2053
+ });
2054
+ }
2055
+ function useColor() {
2056
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
2057
+ return false;
2058
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== undefined)
2059
+ return true;
2060
+ return;
2061
+ }
2062
+ exports.Command = Command;
2063
+ exports.useColor = useColor;
2064
+ });
2065
+
2066
+ // ../../node_modules/commander/index.js
2067
+ var require_commander = __commonJS((exports) => {
2068
+ var { Argument } = require_argument();
2069
+ var { Command } = require_command();
2070
+ var { CommanderError, InvalidArgumentError } = require_error();
2071
+ var { Help } = require_help();
2072
+ var { Option } = require_option();
2073
+ exports.program = new Command;
2074
+ exports.createCommand = (name) => new Command(name);
2075
+ exports.createOption = (flags, description) => new Option(flags, description);
2076
+ exports.createArgument = (name, description) => new Argument(name, description);
2077
+ exports.Command = Command;
2078
+ exports.Option = Option;
2079
+ exports.Argument = Argument;
2080
+ exports.Help = Help;
2081
+ exports.CommanderError = CommanderError;
2082
+ exports.InvalidArgumentError = InvalidArgumentError;
2083
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
2084
+ });
2085
+
2086
+ // src/config.ts
2087
+ import { homedir } from "os";
2088
+ import { join } from "path";
2089
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
2090
+ function ensureConfigDir() {
2091
+ if (!existsSync(CONFIG_DIR)) {
2092
+ mkdirSync(CONFIG_DIR, { recursive: true, mode: 448 });
2093
+ }
2094
+ }
2095
+ function loadCredentials() {
2096
+ try {
2097
+ if (!existsSync(CREDENTIALS_FILE))
2098
+ return null;
2099
+ const raw = readFileSync(CREDENTIALS_FILE, "utf-8");
2100
+ return JSON.parse(raw);
2101
+ } catch {
2102
+ return null;
2103
+ }
2104
+ }
2105
+ function saveCredentials(creds) {
2106
+ ensureConfigDir();
2107
+ writeFileSync(CREDENTIALS_FILE, JSON.stringify(creds, null, 2), { mode: 384 });
2108
+ }
2109
+ function clearCredentials() {
2110
+ try {
2111
+ if (existsSync(CREDENTIALS_FILE)) {
2112
+ writeFileSync(CREDENTIALS_FILE, "{}", { mode: 384 });
2113
+ }
2114
+ } catch {}
2115
+ }
2116
+ function loadBagdockJson(dir) {
2117
+ const file = join(dir, "bagdock.json");
2118
+ if (!existsSync(file))
2119
+ return null;
2120
+ try {
2121
+ return JSON.parse(readFileSync(file, "utf-8"));
2122
+ } catch {
2123
+ return null;
2124
+ }
2125
+ }
2126
+ var CONFIG_DIR, CREDENTIALS_FILE, API_BASE, DASHBOARD_BASE;
2127
+ var init_config = __esm(() => {
2128
+ CONFIG_DIR = join(homedir(), ".bagdock");
2129
+ CREDENTIALS_FILE = join(CONFIG_DIR, "credentials.json");
2130
+ API_BASE = process.env.BAGDOCK_API_URL ?? "https://api.bagdock.com";
2131
+ DASHBOARD_BASE = process.env.BAGDOCK_DASHBOARD_URL ?? "https://dashboard.bagdock.com";
2132
+ });
2133
+
2134
+ // ../../node_modules/chalk/source/vendor/ansi-styles/index.js
2135
+ function assembleStyles() {
2136
+ const codes = new Map;
2137
+ for (const [groupName, group] of Object.entries(styles)) {
2138
+ for (const [styleName, style] of Object.entries(group)) {
2139
+ styles[styleName] = {
2140
+ open: `\x1B[${style[0]}m`,
2141
+ close: `\x1B[${style[1]}m`
2142
+ };
2143
+ group[styleName] = styles[styleName];
2144
+ codes.set(style[0], style[1]);
2145
+ }
2146
+ Object.defineProperty(styles, groupName, {
2147
+ value: group,
2148
+ enumerable: false
2149
+ });
2150
+ }
2151
+ Object.defineProperty(styles, "codes", {
2152
+ value: codes,
2153
+ enumerable: false
2154
+ });
2155
+ styles.color.close = "\x1B[39m";
2156
+ styles.bgColor.close = "\x1B[49m";
2157
+ styles.color.ansi = wrapAnsi16();
2158
+ styles.color.ansi256 = wrapAnsi256();
2159
+ styles.color.ansi16m = wrapAnsi16m();
2160
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
2161
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
2162
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
2163
+ Object.defineProperties(styles, {
2164
+ rgbToAnsi256: {
2165
+ value(red, green, blue) {
2166
+ if (red === green && green === blue) {
2167
+ if (red < 8) {
2168
+ return 16;
2169
+ }
2170
+ if (red > 248) {
2171
+ return 231;
2172
+ }
2173
+ return Math.round((red - 8) / 247 * 24) + 232;
2174
+ }
2175
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
2176
+ },
2177
+ enumerable: false
2178
+ },
2179
+ hexToRgb: {
2180
+ value(hex) {
2181
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
2182
+ if (!matches) {
2183
+ return [0, 0, 0];
2184
+ }
2185
+ let [colorString] = matches;
2186
+ if (colorString.length === 3) {
2187
+ colorString = [...colorString].map((character) => character + character).join("");
2188
+ }
2189
+ const integer = Number.parseInt(colorString, 16);
2190
+ return [
2191
+ integer >> 16 & 255,
2192
+ integer >> 8 & 255,
2193
+ integer & 255
2194
+ ];
2195
+ },
2196
+ enumerable: false
2197
+ },
2198
+ hexToAnsi256: {
2199
+ value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
2200
+ enumerable: false
2201
+ },
2202
+ ansi256ToAnsi: {
2203
+ value(code) {
2204
+ if (code < 8) {
2205
+ return 30 + code;
2206
+ }
2207
+ if (code < 16) {
2208
+ return 90 + (code - 8);
2209
+ }
2210
+ let red;
2211
+ let green;
2212
+ let blue;
2213
+ if (code >= 232) {
2214
+ red = ((code - 232) * 10 + 8) / 255;
2215
+ green = red;
2216
+ blue = red;
2217
+ } else {
2218
+ code -= 16;
2219
+ const remainder = code % 36;
2220
+ red = Math.floor(code / 36) / 5;
2221
+ green = Math.floor(remainder / 6) / 5;
2222
+ blue = remainder % 6 / 5;
2223
+ }
2224
+ const value = Math.max(red, green, blue) * 2;
2225
+ if (value === 0) {
2226
+ return 30;
2227
+ }
2228
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
2229
+ if (value === 2) {
2230
+ result += 60;
2231
+ }
2232
+ return result;
2233
+ },
2234
+ enumerable: false
2235
+ },
2236
+ rgbToAnsi: {
2237
+ value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
2238
+ enumerable: false
2239
+ },
2240
+ hexToAnsi: {
2241
+ value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
2242
+ enumerable: false
2243
+ }
2244
+ });
2245
+ return styles;
2246
+ }
2247
+ var ANSI_BACKGROUND_OFFSET = 10, wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`, wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`, wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`, styles, modifierNames, foregroundColorNames, backgroundColorNames, colorNames, ansiStyles, ansi_styles_default;
2248
+ var init_ansi_styles = __esm(() => {
2249
+ styles = {
2250
+ modifier: {
2251
+ reset: [0, 0],
2252
+ bold: [1, 22],
2253
+ dim: [2, 22],
2254
+ italic: [3, 23],
2255
+ underline: [4, 24],
2256
+ overline: [53, 55],
2257
+ inverse: [7, 27],
2258
+ hidden: [8, 28],
2259
+ strikethrough: [9, 29]
2260
+ },
2261
+ color: {
2262
+ black: [30, 39],
2263
+ red: [31, 39],
2264
+ green: [32, 39],
2265
+ yellow: [33, 39],
2266
+ blue: [34, 39],
2267
+ magenta: [35, 39],
2268
+ cyan: [36, 39],
2269
+ white: [37, 39],
2270
+ blackBright: [90, 39],
2271
+ gray: [90, 39],
2272
+ grey: [90, 39],
2273
+ redBright: [91, 39],
2274
+ greenBright: [92, 39],
2275
+ yellowBright: [93, 39],
2276
+ blueBright: [94, 39],
2277
+ magentaBright: [95, 39],
2278
+ cyanBright: [96, 39],
2279
+ whiteBright: [97, 39]
2280
+ },
2281
+ bgColor: {
2282
+ bgBlack: [40, 49],
2283
+ bgRed: [41, 49],
2284
+ bgGreen: [42, 49],
2285
+ bgYellow: [43, 49],
2286
+ bgBlue: [44, 49],
2287
+ bgMagenta: [45, 49],
2288
+ bgCyan: [46, 49],
2289
+ bgWhite: [47, 49],
2290
+ bgBlackBright: [100, 49],
2291
+ bgGray: [100, 49],
2292
+ bgGrey: [100, 49],
2293
+ bgRedBright: [101, 49],
2294
+ bgGreenBright: [102, 49],
2295
+ bgYellowBright: [103, 49],
2296
+ bgBlueBright: [104, 49],
2297
+ bgMagentaBright: [105, 49],
2298
+ bgCyanBright: [106, 49],
2299
+ bgWhiteBright: [107, 49]
2300
+ }
2301
+ };
2302
+ modifierNames = Object.keys(styles.modifier);
2303
+ foregroundColorNames = Object.keys(styles.color);
2304
+ backgroundColorNames = Object.keys(styles.bgColor);
2305
+ colorNames = [...foregroundColorNames, ...backgroundColorNames];
2306
+ ansiStyles = assembleStyles();
2307
+ ansi_styles_default = ansiStyles;
2308
+ });
2309
+
2310
+ // ../../node_modules/chalk/source/vendor/supports-color/index.js
2311
+ import process2 from "node:process";
2312
+ import os from "node:os";
2313
+ import tty from "node:tty";
2314
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process2.argv) {
2315
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
2316
+ const position = argv.indexOf(prefix + flag);
2317
+ const terminatorPosition = argv.indexOf("--");
2318
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
2319
+ }
2320
+ function envForceColor() {
2321
+ if ("FORCE_COLOR" in env) {
2322
+ if (env.FORCE_COLOR === "true") {
2323
+ return 1;
2324
+ }
2325
+ if (env.FORCE_COLOR === "false") {
2326
+ return 0;
2327
+ }
2328
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
2329
+ }
2330
+ }
2331
+ function translateLevel(level) {
2332
+ if (level === 0) {
2333
+ return false;
2334
+ }
2335
+ return {
2336
+ level,
2337
+ hasBasic: true,
2338
+ has256: level >= 2,
2339
+ has16m: level >= 3
2340
+ };
2341
+ }
2342
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
2343
+ const noFlagForceColor = envForceColor();
2344
+ if (noFlagForceColor !== undefined) {
2345
+ flagForceColor = noFlagForceColor;
2346
+ }
2347
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
2348
+ if (forceColor === 0) {
2349
+ return 0;
2350
+ }
2351
+ if (sniffFlags) {
2352
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
2353
+ return 3;
2354
+ }
2355
+ if (hasFlag("color=256")) {
2356
+ return 2;
2357
+ }
2358
+ }
2359
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
2360
+ return 1;
2361
+ }
2362
+ if (haveStream && !streamIsTTY && forceColor === undefined) {
2363
+ return 0;
2364
+ }
2365
+ const min = forceColor || 0;
2366
+ if (env.TERM === "dumb") {
2367
+ return min;
2368
+ }
2369
+ if (process2.platform === "win32") {
2370
+ const osRelease = os.release().split(".");
2371
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
2372
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
2373
+ }
2374
+ return 1;
2375
+ }
2376
+ if ("CI" in env) {
2377
+ if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => (key in env))) {
2378
+ return 3;
2379
+ }
2380
+ if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => (sign in env)) || env.CI_NAME === "codeship") {
2381
+ return 1;
2382
+ }
2383
+ return min;
2384
+ }
2385
+ if ("TEAMCITY_VERSION" in env) {
2386
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
2387
+ }
2388
+ if (env.COLORTERM === "truecolor") {
2389
+ return 3;
2390
+ }
2391
+ if (env.TERM === "xterm-kitty") {
2392
+ return 3;
2393
+ }
2394
+ if (env.TERM === "xterm-ghostty") {
2395
+ return 3;
2396
+ }
2397
+ if (env.TERM === "wezterm") {
2398
+ return 3;
2399
+ }
2400
+ if ("TERM_PROGRAM" in env) {
2401
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
2402
+ switch (env.TERM_PROGRAM) {
2403
+ case "iTerm.app": {
2404
+ return version >= 3 ? 3 : 2;
2405
+ }
2406
+ case "Apple_Terminal": {
2407
+ return 2;
2408
+ }
2409
+ }
2410
+ }
2411
+ if (/-256(color)?$/i.test(env.TERM)) {
2412
+ return 2;
2413
+ }
2414
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
2415
+ return 1;
2416
+ }
2417
+ if ("COLORTERM" in env) {
2418
+ return 1;
2419
+ }
2420
+ return min;
2421
+ }
2422
+ function createSupportsColor(stream, options = {}) {
2423
+ const level = _supportsColor(stream, {
2424
+ streamIsTTY: stream && stream.isTTY,
2425
+ ...options
2426
+ });
2427
+ return translateLevel(level);
2428
+ }
2429
+ var env, flagForceColor, supportsColor, supports_color_default;
2430
+ var init_supports_color = __esm(() => {
2431
+ ({ env } = process2);
2432
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
2433
+ flagForceColor = 0;
2434
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
2435
+ flagForceColor = 1;
2436
+ }
2437
+ supportsColor = {
2438
+ stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
2439
+ stderr: createSupportsColor({ isTTY: tty.isatty(2) })
2440
+ };
2441
+ supports_color_default = supportsColor;
2442
+ });
2443
+
2444
+ // ../../node_modules/chalk/source/utilities.js
2445
+ function stringReplaceAll(string, substring, replacer) {
2446
+ let index = string.indexOf(substring);
2447
+ if (index === -1) {
2448
+ return string;
2449
+ }
2450
+ const substringLength = substring.length;
2451
+ let endIndex = 0;
2452
+ let returnValue = "";
2453
+ do {
2454
+ returnValue += string.slice(endIndex, index) + substring + replacer;
2455
+ endIndex = index + substringLength;
2456
+ index = string.indexOf(substring, endIndex);
2457
+ } while (index !== -1);
2458
+ returnValue += string.slice(endIndex);
2459
+ return returnValue;
2460
+ }
2461
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
2462
+ let endIndex = 0;
2463
+ let returnValue = "";
2464
+ do {
2465
+ const gotCR = string[index - 1] === "\r";
2466
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? `\r
2467
+ ` : `
2468
+ `) + postfix;
2469
+ endIndex = index + 1;
2470
+ index = string.indexOf(`
2471
+ `, endIndex);
2472
+ } while (index !== -1);
2473
+ returnValue += string.slice(endIndex);
2474
+ return returnValue;
2475
+ }
2476
+
2477
+ // ../../node_modules/chalk/source/index.js
2478
+ function createChalk(options) {
2479
+ return chalkFactory(options);
2480
+ }
2481
+ var stdoutColor, stderrColor, GENERATOR, STYLER, IS_EMPTY, levelMapping, styles2, applyOptions = (object, options = {}) => {
2482
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
2483
+ throw new Error("The `level` option should be an integer from 0 to 3");
2484
+ }
2485
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
2486
+ object.level = options.level === undefined ? colorLevel : options.level;
2487
+ }, chalkFactory = (options) => {
2488
+ const chalk = (...strings) => strings.join(" ");
2489
+ applyOptions(chalk, options);
2490
+ Object.setPrototypeOf(chalk, createChalk.prototype);
2491
+ return chalk;
2492
+ }, getModelAnsi = (model, level, type, ...arguments_) => {
2493
+ if (model === "rgb") {
2494
+ if (level === "ansi16m") {
2495
+ return ansi_styles_default[type].ansi16m(...arguments_);
2496
+ }
2497
+ if (level === "ansi256") {
2498
+ return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
2499
+ }
2500
+ return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
2501
+ }
2502
+ if (model === "hex") {
2503
+ return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
2504
+ }
2505
+ return ansi_styles_default[type][model](...arguments_);
2506
+ }, usedModels, proto, createStyler = (open, close, parent) => {
2507
+ let openAll;
2508
+ let closeAll;
2509
+ if (parent === undefined) {
2510
+ openAll = open;
2511
+ closeAll = close;
2512
+ } else {
2513
+ openAll = parent.openAll + open;
2514
+ closeAll = close + parent.closeAll;
2515
+ }
2516
+ return {
2517
+ open,
2518
+ close,
2519
+ openAll,
2520
+ closeAll,
2521
+ parent
2522
+ };
2523
+ }, createBuilder = (self, _styler, _isEmpty) => {
2524
+ const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
2525
+ Object.setPrototypeOf(builder, proto);
2526
+ builder[GENERATOR] = self;
2527
+ builder[STYLER] = _styler;
2528
+ builder[IS_EMPTY] = _isEmpty;
2529
+ return builder;
2530
+ }, applyStyle = (self, string) => {
2531
+ if (self.level <= 0 || !string) {
2532
+ return self[IS_EMPTY] ? "" : string;
2533
+ }
2534
+ let styler = self[STYLER];
2535
+ if (styler === undefined) {
2536
+ return string;
2537
+ }
2538
+ const { openAll, closeAll } = styler;
2539
+ if (string.includes("\x1B")) {
2540
+ while (styler !== undefined) {
2541
+ string = stringReplaceAll(string, styler.close, styler.open);
2542
+ styler = styler.parent;
2543
+ }
2544
+ }
2545
+ const lfIndex = string.indexOf(`
2546
+ `);
2547
+ if (lfIndex !== -1) {
2548
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
2549
+ }
2550
+ return openAll + string + closeAll;
2551
+ }, chalk, chalkStderr, source_default;
2552
+ var init_source = __esm(() => {
2553
+ init_ansi_styles();
2554
+ init_supports_color();
2555
+ ({ stdout: stdoutColor, stderr: stderrColor } = supports_color_default);
2556
+ GENERATOR = Symbol("GENERATOR");
2557
+ STYLER = Symbol("STYLER");
2558
+ IS_EMPTY = Symbol("IS_EMPTY");
2559
+ levelMapping = [
2560
+ "ansi",
2561
+ "ansi",
2562
+ "ansi256",
2563
+ "ansi16m"
2564
+ ];
2565
+ styles2 = Object.create(null);
2566
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
2567
+ for (const [styleName, style] of Object.entries(ansi_styles_default)) {
2568
+ styles2[styleName] = {
2569
+ get() {
2570
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
2571
+ Object.defineProperty(this, styleName, { value: builder });
2572
+ return builder;
2573
+ }
2574
+ };
2575
+ }
2576
+ styles2.visible = {
2577
+ get() {
2578
+ const builder = createBuilder(this, this[STYLER], true);
2579
+ Object.defineProperty(this, "visible", { value: builder });
2580
+ return builder;
2581
+ }
2582
+ };
2583
+ usedModels = ["rgb", "hex", "ansi256"];
2584
+ for (const model of usedModels) {
2585
+ styles2[model] = {
2586
+ get() {
2587
+ const { level } = this;
2588
+ return function(...arguments_) {
2589
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
2590
+ return createBuilder(this, styler, this[IS_EMPTY]);
2591
+ };
2592
+ }
2593
+ };
2594
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
2595
+ styles2[bgModel] = {
2596
+ get() {
2597
+ const { level } = this;
2598
+ return function(...arguments_) {
2599
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
2600
+ return createBuilder(this, styler, this[IS_EMPTY]);
2601
+ };
2602
+ }
2603
+ };
2604
+ }
2605
+ proto = Object.defineProperties(() => {}, {
2606
+ ...styles2,
2607
+ level: {
2608
+ enumerable: true,
2609
+ get() {
2610
+ return this[GENERATOR].level;
2611
+ },
2612
+ set(level) {
2613
+ this[GENERATOR].level = level;
2614
+ }
2615
+ }
2616
+ });
2617
+ Object.defineProperties(createChalk.prototype, styles2);
2618
+ chalk = createChalk();
2619
+ chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
2620
+ source_default = chalk;
2621
+ });
2622
+
2623
+ // ../../node_modules/is-docker/index.js
2624
+ import fs from "node:fs";
2625
+ function hasDockerEnv() {
2626
+ try {
2627
+ fs.statSync("/.dockerenv");
2628
+ return true;
2629
+ } catch {
2630
+ return false;
2631
+ }
2632
+ }
2633
+ function hasDockerCGroup() {
2634
+ try {
2635
+ return fs.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
2636
+ } catch {
2637
+ return false;
2638
+ }
2639
+ }
2640
+ function isDocker() {
2641
+ if (isDockerCached === undefined) {
2642
+ isDockerCached = hasDockerEnv() || hasDockerCGroup();
2643
+ }
2644
+ return isDockerCached;
2645
+ }
2646
+ var isDockerCached;
2647
+ var init_is_docker = () => {};
2648
+
2649
+ // ../../node_modules/is-inside-container/index.js
2650
+ import fs2 from "node:fs";
2651
+ function isInsideContainer() {
2652
+ if (cachedResult === undefined) {
2653
+ cachedResult = hasContainerEnv() || isDocker();
2654
+ }
2655
+ return cachedResult;
2656
+ }
2657
+ var cachedResult, hasContainerEnv = () => {
2658
+ try {
2659
+ fs2.statSync("/run/.containerenv");
2660
+ return true;
2661
+ } catch {
2662
+ return false;
2663
+ }
2664
+ };
2665
+ var init_is_inside_container = __esm(() => {
2666
+ init_is_docker();
2667
+ });
2668
+
2669
+ // ../../node_modules/is-wsl/index.js
2670
+ import process3 from "node:process";
2671
+ import os2 from "node:os";
2672
+ import fs3 from "node:fs";
2673
+ var isWsl = () => {
2674
+ if (process3.platform !== "linux") {
2675
+ return false;
2676
+ }
2677
+ if (os2.release().toLowerCase().includes("microsoft")) {
2678
+ if (isInsideContainer()) {
2679
+ return false;
2680
+ }
2681
+ return true;
2682
+ }
2683
+ try {
2684
+ if (fs3.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft")) {
2685
+ return !isInsideContainer();
2686
+ }
2687
+ } catch {}
2688
+ if (fs3.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop") || fs3.existsSync("/run/WSL")) {
2689
+ return !isInsideContainer();
2690
+ }
2691
+ return false;
2692
+ }, is_wsl_default;
2693
+ var init_is_wsl = __esm(() => {
2694
+ init_is_inside_container();
2695
+ is_wsl_default = process3.env.__IS_WSL_TEST__ ? isWsl : isWsl();
2696
+ });
2697
+
2698
+ // ../../node_modules/wsl-utils/index.js
2699
+ import process4 from "node:process";
2700
+ import fs4, { constants as fsConstants } from "node:fs/promises";
2701
+ var wslDrivesMountPoint, powerShellPathFromWsl = async () => {
2702
+ const mountPoint = await wslDrivesMountPoint();
2703
+ return `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;
2704
+ }, powerShellPath = async () => {
2705
+ if (is_wsl_default) {
2706
+ return powerShellPathFromWsl();
2707
+ }
2708
+ return `${process4.env.SYSTEMROOT || process4.env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
2709
+ };
2710
+ var init_wsl_utils = __esm(() => {
2711
+ init_is_wsl();
2712
+ init_is_wsl();
2713
+ wslDrivesMountPoint = (() => {
2714
+ const defaultMountPoint = "/mnt/";
2715
+ let mountPoint;
2716
+ return async function() {
2717
+ if (mountPoint) {
2718
+ return mountPoint;
2719
+ }
2720
+ const configFilePath = "/etc/wsl.conf";
2721
+ let isConfigFileExists = false;
2722
+ try {
2723
+ await fs4.access(configFilePath, fsConstants.F_OK);
2724
+ isConfigFileExists = true;
2725
+ } catch {}
2726
+ if (!isConfigFileExists) {
2727
+ return defaultMountPoint;
2728
+ }
2729
+ const configContent = await fs4.readFile(configFilePath, { encoding: "utf8" });
2730
+ const configMountPoint = /(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);
2731
+ if (!configMountPoint) {
2732
+ return defaultMountPoint;
2733
+ }
2734
+ mountPoint = configMountPoint.groups.mountPoint.trim();
2735
+ mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
2736
+ return mountPoint;
2737
+ };
2738
+ })();
2739
+ });
2740
+
2741
+ // ../../node_modules/define-lazy-prop/index.js
2742
+ function defineLazyProperty(object, propertyName, valueGetter) {
2743
+ const define = (value) => Object.defineProperty(object, propertyName, { value, enumerable: true, writable: true });
2744
+ Object.defineProperty(object, propertyName, {
2745
+ configurable: true,
2746
+ enumerable: true,
2747
+ get() {
2748
+ const result = valueGetter();
2749
+ define(result);
2750
+ return result;
2751
+ },
2752
+ set(value) {
2753
+ define(value);
2754
+ }
2755
+ });
2756
+ return object;
2757
+ }
2758
+
2759
+ // ../../node_modules/default-browser-id/index.js
2760
+ import { promisify } from "node:util";
2761
+ import process5 from "node:process";
2762
+ import { execFile } from "node:child_process";
2763
+ async function defaultBrowserId() {
2764
+ if (process5.platform !== "darwin") {
2765
+ throw new Error("macOS only");
2766
+ }
2767
+ const { stdout } = await execFileAsync("defaults", ["read", "com.apple.LaunchServices/com.apple.launchservices.secure", "LSHandlers"]);
2768
+ const match = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout);
2769
+ const browserId = match?.groups.id ?? "com.apple.Safari";
2770
+ if (browserId === "com.apple.safari") {
2771
+ return "com.apple.Safari";
2772
+ }
2773
+ return browserId;
2774
+ }
2775
+ var execFileAsync;
2776
+ var init_default_browser_id = __esm(() => {
2777
+ execFileAsync = promisify(execFile);
2778
+ });
2779
+
2780
+ // ../../node_modules/run-applescript/index.js
2781
+ import process6 from "node:process";
2782
+ import { promisify as promisify2 } from "node:util";
2783
+ import { execFile as execFile2, execFileSync } from "node:child_process";
2784
+ async function runAppleScript(script, { humanReadableOutput = true, signal } = {}) {
2785
+ if (process6.platform !== "darwin") {
2786
+ throw new Error("macOS only");
2787
+ }
2788
+ const outputArguments = humanReadableOutput ? [] : ["-ss"];
2789
+ const execOptions = {};
2790
+ if (signal) {
2791
+ execOptions.signal = signal;
2792
+ }
2793
+ const { stdout } = await execFileAsync2("osascript", ["-e", script, outputArguments], execOptions);
2794
+ return stdout.trim();
2795
+ }
2796
+ var execFileAsync2;
2797
+ var init_run_applescript = __esm(() => {
2798
+ execFileAsync2 = promisify2(execFile2);
2799
+ });
2800
+
2801
+ // ../../node_modules/bundle-name/index.js
2802
+ async function bundleName(bundleId) {
2803
+ return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string
2804
+ tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`);
2805
+ }
2806
+ var init_bundle_name = __esm(() => {
2807
+ init_run_applescript();
2808
+ });
2809
+
2810
+ // ../../node_modules/default-browser/windows.js
2811
+ import { promisify as promisify3 } from "node:util";
2812
+ import { execFile as execFile3 } from "node:child_process";
2813
+ async function defaultBrowser(_execFileAsync = execFileAsync3) {
2814
+ const { stdout } = await _execFileAsync("reg", [
2815
+ "QUERY",
2816
+ " HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
2817
+ "/v",
2818
+ "ProgId"
2819
+ ]);
2820
+ const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);
2821
+ if (!match) {
2822
+ throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
2823
+ }
2824
+ const { id } = match.groups;
2825
+ const dotIndex = id.lastIndexOf(".");
2826
+ const hyphenIndex = id.lastIndexOf("-");
2827
+ const baseIdByDot = dotIndex === -1 ? undefined : id.slice(0, dotIndex);
2828
+ const baseIdByHyphen = hyphenIndex === -1 ? undefined : id.slice(0, hyphenIndex);
2829
+ return windowsBrowserProgIds[id] ?? windowsBrowserProgIds[baseIdByDot] ?? windowsBrowserProgIds[baseIdByHyphen] ?? { name: id, id };
2830
+ }
2831
+ var execFileAsync3, windowsBrowserProgIds, _windowsBrowserProgIdMap, UnknownBrowserError;
2832
+ var init_windows = __esm(() => {
2833
+ execFileAsync3 = promisify3(execFile3);
2834
+ windowsBrowserProgIds = {
2835
+ MSEdgeHTM: { name: "Edge", id: "com.microsoft.edge" },
2836
+ MSEdgeBHTML: { name: "Edge Beta", id: "com.microsoft.edge.beta" },
2837
+ MSEdgeDHTML: { name: "Edge Dev", id: "com.microsoft.edge.dev" },
2838
+ AppXq0fevzme2pys62n3e0fbqa7peapykr8v: { name: "Edge", id: "com.microsoft.edge.old" },
2839
+ ChromeHTML: { name: "Chrome", id: "com.google.chrome" },
2840
+ ChromeBHTML: { name: "Chrome Beta", id: "com.google.chrome.beta" },
2841
+ ChromeDHTML: { name: "Chrome Dev", id: "com.google.chrome.dev" },
2842
+ ChromiumHTM: { name: "Chromium", id: "org.chromium.Chromium" },
2843
+ BraveHTML: { name: "Brave", id: "com.brave.Browser" },
2844
+ BraveBHTML: { name: "Brave Beta", id: "com.brave.Browser.beta" },
2845
+ BraveDHTML: { name: "Brave Dev", id: "com.brave.Browser.dev" },
2846
+ BraveSSHTM: { name: "Brave Nightly", id: "com.brave.Browser.nightly" },
2847
+ FirefoxURL: { name: "Firefox", id: "org.mozilla.firefox" },
2848
+ OperaStable: { name: "Opera", id: "com.operasoftware.Opera" },
2849
+ VivaldiHTM: { name: "Vivaldi", id: "com.vivaldi.Vivaldi" },
2850
+ "IE.HTTP": { name: "Internet Explorer", id: "com.microsoft.ie" }
2851
+ };
2852
+ _windowsBrowserProgIdMap = new Map(Object.entries(windowsBrowserProgIds));
2853
+ UnknownBrowserError = class UnknownBrowserError extends Error {
2854
+ };
2855
+ });
2856
+
2857
+ // ../../node_modules/default-browser/index.js
2858
+ import { promisify as promisify4 } from "node:util";
2859
+ import process7 from "node:process";
2860
+ import { execFile as execFile4 } from "node:child_process";
2861
+ async function defaultBrowser2() {
2862
+ if (process7.platform === "darwin") {
2863
+ const id = await defaultBrowserId();
2864
+ const name = await bundleName(id);
2865
+ return { name, id };
2866
+ }
2867
+ if (process7.platform === "linux") {
2868
+ const { stdout } = await execFileAsync4("xdg-mime", ["query", "default", "x-scheme-handler/http"]);
2869
+ const id = stdout.trim();
2870
+ const name = titleize(id.replace(/.desktop$/, "").replace("-", " "));
2871
+ return { name, id };
2872
+ }
2873
+ if (process7.platform === "win32") {
2874
+ return defaultBrowser();
2875
+ }
2876
+ throw new Error("Only macOS, Linux, and Windows are supported");
2877
+ }
2878
+ var execFileAsync4, titleize = (string) => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase());
2879
+ var init_default_browser = __esm(() => {
2880
+ init_default_browser_id();
2881
+ init_bundle_name();
2882
+ init_windows();
2883
+ execFileAsync4 = promisify4(execFile4);
2884
+ });
2885
+
2886
+ // ../../node_modules/open/index.js
2887
+ var exports_open = {};
2888
+ __export(exports_open, {
2889
+ openApp: () => openApp,
2890
+ default: () => open_default,
2891
+ apps: () => apps
2892
+ });
2893
+ import process8 from "node:process";
2894
+ import { Buffer as Buffer2 } from "node:buffer";
2895
+ import path from "node:path";
2896
+ import { fileURLToPath } from "node:url";
2897
+ import { promisify as promisify5 } from "node:util";
2898
+ import childProcess from "node:child_process";
2899
+ import fs5, { constants as fsConstants2 } from "node:fs/promises";
2900
+ async function getWindowsDefaultBrowserFromWsl() {
2901
+ const powershellPath = await powerShellPath();
2902
+ const rawCommand = String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`;
2903
+ const encodedCommand = Buffer2.from(rawCommand, "utf16le").toString("base64");
2904
+ const { stdout } = await execFile5(powershellPath, [
2905
+ "-NoProfile",
2906
+ "-NonInteractive",
2907
+ "-ExecutionPolicy",
2908
+ "Bypass",
2909
+ "-EncodedCommand",
2910
+ encodedCommand
2911
+ ], { encoding: "utf8" });
2912
+ const progId = stdout.trim();
2913
+ const browserMap = {
2914
+ ChromeHTML: "com.google.chrome",
2915
+ BraveHTML: "com.brave.Browser",
2916
+ MSEdgeHTM: "com.microsoft.edge",
2917
+ FirefoxURL: "org.mozilla.firefox"
2918
+ };
2919
+ return browserMap[progId] ? { id: browserMap[progId] } : {};
2920
+ }
2921
+ function detectArchBinary(binary) {
2922
+ if (typeof binary === "string" || Array.isArray(binary)) {
2923
+ return binary;
2924
+ }
2925
+ const { [arch]: archBinary } = binary;
2926
+ if (!archBinary) {
2927
+ throw new Error(`${arch} is not supported`);
2928
+ }
2929
+ return archBinary;
2930
+ }
2931
+ function detectPlatformBinary({ [platform]: platformBinary }, { wsl }) {
2932
+ if (wsl && is_wsl_default) {
2933
+ return detectArchBinary(wsl);
2934
+ }
2935
+ if (!platformBinary) {
2936
+ throw new Error(`${platform} is not supported`);
2937
+ }
2938
+ return detectArchBinary(platformBinary);
2939
+ }
2940
+ var execFile5, __dirname2, localXdgOpenPath, platform, arch, pTryEach = async (array, mapper) => {
2941
+ let latestError;
2942
+ for (const item of array) {
2943
+ try {
2944
+ return await mapper(item);
2945
+ } catch (error) {
2946
+ latestError = error;
2947
+ }
2948
+ }
2949
+ throw latestError;
2950
+ }, baseOpen = async (options) => {
2951
+ options = {
2952
+ wait: false,
2953
+ background: false,
2954
+ newInstance: false,
2955
+ allowNonzeroExitCode: false,
2956
+ ...options
2957
+ };
2958
+ if (Array.isArray(options.app)) {
2959
+ return pTryEach(options.app, (singleApp) => baseOpen({
2960
+ ...options,
2961
+ app: singleApp
2962
+ }));
2963
+ }
2964
+ let { name: app, arguments: appArguments = [] } = options.app ?? {};
2965
+ appArguments = [...appArguments];
2966
+ if (Array.isArray(app)) {
2967
+ return pTryEach(app, (appName) => baseOpen({
2968
+ ...options,
2969
+ app: {
2970
+ name: appName,
2971
+ arguments: appArguments
2972
+ }
2973
+ }));
2974
+ }
2975
+ if (app === "browser" || app === "browserPrivate") {
2976
+ const ids = {
2977
+ "com.google.chrome": "chrome",
2978
+ "google-chrome.desktop": "chrome",
2979
+ "com.brave.Browser": "brave",
2980
+ "org.mozilla.firefox": "firefox",
2981
+ "firefox.desktop": "firefox",
2982
+ "com.microsoft.msedge": "edge",
2983
+ "com.microsoft.edge": "edge",
2984
+ "com.microsoft.edgemac": "edge",
2985
+ "microsoft-edge.desktop": "edge"
2986
+ };
2987
+ const flags = {
2988
+ chrome: "--incognito",
2989
+ brave: "--incognito",
2990
+ firefox: "--private-window",
2991
+ edge: "--inPrivate"
2992
+ };
2993
+ const browser = is_wsl_default ? await getWindowsDefaultBrowserFromWsl() : await defaultBrowser2();
2994
+ if (browser.id in ids) {
2995
+ const browserName = ids[browser.id];
2996
+ if (app === "browserPrivate") {
2997
+ appArguments.push(flags[browserName]);
2998
+ }
2999
+ return baseOpen({
3000
+ ...options,
3001
+ app: {
3002
+ name: apps[browserName],
3003
+ arguments: appArguments
3004
+ }
3005
+ });
3006
+ }
3007
+ throw new Error(`${browser.name} is not supported as a default browser`);
3008
+ }
3009
+ let command;
3010
+ const cliArguments = [];
3011
+ const childProcessOptions = {};
3012
+ if (platform === "darwin") {
3013
+ command = "open";
3014
+ if (options.wait) {
3015
+ cliArguments.push("--wait-apps");
3016
+ }
3017
+ if (options.background) {
3018
+ cliArguments.push("--background");
3019
+ }
3020
+ if (options.newInstance) {
3021
+ cliArguments.push("--new");
3022
+ }
3023
+ if (app) {
3024
+ cliArguments.push("-a", app);
3025
+ }
3026
+ } else if (platform === "win32" || is_wsl_default && !isInsideContainer() && !app) {
3027
+ command = await powerShellPath();
3028
+ cliArguments.push("-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand");
3029
+ if (!is_wsl_default) {
3030
+ childProcessOptions.windowsVerbatimArguments = true;
3031
+ }
3032
+ const encodedArguments = ["Start"];
3033
+ if (options.wait) {
3034
+ encodedArguments.push("-Wait");
3035
+ }
3036
+ if (app) {
3037
+ encodedArguments.push(`"\`"${app}\`""`);
3038
+ if (options.target) {
3039
+ appArguments.push(options.target);
3040
+ }
3041
+ } else if (options.target) {
3042
+ encodedArguments.push(`"${options.target}"`);
3043
+ }
3044
+ if (appArguments.length > 0) {
3045
+ appArguments = appArguments.map((argument) => `"\`"${argument}\`""`);
3046
+ encodedArguments.push("-ArgumentList", appArguments.join(","));
3047
+ }
3048
+ options.target = Buffer2.from(encodedArguments.join(" "), "utf16le").toString("base64");
3049
+ } else {
3050
+ if (app) {
3051
+ command = app;
3052
+ } else {
3053
+ const isBundled = !__dirname2 || __dirname2 === "/";
3054
+ let exeLocalXdgOpen = false;
3055
+ try {
3056
+ await fs5.access(localXdgOpenPath, fsConstants2.X_OK);
3057
+ exeLocalXdgOpen = true;
3058
+ } catch {}
3059
+ const useSystemXdgOpen = process8.versions.electron ?? (platform === "android" || isBundled || !exeLocalXdgOpen);
3060
+ command = useSystemXdgOpen ? "xdg-open" : localXdgOpenPath;
3061
+ }
3062
+ if (appArguments.length > 0) {
3063
+ cliArguments.push(...appArguments);
3064
+ }
3065
+ if (!options.wait) {
3066
+ childProcessOptions.stdio = "ignore";
3067
+ childProcessOptions.detached = true;
3068
+ }
3069
+ }
3070
+ if (platform === "darwin" && appArguments.length > 0) {
3071
+ cliArguments.push("--args", ...appArguments);
3072
+ }
3073
+ if (options.target) {
3074
+ cliArguments.push(options.target);
3075
+ }
3076
+ const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
3077
+ if (options.wait) {
3078
+ return new Promise((resolve, reject) => {
3079
+ subprocess.once("error", reject);
3080
+ subprocess.once("close", (exitCode) => {
3081
+ if (!options.allowNonzeroExitCode && exitCode > 0) {
3082
+ reject(new Error(`Exited with code ${exitCode}`));
3083
+ return;
3084
+ }
3085
+ resolve(subprocess);
3086
+ });
3087
+ });
3088
+ }
3089
+ subprocess.unref();
3090
+ return subprocess;
3091
+ }, open = (target, options) => {
3092
+ if (typeof target !== "string") {
3093
+ throw new TypeError("Expected a `target`");
3094
+ }
3095
+ return baseOpen({
3096
+ ...options,
3097
+ target
3098
+ });
3099
+ }, openApp = (name, options) => {
3100
+ if (typeof name !== "string" && !Array.isArray(name)) {
3101
+ throw new TypeError("Expected a valid `name`");
3102
+ }
3103
+ const { arguments: appArguments = [] } = options ?? {};
3104
+ if (appArguments !== undefined && appArguments !== null && !Array.isArray(appArguments)) {
3105
+ throw new TypeError("Expected `appArguments` as Array type");
3106
+ }
3107
+ return baseOpen({
3108
+ ...options,
3109
+ app: {
3110
+ name,
3111
+ arguments: appArguments
3112
+ }
3113
+ });
3114
+ }, apps, open_default;
3115
+ var init_open = __esm(() => {
3116
+ init_wsl_utils();
3117
+ init_default_browser();
3118
+ init_is_inside_container();
3119
+ execFile5 = promisify5(childProcess.execFile);
3120
+ __dirname2 = path.dirname(fileURLToPath(import.meta.url));
3121
+ localXdgOpenPath = path.join(__dirname2, "xdg-open");
3122
+ ({ platform, arch } = process8);
3123
+ apps = {};
3124
+ defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
3125
+ darwin: "google chrome",
3126
+ win32: "chrome",
3127
+ linux: ["google-chrome", "google-chrome-stable", "chromium"]
3128
+ }, {
3129
+ wsl: {
3130
+ ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
3131
+ x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]
3132
+ }
3133
+ }));
3134
+ defineLazyProperty(apps, "brave", () => detectPlatformBinary({
3135
+ darwin: "brave browser",
3136
+ win32: "brave",
3137
+ linux: ["brave-browser", "brave"]
3138
+ }, {
3139
+ wsl: {
3140
+ ia32: "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",
3141
+ x64: ["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe", "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]
3142
+ }
3143
+ }));
3144
+ defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
3145
+ darwin: "firefox",
3146
+ win32: String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,
3147
+ linux: "firefox"
3148
+ }, {
3149
+ wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe"
3150
+ }));
3151
+ defineLazyProperty(apps, "edge", () => detectPlatformBinary({
3152
+ darwin: "microsoft edge",
3153
+ win32: "msedge",
3154
+ linux: ["microsoft-edge", "microsoft-edge-dev"]
3155
+ }, {
3156
+ wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"
3157
+ }));
3158
+ defineLazyProperty(apps, "browser", () => "browser");
3159
+ defineLazyProperty(apps, "browserPrivate", () => "browserPrivate");
3160
+ open_default = open;
3161
+ });
3162
+
3163
+ // src/dev.ts
3164
+ var exports_dev = {};
3165
+ __export(exports_dev, {
3166
+ dev: () => dev
3167
+ });
3168
+ import { existsSync as existsSync3, writeFileSync as writeFileSync3 } from "fs";
3169
+ import { join as join3 } from "path";
3170
+ import { spawn } from "child_process";
3171
+ async function dev(opts) {
3172
+ const cwd = process.cwd();
3173
+ const config = loadBagdockJson(cwd);
3174
+ if (!config) {
3175
+ console.error(source_default.red("No bagdock.json found. Run"), source_default.cyan("bagdock init"), source_default.red("first."));
3176
+ process.exit(1);
3177
+ }
3178
+ const port = opts.port ?? "8787";
3179
+ const wranglerToml = generateWranglerToml(config, port);
3180
+ const wranglerPath = join3(cwd, "wrangler.toml");
3181
+ writeFileSync3(wranglerPath, wranglerToml);
3182
+ console.log(source_default.green("Generated"), source_default.cyan("wrangler.toml"), source_default.green("from bagdock.json"));
3183
+ const devVarsPath = join3(cwd, ".dev.vars");
3184
+ if (!existsSync3(devVarsPath) && config.env) {
3185
+ const hint = Object.entries(config.env).map(([key, meta]) => `# ${meta.description ?? key}${meta.required ? " (required)" : ""}
3186
+ ${key}=`).join(`
3187
+ `);
3188
+ writeFileSync3(devVarsPath, hint + `
3189
+ `);
3190
+ console.log(source_default.yellow("Created .dev.vars template — fill in your local secrets"));
3191
+ }
3192
+ console.log(source_default.cyan(`
3193
+ Starting wrangler dev on port ${port}...
3194
+ `));
3195
+ const child = spawn("npx", ["wrangler", "dev", "--port", port], {
3196
+ cwd,
3197
+ stdio: "inherit",
3198
+ shell: true
3199
+ });
3200
+ child.on("exit", (code) => {
3201
+ process.exit(code ?? 0);
3202
+ });
3203
+ }
3204
+ function generateWranglerToml(config, port) {
3205
+ const lines = [
3206
+ `# Auto-generated by @bagdock/cli from bagdock.json`,
3207
+ `# Do not edit manually — run \`bagdock dev\` to regenerate`,
3208
+ ``,
3209
+ `name = "${config.slug}"`,
3210
+ `main = "${config.main}"`,
3211
+ `compatibility_date = "${config.compatibilityDate ?? "2024-09-23"}"`,
3212
+ ``
3213
+ ];
3214
+ if (config.wrangler) {
3215
+ for (const [key, value] of Object.entries(config.wrangler)) {
3216
+ if (typeof value === "string") {
3217
+ lines.push(`${key} = "${value}"`);
3218
+ } else if (typeof value === "boolean" || typeof value === "number") {
3219
+ lines.push(`${key} = ${value}`);
3220
+ }
3221
+ }
3222
+ lines.push("");
3223
+ }
3224
+ if (config.env && Object.keys(config.env).length > 0) {
3225
+ lines.push(`[vars]`);
3226
+ for (const [key, meta] of Object.entries(config.env)) {
3227
+ lines.push(`# ${meta.description ?? key}`);
3228
+ lines.push(`# ${key} = "" # Loaded from .dev.vars at runtime`);
3229
+ }
3230
+ lines.push("");
3231
+ }
3232
+ return lines.join(`
3233
+ `);
3234
+ }
3235
+ var init_dev = __esm(() => {
3236
+ init_source();
3237
+ init_config();
3238
+ });
3239
+
3240
+ // src/deploy.ts
3241
+ var exports_deploy = {};
3242
+ __export(exports_deploy, {
3243
+ deploy: () => deploy
3244
+ });
3245
+ import { existsSync as existsSync4, readFileSync as readFileSync2 } from "fs";
3246
+ import { join as join4 } from "path";
3247
+ import { execSync } from "child_process";
3248
+ import { createInterface } from "readline";
3249
+ async function deploy(opts) {
3250
+ const cwd = process.cwd();
3251
+ const config = loadBagdockJson(cwd);
3252
+ if (!config) {
3253
+ console.error(source_default.red("No bagdock.json found. Run"), source_default.cyan("bagdock init"), source_default.red("first."));
3254
+ process.exit(1);
3255
+ }
3256
+ const creds = loadCredentials();
3257
+ if (!creds?.accessToken) {
3258
+ console.error(source_default.red("Not authenticated. Run"), source_default.cyan("bagdock login"), source_default.red("first."));
3259
+ process.exit(1);
3260
+ }
3261
+ let environment = opts.env ?? "staging";
3262
+ if (opts.preview)
3263
+ environment = "preview";
3264
+ if (opts.production)
3265
+ environment = "production";
3266
+ if (!["preview", "staging", "production"].includes(environment)) {
3267
+ console.error(source_default.red(`Invalid environment: ${environment}`));
3268
+ console.error("Valid environments: preview, staging, production");
3269
+ process.exit(1);
3270
+ }
3271
+ if (environment === "production" && !opts.yes) {
3272
+ console.log(source_default.yellow(`
3273
+ You are about to deploy ${source_default.bold(config.slug)}@${config.version} to ${source_default.bold("production")}.`));
3274
+ if (config.visibility === "public") {
3275
+ console.log(source_default.yellow(" This is a public integration — it must be approved by Bagdock."));
3276
+ }
3277
+ const confirmed = await confirm(" Continue? [y/N] ");
3278
+ if (!confirmed) {
3279
+ console.log(source_default.dim(" Aborted."));
3280
+ process.exit(0);
3281
+ }
3282
+ }
3283
+ const envLabel = environment === "preview" ? source_default.magenta("preview") : environment === "production" ? source_default.red("production") : source_default.blue("staging");
3284
+ console.log(source_default.cyan(`
3285
+ Deploying ${config.slug}@${config.version} → ${envLabel}
3286
+ `));
3287
+ const outDir = join4(cwd, ".bagdock");
3288
+ const outFile = join4(outDir, "worker.mjs");
3289
+ console.log(source_default.dim(" Building worker bundle..."));
3290
+ execSync(`mkdir -p ${outDir}`, { cwd });
3291
+ try {
3292
+ execSync(`bun build ${config.main} --outfile ${outFile} --target browser --format esm --minify`, { cwd, stdio: "pipe" });
3293
+ console.log(source_default.green(" Bundle built"));
3294
+ } catch {
3295
+ try {
3296
+ execSync(`npx esbuild ${config.main} --bundle --outfile=${outFile} --format=esm --minify --platform=neutral`, { cwd, stdio: "pipe" });
3297
+ console.log(source_default.green(" Bundle built (esbuild)"));
3298
+ } catch (err) {
3299
+ console.error(source_default.red(" Build failed. Ensure bun or esbuild is available."));
3300
+ console.error(source_default.dim(` ${err.message?.slice(0, 200)}`));
3301
+ process.exit(1);
3302
+ }
3303
+ }
3304
+ if (!existsSync4(outFile)) {
3305
+ console.error(source_default.red(" Build output not found at"), outFile);
3306
+ process.exit(1);
3307
+ }
3308
+ const scriptContent = readFileSync2(outFile);
3309
+ const sizeKb = (scriptContent.length / 1024).toFixed(1);
3310
+ console.log(source_default.dim(` Bundle size: ${sizeKb} KB`));
3311
+ console.log(source_default.dim(" Uploading to Bagdock platform..."));
3312
+ const formData = new FormData;
3313
+ formData.append("script", new Blob([scriptContent], { type: "application/javascript+module" }), "worker.mjs");
3314
+ formData.append("metadata", JSON.stringify({
3315
+ version: config.version,
3316
+ environment,
3317
+ compatibilityDate: config.compatibilityDate ?? "2024-09-23"
3318
+ }));
3319
+ try {
3320
+ const res = await fetch(`${API_BASE}/api/v1/developer/apps/${config.slug}/deploy`, {
3321
+ method: "POST",
3322
+ headers: {
3323
+ Authorization: `Bearer ${creds.accessToken}`
3324
+ },
3325
+ body: formData
3326
+ });
3327
+ if (res.status === 403) {
3328
+ const body = await res.json();
3329
+ console.error(source_default.red(`
3330
+ Deploy blocked by governance policy
3331
+ `));
3332
+ if (body.code === "REVIEW_REQUIRED") {
3333
+ console.error(source_default.yellow(` ${body.message}`));
3334
+ console.error();
3335
+ console.error(` To submit for review, run: ${source_default.cyan("bagdock submit")}`);
3336
+ console.error(` To deploy to staging instead: ${source_default.cyan("bagdock deploy")}`);
3337
+ } else {
3338
+ console.error(` ${body.error}`);
3339
+ }
3340
+ process.exit(1);
3341
+ }
3342
+ if (!res.ok) {
3343
+ const body = await res.text();
3344
+ console.error(source_default.red(` Deploy failed (${res.status}):`), body.slice(0, 300));
3345
+ process.exit(1);
3346
+ }
3347
+ const result = await res.json();
3348
+ console.log(source_default.green(`
3349
+ Deploy successful!
3350
+ `));
3351
+ console.log(` Version: ${source_default.bold(result.data.version)}`);
3352
+ console.log(` Environment: ${source_default.bold(result.data.environment)}`);
3353
+ console.log(` Worker URL: ${source_default.cyan(result.data.workerUrl)}`);
3354
+ if (result.data.previewHash) {
3355
+ console.log(` Preview ID: ${source_default.dim(result.data.previewHash)}`);
3356
+ }
3357
+ console.log(` Namespace: ${source_default.dim(result.data.namespace)}`);
3358
+ if (environment === "preview") {
3359
+ console.log(source_default.dim(`
3360
+ This is an ephemeral preview deploy. It will not replace the stable staging URL.`));
3361
+ }
3362
+ } catch (err) {
3363
+ console.error(source_default.red(" Deploy failed:"), err.message);
3364
+ process.exit(1);
3365
+ }
3366
+ }
3367
+ function confirm(prompt) {
3368
+ return new Promise((resolve) => {
3369
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
3370
+ rl.question(prompt, (answer) => {
3371
+ rl.close();
3372
+ resolve(answer.toLowerCase() === "y" || answer.toLowerCase() === "yes");
3373
+ });
3374
+ });
3375
+ }
3376
+ var init_deploy = __esm(() => {
3377
+ init_source();
3378
+ init_config();
3379
+ });
3380
+
3381
+ // src/submit.ts
3382
+ var exports_submit = {};
3383
+ __export(exports_submit, {
3384
+ submit: () => submit
3385
+ });
3386
+ async function submit() {
3387
+ const config = loadBagdockJson(process.cwd());
3388
+ if (!config) {
3389
+ console.error(source_default.red("No bagdock.json found. Run"), source_default.cyan("bagdock init"), source_default.red("first."));
3390
+ process.exit(1);
3391
+ }
3392
+ const creds = loadCredentials();
3393
+ if (!creds?.accessToken) {
3394
+ console.error(source_default.red("Not authenticated. Run"), source_default.cyan("bagdock login"), source_default.red("first."));
3395
+ process.exit(1);
3396
+ }
3397
+ console.log(source_default.cyan(`
3398
+ Submitting ${source_default.bold(config.slug)} for marketplace review...
3399
+ `));
3400
+ try {
3401
+ const res = await fetch(`${API_BASE}/api/v1/developer/apps/${config.slug}/submit`, {
3402
+ method: "POST",
3403
+ headers: {
3404
+ Authorization: `Bearer ${creds.accessToken}`,
3405
+ "Content-Type": "application/json"
3406
+ }
3407
+ });
3408
+ if (!res.ok) {
3409
+ const body = await res.text();
3410
+ if (res.status === 404) {
3411
+ console.error(source_default.red(" App not found."), "Make sure you have created it with", source_default.cyan("bagdock deploy"), "first.");
3412
+ } else {
3413
+ console.error(source_default.red(` Submit failed (${res.status}):`), body.slice(0, 300));
3414
+ }
3415
+ process.exit(1);
3416
+ }
3417
+ console.log(source_default.green(" Submitted for review!"));
3418
+ console.log();
3419
+ console.log(` The Bagdock team will review ${source_default.bold(config.slug)} and notify you`);
3420
+ console.log(` when it's approved. Once approved, you can deploy to production:`);
3421
+ console.log();
3422
+ console.log(` ${source_default.cyan("bagdock deploy --production")}`);
3423
+ console.log();
3424
+ } catch (err) {
3425
+ console.error(source_default.red(" Submit failed:"), err.message);
3426
+ process.exit(1);
3427
+ }
3428
+ }
3429
+ var init_submit = __esm(() => {
3430
+ init_source();
3431
+ init_config();
3432
+ });
3433
+
3434
+ // src/env-cmd.ts
3435
+ var exports_env_cmd = {};
3436
+ __export(exports_env_cmd, {
3437
+ envSet: () => envSet,
3438
+ envRemove: () => envRemove,
3439
+ envList: () => envList
3440
+ });
3441
+ function requireAuth() {
3442
+ const creds = loadCredentials();
3443
+ if (!creds?.accessToken) {
3444
+ console.error(source_default.red("Not authenticated. Run"), source_default.cyan("bagdock login"));
3445
+ process.exit(1);
3446
+ }
3447
+ return creds;
3448
+ }
3449
+ function requireConfig() {
3450
+ const config = loadBagdockJson(process.cwd());
3451
+ if (!config) {
3452
+ console.error(source_default.red("No bagdock.json found. Run"), source_default.cyan("bagdock init"));
3453
+ process.exit(1);
3454
+ }
3455
+ return config;
3456
+ }
3457
+ async function envList() {
3458
+ const creds = requireAuth();
3459
+ const config = requireConfig();
3460
+ try {
3461
+ const res = await fetch(`${API_BASE}/v1/developer/apps/${config.slug}/env`, {
3462
+ headers: { Authorization: `Bearer ${creds.accessToken}` }
3463
+ });
3464
+ if (!res.ok) {
3465
+ console.error(source_default.red(`Failed to list env vars (${res.status})`));
3466
+ process.exit(1);
3467
+ }
3468
+ const { data } = await res.json();
3469
+ if (!data.length) {
3470
+ console.log(source_default.yellow("No environment variables set."));
3471
+ console.log("Use", source_default.cyan("bagdock env set <KEY> <VALUE>"), "to add one.");
3472
+ return;
3473
+ }
3474
+ console.log(source_default.bold(`
3475
+ Environment variables for ${config.slug}:
3476
+ `));
3477
+ for (const v of data) {
3478
+ console.log(` ${source_default.cyan(v.key)} ${source_default.dim(`(updated ${v.updatedAt})`)}`);
3479
+ }
3480
+ console.log();
3481
+ } catch (err) {
3482
+ console.error(source_default.red("Failed to reach API:"), err.message);
3483
+ process.exit(1);
3484
+ }
3485
+ }
3486
+ async function envSet(key, value) {
3487
+ const creds = requireAuth();
3488
+ const config = requireConfig();
3489
+ try {
3490
+ const res = await fetch(`${API_BASE}/v1/developer/apps/${config.slug}/env`, {
3491
+ method: "PUT",
3492
+ headers: {
3493
+ "Content-Type": "application/json",
3494
+ Authorization: `Bearer ${creds.accessToken}`
3495
+ },
3496
+ body: JSON.stringify({ key, value })
3497
+ });
3498
+ if (!res.ok) {
3499
+ const body = await res.text();
3500
+ console.error(source_default.red(`Failed to set ${key} (${res.status}):`), body.slice(0, 200));
3501
+ process.exit(1);
3502
+ }
3503
+ console.log(source_default.green(`Set ${key}`), source_default.dim("— will take effect on next deploy"));
3504
+ } catch (err) {
3505
+ console.error(source_default.red("Failed:"), err.message);
3506
+ process.exit(1);
3507
+ }
3508
+ }
3509
+ async function envRemove(key) {
3510
+ const creds = requireAuth();
3511
+ const config = requireConfig();
3512
+ try {
3513
+ const res = await fetch(`${API_BASE}/v1/developer/apps/${config.slug}/env/${key}`, {
3514
+ method: "DELETE",
3515
+ headers: { Authorization: `Bearer ${creds.accessToken}` }
3516
+ });
3517
+ if (!res.ok) {
3518
+ console.error(source_default.red(`Failed to remove ${key} (${res.status})`));
3519
+ process.exit(1);
3520
+ }
3521
+ console.log(source_default.green(`Removed ${key}`), source_default.dim("— will take effect on next deploy"));
3522
+ } catch (err) {
3523
+ console.error(source_default.red("Failed:"), err.message);
3524
+ process.exit(1);
3525
+ }
3526
+ }
3527
+ var init_env_cmd = __esm(() => {
3528
+ init_source();
3529
+ init_config();
3530
+ });
3531
+
3532
+ // ../../node_modules/commander/esm.mjs
3533
+ var import__ = __toESM(require_commander(), 1);
3534
+ var {
3535
+ program,
3536
+ createCommand,
3537
+ createArgument,
3538
+ createOption,
3539
+ CommanderError,
3540
+ InvalidArgumentError,
3541
+ InvalidOptionArgumentError,
3542
+ Command,
3543
+ Argument,
3544
+ Option,
3545
+ Help
3546
+ } = import__.default;
3547
+
3548
+ // src/auth.ts
3549
+ init_config();
3550
+ init_source();
3551
+ var CLIENT_ID = "bagdock-cli";
3552
+ var MAX_POLL_DURATION_MS = 300000;
3553
+ async function login() {
3554
+ const existing = loadCredentials();
3555
+ if (existing?.accessToken && existing.expiresAt && existing.expiresAt > Date.now()) {
3556
+ console.log(source_default.green("Already logged in as"), source_default.bold(existing.email ?? "unknown"));
3557
+ console.log("Run", source_default.cyan("bagdock logout"), "to sign out first.");
3558
+ return;
3559
+ }
3560
+ console.log(source_default.cyan(`
3561
+ Requesting device authorization...
3562
+ `));
3563
+ const deviceRes = await fetch(`${API_BASE}/oauth2/device/authorize`, {
3564
+ method: "POST",
3565
+ headers: { "Content-Type": "application/json" },
3566
+ body: JSON.stringify({ client_id: CLIENT_ID, scope: "developer:read developer:write" })
3567
+ });
3568
+ if (!deviceRes.ok) {
3569
+ const err = await deviceRes.text();
3570
+ console.log(source_default.red("Failed to start login:"), err);
3571
+ process.exit(1);
3572
+ }
3573
+ const device = await deviceRes.json();
3574
+ const pollInterval = (device.interval ?? 5) * 1000;
3575
+ console.log(` Visit ${source_default.bold(device.verification_uri)} and enter code:
3576
+ `);
3577
+ console.log(` ${source_default.bold.cyan(device.user_code)}
3578
+ `);
3579
+ const open2 = (await Promise.resolve().then(() => (init_open(), exports_open))).default;
3580
+ await open2(device.verification_uri_complete).catch(() => {});
3581
+ console.log(source_default.dim(" Waiting for authorization..."));
3582
+ const startedAt = Date.now();
3583
+ while (Date.now() - startedAt < MAX_POLL_DURATION_MS) {
3584
+ await sleep(pollInterval);
3585
+ const tokenRes = await fetch(`${API_BASE}/oauth2/token`, {
3586
+ method: "POST",
3587
+ headers: { "Content-Type": "application/json" },
3588
+ body: JSON.stringify({
3589
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
3590
+ client_id: CLIENT_ID,
3591
+ device_code: device.device_code
3592
+ })
3593
+ });
3594
+ if (tokenRes.ok) {
3595
+ const tokens = await tokenRes.json();
3596
+ saveCredentials({
3597
+ accessToken: tokens.access_token,
3598
+ refreshToken: tokens.refresh_token,
3599
+ expiresAt: tokens.expires_in ? Date.now() + tokens.expires_in * 1000 : undefined,
3600
+ email: tokens.email,
3601
+ operatorId: tokens.operator_id
3602
+ });
3603
+ console.log(source_default.green(`
3604
+ Logged in successfully!`));
3605
+ if (tokens.email)
3606
+ console.log(" Email:", source_default.bold(tokens.email));
3607
+ if (tokens.operator_id)
3608
+ console.log(" Operator:", source_default.bold(tokens.operator_id));
3609
+ return;
3610
+ }
3611
+ const error = await tokenRes.json().catch(() => ({ error: "unknown" }));
3612
+ if (error.error === "authorization_pending") {
3613
+ continue;
3614
+ }
3615
+ if (error.error === "slow_down") {
3616
+ await sleep(pollInterval);
3617
+ continue;
3618
+ }
3619
+ if (error.error === "expired_token") {
3620
+ console.log(source_default.red(`
3621
+ Device code expired. Please try again.`));
3622
+ process.exit(1);
3623
+ }
3624
+ if (error.error === "access_denied") {
3625
+ console.log(source_default.red(`
3626
+ Authorization denied.`));
3627
+ process.exit(1);
3628
+ }
3629
+ console.log(source_default.red(`
3630
+ Login failed:`), error.error_description ?? error.error);
3631
+ process.exit(1);
3632
+ }
3633
+ console.log(source_default.red(`
3634
+ Login timed out. Please try again.`));
3635
+ process.exit(1);
3636
+ }
3637
+ async function logout() {
3638
+ clearCredentials();
3639
+ console.log(source_default.green("Logged out."));
3640
+ }
3641
+ async function whoami() {
3642
+ const envToken = process.env.BAGDOCK_TOKEN;
3643
+ const creds = envToken ? { accessToken: envToken, email: "(M2M token)" } : loadCredentials();
3644
+ if (!creds?.accessToken) {
3645
+ console.log(source_default.yellow("Not logged in."), "Run", source_default.cyan("bagdock login"));
3646
+ process.exit(1);
3647
+ }
3648
+ try {
3649
+ const res = await fetch(`${API_BASE}/v1/auth/me`, {
3650
+ headers: { Authorization: `Bearer ${creds.accessToken}` }
3651
+ });
3652
+ if (!res.ok) {
3653
+ console.log(source_default.red("Session expired or invalid."), "Run", source_default.cyan("bagdock login"));
3654
+ process.exit(1);
3655
+ }
3656
+ const user = await res.json();
3657
+ console.log(source_default.green("Logged in as"), source_default.bold(user.email));
3658
+ if (user.operator_id)
3659
+ console.log("Operator:", source_default.bold(user.operator_id));
3660
+ if (user.name)
3661
+ console.log("Name:", user.name);
3662
+ } catch (err) {
3663
+ console.log(source_default.red("Failed to reach API:"), err.message);
3664
+ process.exit(1);
3665
+ }
3666
+ }
3667
+ function sleep(ms) {
3668
+ return new Promise((resolve) => setTimeout(resolve, ms));
3669
+ }
3670
+
3671
+ // src/init.ts
3672
+ init_source();
3673
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
3674
+ import { join as join2, basename } from "path";
3675
+ var CATEGORIES = {
3676
+ adapter: ["locks", "gates", "intercoms", "full_access", "sensors", "connectivity", "payment_processing", "analytics", "other"],
3677
+ comms: ["telephony", "sms", "voice"],
3678
+ webhook: ["automation", "other"],
3679
+ "ui-extension": ["analytics", "crm", "scheduling", "live_chat", "other"],
3680
+ microfrontend: ["analytics", "ecommerce", "other"]
3681
+ };
3682
+ async function init(dir, opts) {
3683
+ const projectDir = dir || process.cwd();
3684
+ const projectName = basename(projectDir);
3685
+ if (existsSync2(join2(projectDir, "bagdock.json"))) {
3686
+ console.log(source_default.yellow("bagdock.json already exists in this directory."));
3687
+ return;
3688
+ }
3689
+ const slug = opts.slug ?? projectName.toLowerCase().replace(/[^a-z0-9-]/g, "-");
3690
+ const type = opts.type ?? "edge";
3691
+ const kind = resolveKind(type, opts.kind);
3692
+ const categories = CATEGORIES[kind] ?? ["other"];
3693
+ const category = opts.category ?? categories[0];
3694
+ const config = {
3695
+ name: opts.name ?? projectName,
3696
+ slug,
3697
+ version: "0.1.0",
3698
+ type,
3699
+ kind,
3700
+ category,
3701
+ maintainer: "operator",
3702
+ visibility: "private",
3703
+ main: "src/index.ts",
3704
+ compatibilityDate: "2024-09-23",
3705
+ env: {
3706
+ API_KEY: { description: "Provider API key", required: true }
3707
+ }
3708
+ };
3709
+ writeFileSync2(join2(projectDir, "bagdock.json"), JSON.stringify(config, null, 2));
3710
+ const srcDir = join2(projectDir, "src");
3711
+ if (!existsSync2(srcDir)) {
3712
+ mkdirSync2(srcDir, { recursive: true });
3713
+ }
3714
+ const entryFile = join2(srcDir, "index.ts");
3715
+ if (!existsSync2(entryFile)) {
3716
+ const template = selectTemplate(type, kind, slug);
3717
+ writeFileSync2(entryFile, template);
3718
+ }
3719
+ const pkgFile = join2(projectDir, "package.json");
3720
+ if (!existsSync2(pkgFile)) {
3721
+ const devDeps = {
3722
+ "@cloudflare/workers-types": "^4.20240909.0",
3723
+ typescript: "^5.3.3"
3724
+ };
3725
+ if (type === "edge" && kind === "adapter") {
3726
+ devDeps["@bagdock/adapter-worker-template"] = "workspace:*";
3727
+ }
3728
+ writeFileSync2(pkgFile, JSON.stringify({
3729
+ name: slug,
3730
+ version: "0.1.0",
3731
+ private: true,
3732
+ main: "src/index.ts",
3733
+ devDependencies: devDeps
3734
+ }, null, 2));
3735
+ }
3736
+ const label = type === "app" ? "app" : "edge";
3737
+ console.log(source_default.green(`
3738
+ Initialised Bagdock ${label} project!
3739
+ `));
3740
+ console.log("Created:");
3741
+ console.log(` ${source_default.cyan("bagdock.json")} — project config`);
3742
+ console.log(` ${source_default.cyan("src/index.ts")} — worker entry point`);
3743
+ console.log();
3744
+ console.log("Next steps:");
3745
+ console.log(` 1. ${source_default.cyan("bagdock dev")} — start local dev server`);
3746
+ console.log(` 2. ${source_default.cyan("bagdock deploy")} — deploy to Bagdock platform`);
3747
+ }
3748
+ function resolveKind(type, kindOpt) {
3749
+ if (kindOpt)
3750
+ return kindOpt;
3751
+ return type === "app" ? "ui-extension" : "adapter";
3752
+ }
3753
+ function selectTemplate(type, kind, slug) {
3754
+ if (type === "app")
3755
+ return APP_TEMPLATE(slug);
3756
+ if (kind === "comms")
3757
+ return COMMS_TEMPLATE(slug);
3758
+ if (kind === "webhook")
3759
+ return WEBHOOK_TEMPLATE(slug);
3760
+ return ADAPTER_TEMPLATE(slug);
3761
+ }
3762
+ function ADAPTER_TEMPLATE(slug) {
3763
+ return `import { createAdapterWorker } from '@bagdock/adapter-worker-template'
3764
+ import type { AdapterWorkerContract, AdapterRequest, ActionResult, HealthResult } from '@bagdock/adapter-worker-template'
3765
+
3766
+ class ${toPascalCase(slug)}Adapter implements AdapterWorkerContract {
3767
+ async syncAccessPoints(req: AdapterRequest) {
3768
+ return { access_points: [] }
3769
+ }
3770
+
3771
+ async programCredential(req: AdapterRequest): Promise<ActionResult> {
3772
+ return { success: true }
3773
+ }
3774
+
3775
+ async revokeCredential(req: AdapterRequest): Promise<ActionResult> {
3776
+ return { success: true }
3777
+ }
3778
+
3779
+ async openAccessPoint(req: AdapterRequest): Promise<ActionResult> {
3780
+ return { success: true }
3781
+ }
3782
+
3783
+ async checkHealth(req: AdapterRequest): Promise<HealthResult> {
3784
+ return { status: 'healthy', version: '0.1.0', uptime_seconds: 0 }
3785
+ }
3786
+ }
3787
+
3788
+ export default createAdapterWorker(new ${toPascalCase(slug)}Adapter())
3789
+ `;
3790
+ }
3791
+ function COMMS_TEMPLATE(slug) {
3792
+ return `/**
3793
+ * ${toPascalCase(slug)} — Communications edge worker.
3794
+ *
3795
+ * Handles SMS, Voice, or Telephony actions dispatched by the workflow engine.
3796
+ */
3797
+
3798
+ interface Env {
3799
+ API_KEY: string
3800
+ }
3801
+
3802
+ export default {
3803
+ async fetch(request: Request, env: Env): Promise<Response> {
3804
+ const url = new URL(request.url)
3805
+ const action = url.pathname.replace(/^\\//, '')
3806
+
3807
+ if (action === 'send-sms') {
3808
+ const body = await request.json() as { to: string; text: string; from?: string }
3809
+ return Response.json({ id: crypto.randomUUID(), status: 'queued' })
3810
+ }
3811
+
3812
+ if (action === 'health') {
3813
+ return Response.json({ status: 'healthy', version: '0.1.0' })
3814
+ }
3815
+
3816
+ return Response.json({ error: 'Unknown action', action }, { status: 404 })
3817
+ },
3818
+ }
3819
+ `;
3820
+ }
3821
+ function WEBHOOK_TEMPLATE(slug) {
3822
+ return `/**
3823
+ * ${toPascalCase(slug)} — Webhook handler edge worker.
3824
+ *
3825
+ * Receives inbound webhooks from external services and dispatches events.
3826
+ */
3827
+
3828
+ interface Env {
3829
+ WEBHOOK_SECRET: string
3830
+ }
3831
+
3832
+ export default {
3833
+ async fetch(request: Request, env: Env): Promise<Response> {
3834
+ if (request.method !== 'POST') {
3835
+ return Response.json({ error: 'Method not allowed' }, { status: 405 })
3836
+ }
3837
+
3838
+ const body = await request.json()
3839
+ // TODO: validate signature using env.WEBHOOK_SECRET
3840
+ // TODO: process webhook payload and dispatch to Bagdock event bus
3841
+
3842
+ return Response.json({ received: true })
3843
+ },
3844
+ }
3845
+ `;
3846
+ }
3847
+ function APP_TEMPLATE(slug) {
3848
+ return `/**
3849
+ * ${toPascalCase(slug)} — Bagdock UI extension app.
3850
+ *
3851
+ * This worker serves as the backend for a UI extension that renders
3852
+ * panels, drawers, or cards within the Bagdock operator dashboard.
3853
+ *
3854
+ * The Bagdock App Bridge calls these endpoints to fetch data and
3855
+ * execute actions on behalf of the authenticated operator.
3856
+ */
3857
+
3858
+ interface Env {
3859
+ API_KEY: string
3860
+ }
3861
+
3862
+ interface AppContext {
3863
+ operatorId: string
3864
+ facilityId?: string
3865
+ entityType?: string
3866
+ entityId?: string
3867
+ }
3868
+
3869
+ export default {
3870
+ async fetch(request: Request, env: Env): Promise<Response> {
3871
+ const url = new URL(request.url)
3872
+ const path = url.pathname.replace(/^\\//, '')
3873
+
3874
+ // Bagdock App Bridge injects operator context via headers
3875
+ const ctx: AppContext = {
3876
+ operatorId: request.headers.get('x-bagdock-operator-id') ?? '',
3877
+ facilityId: request.headers.get('x-bagdock-facility-id') ?? undefined,
3878
+ entityType: request.headers.get('x-bagdock-entity-type') ?? undefined,
3879
+ entityId: request.headers.get('x-bagdock-entity-id') ?? undefined,
3880
+ }
3881
+
3882
+ if (path === 'manifest') {
3883
+ return Response.json({
3884
+ name: '${slug}',
3885
+ version: '0.1.0',
3886
+ extensions: [
3887
+ {
3888
+ type: 'panel',
3889
+ target: 'facility.overview',
3890
+ title: '${toPascalCase(slug)}',
3891
+ dataUrl: '/data',
3892
+ },
3893
+ ],
3894
+ })
3895
+ }
3896
+
3897
+ if (path === 'data') {
3898
+ return Response.json({
3899
+ operator_id: ctx.operatorId,
3900
+ facility_id: ctx.facilityId,
3901
+ items: [],
3902
+ })
3903
+ }
3904
+
3905
+ if (path === 'health') {
3906
+ return Response.json({ status: 'healthy', version: '0.1.0' })
3907
+ }
3908
+
3909
+ return Response.json({ error: 'Not found' }, { status: 404 })
3910
+ },
3911
+ }
3912
+ `;
3913
+ }
3914
+ function toPascalCase(s) {
3915
+ return s.replace(/(^|-|_)(\w)/g, (_, __, c) => c.toUpperCase());
3916
+ }
3917
+
3918
+ // bin/bagdock.ts
3919
+ var program2 = new Command;
3920
+ program2.name("bagdock").description("Bagdock developer CLI").version("0.1.0");
3921
+ program2.command("login").description("Authenticate with Bagdock (opens browser)").action(login);
3922
+ program2.command("logout").description("Clear stored credentials").action(logout);
3923
+ program2.command("whoami").description("Show current authenticated user").action(whoami);
3924
+ program2.command("init [dir]").description("Scaffold a new project with bagdock.json").option("-t, --type <type>", "Project type (edge, app)").option("-k, --kind <kind>", "Project kind (adapter, comms, webhook, ui-extension, microfrontend)").option("-c, --category <category>", "Category").option("-s, --slug <slug>", "Unique project slug").option("-n, --name <name>", "Display name").action((dir, opts) => init(dir ?? ".", opts));
3925
+ program2.command("dev").description("Start local dev server").option("-p, --port <port>", "Local dev port", "8787").action(async (opts) => {
3926
+ const { dev: dev2 } = await Promise.resolve().then(() => (init_dev(), exports_dev));
3927
+ await dev2(opts);
3928
+ });
3929
+ program2.command("deploy").description("Build locally and deploy via Bagdock API \u2192 CF Workers for Platforms").option("--env <environment>", "Target environment (preview, staging, production)", "staging").option("--preview", "Deploy an ephemeral preview ({slug}-{hash}.pre.bdok.sh)").option("--production", "Deploy to production ({slug}.bdok.sh)").option("-y, --yes", "Skip confirmation prompts").action(async (opts) => {
3930
+ const { deploy: deploy2 } = await Promise.resolve().then(() => (init_deploy(), exports_deploy));
3931
+ await deploy2(opts);
3932
+ });
3933
+ program2.command("submit").description("Submit app for Bagdock marketplace review (required for public production deploys)").action(async () => {
3934
+ const { submit: submit2 } = await Promise.resolve().then(() => (init_submit(), exports_submit));
3935
+ await submit2();
3936
+ });
3937
+ var envCmd = program2.command("env").description("Manage app environment variables");
3938
+ envCmd.command("list").description("List environment variables for this app").action(async () => {
3939
+ const { envList: envList2 } = await Promise.resolve().then(() => (init_env_cmd(), exports_env_cmd));
3940
+ await envList2();
3941
+ });
3942
+ envCmd.command("set <key> <value>").description("Set an environment variable").action(async (key, value) => {
3943
+ const { envSet: envSet2 } = await Promise.resolve().then(() => (init_env_cmd(), exports_env_cmd));
3944
+ await envSet2(key, value);
3945
+ });
3946
+ envCmd.command("remove <key>").description("Remove an environment variable").action(async (key) => {
3947
+ const { envRemove: envRemove2 } = await Promise.resolve().then(() => (init_env_cmd(), exports_env_cmd));
3948
+ await envRemove2(key);
3949
+ });
3950
+ program2.parse();