lumail 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,3152 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from "node:module";
3
+ var __create = Object.create;
4
+ var __getProtoOf = Object.getPrototypeOf;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __toESM = (mod, isNodeMode, target) => {
9
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
10
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
11
+ for (let key of __getOwnPropNames(mod))
12
+ if (!__hasOwnProp.call(to, key))
13
+ __defProp(to, key, {
14
+ get: () => mod[key],
15
+ enumerable: true
16
+ });
17
+ return to;
18
+ };
19
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
20
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
21
+
22
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/error.js
23
+ var require_error = __commonJS((exports) => {
24
+ class CommanderError extends Error {
25
+ constructor(exitCode, code, message) {
26
+ super(message);
27
+ Error.captureStackTrace(this, this.constructor);
28
+ this.name = this.constructor.name;
29
+ this.code = code;
30
+ this.exitCode = exitCode;
31
+ this.nestedError = undefined;
32
+ }
33
+ }
34
+
35
+ class InvalidArgumentError extends CommanderError {
36
+ constructor(message) {
37
+ super(1, "commander.invalidArgument", message);
38
+ Error.captureStackTrace(this, this.constructor);
39
+ this.name = this.constructor.name;
40
+ }
41
+ }
42
+ exports.CommanderError = CommanderError;
43
+ exports.InvalidArgumentError = InvalidArgumentError;
44
+ });
45
+
46
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/argument.js
47
+ var require_argument = __commonJS((exports) => {
48
+ var { InvalidArgumentError } = require_error();
49
+
50
+ class Argument {
51
+ constructor(name, description) {
52
+ this.description = description || "";
53
+ this.variadic = false;
54
+ this.parseArg = undefined;
55
+ this.defaultValue = undefined;
56
+ this.defaultValueDescription = undefined;
57
+ this.argChoices = undefined;
58
+ switch (name[0]) {
59
+ case "<":
60
+ this.required = true;
61
+ this._name = name.slice(1, -1);
62
+ break;
63
+ case "[":
64
+ this.required = false;
65
+ this._name = name.slice(1, -1);
66
+ break;
67
+ default:
68
+ this.required = true;
69
+ this._name = name;
70
+ break;
71
+ }
72
+ if (this._name.endsWith("...")) {
73
+ this.variadic = true;
74
+ this._name = this._name.slice(0, -3);
75
+ }
76
+ }
77
+ name() {
78
+ return this._name;
79
+ }
80
+ _collectValue(value, previous) {
81
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
82
+ return [value];
83
+ }
84
+ previous.push(value);
85
+ return previous;
86
+ }
87
+ default(value, description) {
88
+ this.defaultValue = value;
89
+ this.defaultValueDescription = description;
90
+ return this;
91
+ }
92
+ argParser(fn) {
93
+ this.parseArg = fn;
94
+ return this;
95
+ }
96
+ choices(values) {
97
+ this.argChoices = values.slice();
98
+ this.parseArg = (arg, previous) => {
99
+ if (!this.argChoices.includes(arg)) {
100
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
101
+ }
102
+ if (this.variadic) {
103
+ return this._collectValue(arg, previous);
104
+ }
105
+ return arg;
106
+ };
107
+ return this;
108
+ }
109
+ argRequired() {
110
+ this.required = true;
111
+ return this;
112
+ }
113
+ argOptional() {
114
+ this.required = false;
115
+ return this;
116
+ }
117
+ }
118
+ function humanReadableArgName(arg) {
119
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
120
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
121
+ }
122
+ exports.Argument = Argument;
123
+ exports.humanReadableArgName = humanReadableArgName;
124
+ });
125
+
126
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/help.js
127
+ var require_help = __commonJS((exports) => {
128
+ var { humanReadableArgName } = require_argument();
129
+
130
+ class Help {
131
+ constructor() {
132
+ this.helpWidth = undefined;
133
+ this.minWidthToWrap = 40;
134
+ this.sortSubcommands = false;
135
+ this.sortOptions = false;
136
+ this.showGlobalOptions = false;
137
+ }
138
+ prepareContext(contextOptions) {
139
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
140
+ }
141
+ visibleCommands(cmd) {
142
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
143
+ const helpCommand = cmd._getHelpCommand();
144
+ if (helpCommand && !helpCommand._hidden) {
145
+ visibleCommands.push(helpCommand);
146
+ }
147
+ if (this.sortSubcommands) {
148
+ visibleCommands.sort((a, b) => {
149
+ return a.name().localeCompare(b.name());
150
+ });
151
+ }
152
+ return visibleCommands;
153
+ }
154
+ compareOptions(a, b) {
155
+ const getSortKey = (option) => {
156
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
157
+ };
158
+ return getSortKey(a).localeCompare(getSortKey(b));
159
+ }
160
+ visibleOptions(cmd) {
161
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
162
+ const helpOption = cmd._getHelpOption();
163
+ if (helpOption && !helpOption.hidden) {
164
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
165
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
166
+ if (!removeShort && !removeLong) {
167
+ visibleOptions.push(helpOption);
168
+ } else if (helpOption.long && !removeLong) {
169
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
170
+ } else if (helpOption.short && !removeShort) {
171
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
172
+ }
173
+ }
174
+ if (this.sortOptions) {
175
+ visibleOptions.sort(this.compareOptions);
176
+ }
177
+ return visibleOptions;
178
+ }
179
+ visibleGlobalOptions(cmd) {
180
+ if (!this.showGlobalOptions)
181
+ return [];
182
+ const globalOptions = [];
183
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
184
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
185
+ globalOptions.push(...visibleOptions);
186
+ }
187
+ if (this.sortOptions) {
188
+ globalOptions.sort(this.compareOptions);
189
+ }
190
+ return globalOptions;
191
+ }
192
+ visibleArguments(cmd) {
193
+ if (cmd._argsDescription) {
194
+ cmd.registeredArguments.forEach((argument) => {
195
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
196
+ });
197
+ }
198
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
199
+ return cmd.registeredArguments;
200
+ }
201
+ return [];
202
+ }
203
+ subcommandTerm(cmd) {
204
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
205
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
206
+ }
207
+ optionTerm(option) {
208
+ return option.flags;
209
+ }
210
+ argumentTerm(argument) {
211
+ return argument.name();
212
+ }
213
+ longestSubcommandTermLength(cmd, helper) {
214
+ return helper.visibleCommands(cmd).reduce((max, command) => {
215
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
216
+ }, 0);
217
+ }
218
+ longestOptionTermLength(cmd, helper) {
219
+ return helper.visibleOptions(cmd).reduce((max, option) => {
220
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
221
+ }, 0);
222
+ }
223
+ longestGlobalOptionTermLength(cmd, helper) {
224
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
225
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
226
+ }, 0);
227
+ }
228
+ longestArgumentTermLength(cmd, helper) {
229
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
230
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
231
+ }, 0);
232
+ }
233
+ commandUsage(cmd) {
234
+ let cmdName = cmd._name;
235
+ if (cmd._aliases[0]) {
236
+ cmdName = cmdName + "|" + cmd._aliases[0];
237
+ }
238
+ let ancestorCmdNames = "";
239
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
240
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
241
+ }
242
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
243
+ }
244
+ commandDescription(cmd) {
245
+ return cmd.description();
246
+ }
247
+ subcommandDescription(cmd) {
248
+ return cmd.summary() || cmd.description();
249
+ }
250
+ optionDescription(option) {
251
+ const extraInfo = [];
252
+ if (option.argChoices) {
253
+ extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
254
+ }
255
+ if (option.defaultValue !== undefined) {
256
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
257
+ if (showDefault) {
258
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
259
+ }
260
+ }
261
+ if (option.presetArg !== undefined && option.optional) {
262
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
263
+ }
264
+ if (option.envVar !== undefined) {
265
+ extraInfo.push(`env: ${option.envVar}`);
266
+ }
267
+ if (extraInfo.length > 0) {
268
+ const extraDescription = `(${extraInfo.join(", ")})`;
269
+ if (option.description) {
270
+ return `${option.description} ${extraDescription}`;
271
+ }
272
+ return extraDescription;
273
+ }
274
+ return option.description;
275
+ }
276
+ argumentDescription(argument) {
277
+ const extraInfo = [];
278
+ if (argument.argChoices) {
279
+ extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
280
+ }
281
+ if (argument.defaultValue !== undefined) {
282
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
283
+ }
284
+ if (extraInfo.length > 0) {
285
+ const extraDescription = `(${extraInfo.join(", ")})`;
286
+ if (argument.description) {
287
+ return `${argument.description} ${extraDescription}`;
288
+ }
289
+ return extraDescription;
290
+ }
291
+ return argument.description;
292
+ }
293
+ formatItemList(heading, items, helper) {
294
+ if (items.length === 0)
295
+ return [];
296
+ return [helper.styleTitle(heading), ...items, ""];
297
+ }
298
+ groupItems(unsortedItems, visibleItems, getGroup) {
299
+ const result = new Map;
300
+ unsortedItems.forEach((item) => {
301
+ const group = getGroup(item);
302
+ if (!result.has(group))
303
+ result.set(group, []);
304
+ });
305
+ visibleItems.forEach((item) => {
306
+ const group = getGroup(item);
307
+ if (!result.has(group)) {
308
+ result.set(group, []);
309
+ }
310
+ result.get(group).push(item);
311
+ });
312
+ return result;
313
+ }
314
+ formatHelp(cmd, helper) {
315
+ const termWidth = helper.padWidth(cmd, helper);
316
+ const helpWidth = helper.helpWidth ?? 80;
317
+ function callFormatItem(term, description) {
318
+ return helper.formatItem(term, termWidth, description, helper);
319
+ }
320
+ let output = [
321
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
322
+ ""
323
+ ];
324
+ const commandDescription = helper.commandDescription(cmd);
325
+ if (commandDescription.length > 0) {
326
+ output = output.concat([
327
+ helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth),
328
+ ""
329
+ ]);
330
+ }
331
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
332
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
333
+ });
334
+ output = output.concat(this.formatItemList("Arguments:", argumentList, helper));
335
+ const optionGroups = this.groupItems(cmd.options, helper.visibleOptions(cmd), (option) => option.helpGroupHeading ?? "Options:");
336
+ optionGroups.forEach((options, group) => {
337
+ const optionList = options.map((option) => {
338
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
339
+ });
340
+ output = output.concat(this.formatItemList(group, optionList, helper));
341
+ });
342
+ if (helper.showGlobalOptions) {
343
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
344
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
345
+ });
346
+ output = output.concat(this.formatItemList("Global Options:", globalOptionList, helper));
347
+ }
348
+ const commandGroups = this.groupItems(cmd.commands, helper.visibleCommands(cmd), (sub) => sub.helpGroup() || "Commands:");
349
+ commandGroups.forEach((commands, group) => {
350
+ const commandList = commands.map((sub) => {
351
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(sub)), helper.styleSubcommandDescription(helper.subcommandDescription(sub)));
352
+ });
353
+ output = output.concat(this.formatItemList(group, commandList, helper));
354
+ });
355
+ return output.join(`
356
+ `);
357
+ }
358
+ displayWidth(str) {
359
+ return stripColor(str).length;
360
+ }
361
+ styleTitle(str) {
362
+ return str;
363
+ }
364
+ styleUsage(str) {
365
+ return str.split(" ").map((word) => {
366
+ if (word === "[options]")
367
+ return this.styleOptionText(word);
368
+ if (word === "[command]")
369
+ return this.styleSubcommandText(word);
370
+ if (word[0] === "[" || word[0] === "<")
371
+ return this.styleArgumentText(word);
372
+ return this.styleCommandText(word);
373
+ }).join(" ");
374
+ }
375
+ styleCommandDescription(str) {
376
+ return this.styleDescriptionText(str);
377
+ }
378
+ styleOptionDescription(str) {
379
+ return this.styleDescriptionText(str);
380
+ }
381
+ styleSubcommandDescription(str) {
382
+ return this.styleDescriptionText(str);
383
+ }
384
+ styleArgumentDescription(str) {
385
+ return this.styleDescriptionText(str);
386
+ }
387
+ styleDescriptionText(str) {
388
+ return str;
389
+ }
390
+ styleOptionTerm(str) {
391
+ return this.styleOptionText(str);
392
+ }
393
+ styleSubcommandTerm(str) {
394
+ return str.split(" ").map((word) => {
395
+ if (word === "[options]")
396
+ return this.styleOptionText(word);
397
+ if (word[0] === "[" || word[0] === "<")
398
+ return this.styleArgumentText(word);
399
+ return this.styleSubcommandText(word);
400
+ }).join(" ");
401
+ }
402
+ styleArgumentTerm(str) {
403
+ return this.styleArgumentText(str);
404
+ }
405
+ styleOptionText(str) {
406
+ return str;
407
+ }
408
+ styleArgumentText(str) {
409
+ return str;
410
+ }
411
+ styleSubcommandText(str) {
412
+ return str;
413
+ }
414
+ styleCommandText(str) {
415
+ return str;
416
+ }
417
+ padWidth(cmd, helper) {
418
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
419
+ }
420
+ preformatted(str) {
421
+ return /\n[^\S\r\n]/.test(str);
422
+ }
423
+ formatItem(term, termWidth, description, helper) {
424
+ const itemIndent = 2;
425
+ const itemIndentStr = " ".repeat(itemIndent);
426
+ if (!description)
427
+ return itemIndentStr + term;
428
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
429
+ const spacerWidth = 2;
430
+ const helpWidth = this.helpWidth ?? 80;
431
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
432
+ let formattedDescription;
433
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
434
+ formattedDescription = description;
435
+ } else {
436
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
437
+ formattedDescription = wrappedDescription.replace(/\n/g, `
438
+ ` + " ".repeat(termWidth + spacerWidth));
439
+ }
440
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
441
+ ${itemIndentStr}`);
442
+ }
443
+ boxWrap(str, width) {
444
+ if (width < this.minWidthToWrap)
445
+ return str;
446
+ const rawLines = str.split(/\r\n|\n/);
447
+ const chunkPattern = /[\s]*[^\s]+/g;
448
+ const wrappedLines = [];
449
+ rawLines.forEach((line) => {
450
+ const chunks = line.match(chunkPattern);
451
+ if (chunks === null) {
452
+ wrappedLines.push("");
453
+ return;
454
+ }
455
+ let sumChunks = [chunks.shift()];
456
+ let sumWidth = this.displayWidth(sumChunks[0]);
457
+ chunks.forEach((chunk) => {
458
+ const visibleWidth = this.displayWidth(chunk);
459
+ if (sumWidth + visibleWidth <= width) {
460
+ sumChunks.push(chunk);
461
+ sumWidth += visibleWidth;
462
+ return;
463
+ }
464
+ wrappedLines.push(sumChunks.join(""));
465
+ const nextChunk = chunk.trimStart();
466
+ sumChunks = [nextChunk];
467
+ sumWidth = this.displayWidth(nextChunk);
468
+ });
469
+ wrappedLines.push(sumChunks.join(""));
470
+ });
471
+ return wrappedLines.join(`
472
+ `);
473
+ }
474
+ }
475
+ function stripColor(str) {
476
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
477
+ return str.replace(sgrPattern, "");
478
+ }
479
+ exports.Help = Help;
480
+ exports.stripColor = stripColor;
481
+ });
482
+
483
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/option.js
484
+ var require_option = __commonJS((exports) => {
485
+ var { InvalidArgumentError } = require_error();
486
+
487
+ class Option {
488
+ constructor(flags, description) {
489
+ this.flags = flags;
490
+ this.description = description || "";
491
+ this.required = flags.includes("<");
492
+ this.optional = flags.includes("[");
493
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
494
+ this.mandatory = false;
495
+ const optionFlags = splitOptionFlags(flags);
496
+ this.short = optionFlags.shortFlag;
497
+ this.long = optionFlags.longFlag;
498
+ this.negate = false;
499
+ if (this.long) {
500
+ this.negate = this.long.startsWith("--no-");
501
+ }
502
+ this.defaultValue = undefined;
503
+ this.defaultValueDescription = undefined;
504
+ this.presetArg = undefined;
505
+ this.envVar = undefined;
506
+ this.parseArg = undefined;
507
+ this.hidden = false;
508
+ this.argChoices = undefined;
509
+ this.conflictsWith = [];
510
+ this.implied = undefined;
511
+ this.helpGroupHeading = undefined;
512
+ }
513
+ default(value, description) {
514
+ this.defaultValue = value;
515
+ this.defaultValueDescription = description;
516
+ return this;
517
+ }
518
+ preset(arg) {
519
+ this.presetArg = arg;
520
+ return this;
521
+ }
522
+ conflicts(names) {
523
+ this.conflictsWith = this.conflictsWith.concat(names);
524
+ return this;
525
+ }
526
+ implies(impliedOptionValues) {
527
+ let newImplied = impliedOptionValues;
528
+ if (typeof impliedOptionValues === "string") {
529
+ newImplied = { [impliedOptionValues]: true };
530
+ }
531
+ this.implied = Object.assign(this.implied || {}, newImplied);
532
+ return this;
533
+ }
534
+ env(name) {
535
+ this.envVar = name;
536
+ return this;
537
+ }
538
+ argParser(fn) {
539
+ this.parseArg = fn;
540
+ return this;
541
+ }
542
+ makeOptionMandatory(mandatory = true) {
543
+ this.mandatory = !!mandatory;
544
+ return this;
545
+ }
546
+ hideHelp(hide = true) {
547
+ this.hidden = !!hide;
548
+ return this;
549
+ }
550
+ _collectValue(value, previous) {
551
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
552
+ return [value];
553
+ }
554
+ previous.push(value);
555
+ return previous;
556
+ }
557
+ choices(values) {
558
+ this.argChoices = values.slice();
559
+ this.parseArg = (arg, previous) => {
560
+ if (!this.argChoices.includes(arg)) {
561
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
562
+ }
563
+ if (this.variadic) {
564
+ return this._collectValue(arg, previous);
565
+ }
566
+ return arg;
567
+ };
568
+ return this;
569
+ }
570
+ name() {
571
+ if (this.long) {
572
+ return this.long.replace(/^--/, "");
573
+ }
574
+ return this.short.replace(/^-/, "");
575
+ }
576
+ attributeName() {
577
+ if (this.negate) {
578
+ return camelcase(this.name().replace(/^no-/, ""));
579
+ }
580
+ return camelcase(this.name());
581
+ }
582
+ helpGroup(heading) {
583
+ this.helpGroupHeading = heading;
584
+ return this;
585
+ }
586
+ is(arg) {
587
+ return this.short === arg || this.long === arg;
588
+ }
589
+ isBoolean() {
590
+ return !this.required && !this.optional && !this.negate;
591
+ }
592
+ }
593
+
594
+ class DualOptions {
595
+ constructor(options) {
596
+ this.positiveOptions = new Map;
597
+ this.negativeOptions = new Map;
598
+ this.dualOptions = new Set;
599
+ options.forEach((option) => {
600
+ if (option.negate) {
601
+ this.negativeOptions.set(option.attributeName(), option);
602
+ } else {
603
+ this.positiveOptions.set(option.attributeName(), option);
604
+ }
605
+ });
606
+ this.negativeOptions.forEach((value, key) => {
607
+ if (this.positiveOptions.has(key)) {
608
+ this.dualOptions.add(key);
609
+ }
610
+ });
611
+ }
612
+ valueFromOption(value, option) {
613
+ const optionKey = option.attributeName();
614
+ if (!this.dualOptions.has(optionKey))
615
+ return true;
616
+ const preset = this.negativeOptions.get(optionKey).presetArg;
617
+ const negativeValue = preset !== undefined ? preset : false;
618
+ return option.negate === (negativeValue === value);
619
+ }
620
+ }
621
+ function camelcase(str) {
622
+ return str.split("-").reduce((str2, word) => {
623
+ return str2 + word[0].toUpperCase() + word.slice(1);
624
+ });
625
+ }
626
+ function splitOptionFlags(flags) {
627
+ let shortFlag;
628
+ let longFlag;
629
+ const shortFlagExp = /^-[^-]$/;
630
+ const longFlagExp = /^--[^-]/;
631
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
632
+ if (shortFlagExp.test(flagParts[0]))
633
+ shortFlag = flagParts.shift();
634
+ if (longFlagExp.test(flagParts[0]))
635
+ longFlag = flagParts.shift();
636
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
637
+ shortFlag = flagParts.shift();
638
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
639
+ shortFlag = longFlag;
640
+ longFlag = flagParts.shift();
641
+ }
642
+ if (flagParts[0].startsWith("-")) {
643
+ const unsupportedFlag = flagParts[0];
644
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
645
+ if (/^-[^-][^-]/.test(unsupportedFlag))
646
+ throw new Error(`${baseError}
647
+ - a short flag is a single dash and a single character
648
+ - either use a single dash and a single character (for a short flag)
649
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
650
+ if (shortFlagExp.test(unsupportedFlag))
651
+ throw new Error(`${baseError}
652
+ - too many short flags`);
653
+ if (longFlagExp.test(unsupportedFlag))
654
+ throw new Error(`${baseError}
655
+ - too many long flags`);
656
+ throw new Error(`${baseError}
657
+ - unrecognised flag format`);
658
+ }
659
+ if (shortFlag === undefined && longFlag === undefined)
660
+ throw new Error(`option creation failed due to no flags found in '${flags}'.`);
661
+ return { shortFlag, longFlag };
662
+ }
663
+ exports.Option = Option;
664
+ exports.DualOptions = DualOptions;
665
+ });
666
+
667
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/suggestSimilar.js
668
+ var require_suggestSimilar = __commonJS((exports) => {
669
+ var maxDistance = 3;
670
+ function editDistance(a, b) {
671
+ if (Math.abs(a.length - b.length) > maxDistance)
672
+ return Math.max(a.length, b.length);
673
+ const d = [];
674
+ for (let i = 0;i <= a.length; i++) {
675
+ d[i] = [i];
676
+ }
677
+ for (let j = 0;j <= b.length; j++) {
678
+ d[0][j] = j;
679
+ }
680
+ for (let j = 1;j <= b.length; j++) {
681
+ for (let i = 1;i <= a.length; i++) {
682
+ let cost = 1;
683
+ if (a[i - 1] === b[j - 1]) {
684
+ cost = 0;
685
+ } else {
686
+ cost = 1;
687
+ }
688
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
689
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
690
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
691
+ }
692
+ }
693
+ }
694
+ return d[a.length][b.length];
695
+ }
696
+ function suggestSimilar(word, candidates) {
697
+ if (!candidates || candidates.length === 0)
698
+ return "";
699
+ candidates = Array.from(new Set(candidates));
700
+ const searchingOptions = word.startsWith("--");
701
+ if (searchingOptions) {
702
+ word = word.slice(2);
703
+ candidates = candidates.map((candidate) => candidate.slice(2));
704
+ }
705
+ let similar = [];
706
+ let bestDistance = maxDistance;
707
+ const minSimilarity = 0.4;
708
+ candidates.forEach((candidate) => {
709
+ if (candidate.length <= 1)
710
+ return;
711
+ const distance = editDistance(word, candidate);
712
+ const length = Math.max(word.length, candidate.length);
713
+ const similarity = (length - distance) / length;
714
+ if (similarity > minSimilarity) {
715
+ if (distance < bestDistance) {
716
+ bestDistance = distance;
717
+ similar = [candidate];
718
+ } else if (distance === bestDistance) {
719
+ similar.push(candidate);
720
+ }
721
+ }
722
+ });
723
+ similar.sort((a, b) => a.localeCompare(b));
724
+ if (searchingOptions) {
725
+ similar = similar.map((candidate) => `--${candidate}`);
726
+ }
727
+ if (similar.length > 1) {
728
+ return `
729
+ (Did you mean one of ${similar.join(", ")}?)`;
730
+ }
731
+ if (similar.length === 1) {
732
+ return `
733
+ (Did you mean ${similar[0]}?)`;
734
+ }
735
+ return "";
736
+ }
737
+ exports.suggestSimilar = suggestSimilar;
738
+ });
739
+
740
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/lib/command.js
741
+ var require_command = __commonJS((exports) => {
742
+ var EventEmitter = __require("node:events").EventEmitter;
743
+ var childProcess = __require("node:child_process");
744
+ var path = __require("node:path");
745
+ var fs = __require("node:fs");
746
+ var process2 = __require("node:process");
747
+ var { Argument, humanReadableArgName } = require_argument();
748
+ var { CommanderError } = require_error();
749
+ var { Help, stripColor } = require_help();
750
+ var { Option, DualOptions } = require_option();
751
+ var { suggestSimilar } = require_suggestSimilar();
752
+
753
+ class Command extends EventEmitter {
754
+ constructor(name) {
755
+ super();
756
+ this.commands = [];
757
+ this.options = [];
758
+ this.parent = null;
759
+ this._allowUnknownOption = false;
760
+ this._allowExcessArguments = false;
761
+ this.registeredArguments = [];
762
+ this._args = this.registeredArguments;
763
+ this.args = [];
764
+ this.rawArgs = [];
765
+ this.processedArgs = [];
766
+ this._scriptPath = null;
767
+ this._name = name || "";
768
+ this._optionValues = {};
769
+ this._optionValueSources = {};
770
+ this._storeOptionsAsProperties = false;
771
+ this._actionHandler = null;
772
+ this._executableHandler = false;
773
+ this._executableFile = null;
774
+ this._executableDir = null;
775
+ this._defaultCommandName = null;
776
+ this._exitCallback = null;
777
+ this._aliases = [];
778
+ this._combineFlagAndOptionalValue = true;
779
+ this._description = "";
780
+ this._summary = "";
781
+ this._argsDescription = undefined;
782
+ this._enablePositionalOptions = false;
783
+ this._passThroughOptions = false;
784
+ this._lifeCycleHooks = {};
785
+ this._showHelpAfterError = false;
786
+ this._showSuggestionAfterError = true;
787
+ this._savedState = null;
788
+ this._outputConfiguration = {
789
+ writeOut: (str) => process2.stdout.write(str),
790
+ writeErr: (str) => process2.stderr.write(str),
791
+ outputError: (str, write) => write(str),
792
+ getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : undefined,
793
+ getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : undefined,
794
+ getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
795
+ getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
796
+ stripColor: (str) => stripColor(str)
797
+ };
798
+ this._hidden = false;
799
+ this._helpOption = undefined;
800
+ this._addImplicitHelpCommand = undefined;
801
+ this._helpCommand = undefined;
802
+ this._helpConfiguration = {};
803
+ this._helpGroupHeading = undefined;
804
+ this._defaultCommandGroup = undefined;
805
+ this._defaultOptionGroup = undefined;
806
+ }
807
+ copyInheritedSettings(sourceCommand) {
808
+ this._outputConfiguration = sourceCommand._outputConfiguration;
809
+ this._helpOption = sourceCommand._helpOption;
810
+ this._helpCommand = sourceCommand._helpCommand;
811
+ this._helpConfiguration = sourceCommand._helpConfiguration;
812
+ this._exitCallback = sourceCommand._exitCallback;
813
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
814
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
815
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
816
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
817
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
818
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
819
+ return this;
820
+ }
821
+ _getCommandAndAncestors() {
822
+ const result = [];
823
+ for (let command = this;command; command = command.parent) {
824
+ result.push(command);
825
+ }
826
+ return result;
827
+ }
828
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
829
+ let desc = actionOptsOrExecDesc;
830
+ let opts = execOpts;
831
+ if (typeof desc === "object" && desc !== null) {
832
+ opts = desc;
833
+ desc = null;
834
+ }
835
+ opts = opts || {};
836
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
837
+ const cmd = this.createCommand(name);
838
+ if (desc) {
839
+ cmd.description(desc);
840
+ cmd._executableHandler = true;
841
+ }
842
+ if (opts.isDefault)
843
+ this._defaultCommandName = cmd._name;
844
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
845
+ cmd._executableFile = opts.executableFile || null;
846
+ if (args)
847
+ cmd.arguments(args);
848
+ this._registerCommand(cmd);
849
+ cmd.parent = this;
850
+ cmd.copyInheritedSettings(this);
851
+ if (desc)
852
+ return this;
853
+ return cmd;
854
+ }
855
+ createCommand(name) {
856
+ return new Command(name);
857
+ }
858
+ createHelp() {
859
+ return Object.assign(new Help, this.configureHelp());
860
+ }
861
+ configureHelp(configuration) {
862
+ if (configuration === undefined)
863
+ return this._helpConfiguration;
864
+ this._helpConfiguration = configuration;
865
+ return this;
866
+ }
867
+ configureOutput(configuration) {
868
+ if (configuration === undefined)
869
+ return this._outputConfiguration;
870
+ this._outputConfiguration = {
871
+ ...this._outputConfiguration,
872
+ ...configuration
873
+ };
874
+ return this;
875
+ }
876
+ showHelpAfterError(displayHelp = true) {
877
+ if (typeof displayHelp !== "string")
878
+ displayHelp = !!displayHelp;
879
+ this._showHelpAfterError = displayHelp;
880
+ return this;
881
+ }
882
+ showSuggestionAfterError(displaySuggestion = true) {
883
+ this._showSuggestionAfterError = !!displaySuggestion;
884
+ return this;
885
+ }
886
+ addCommand(cmd, opts) {
887
+ if (!cmd._name) {
888
+ throw new Error(`Command passed to .addCommand() must have a name
889
+ - specify the name in Command constructor or using .name()`);
890
+ }
891
+ opts = opts || {};
892
+ if (opts.isDefault)
893
+ this._defaultCommandName = cmd._name;
894
+ if (opts.noHelp || opts.hidden)
895
+ cmd._hidden = true;
896
+ this._registerCommand(cmd);
897
+ cmd.parent = this;
898
+ cmd._checkForBrokenPassThrough();
899
+ return this;
900
+ }
901
+ createArgument(name, description) {
902
+ return new Argument(name, description);
903
+ }
904
+ argument(name, description, parseArg, defaultValue) {
905
+ const argument = this.createArgument(name, description);
906
+ if (typeof parseArg === "function") {
907
+ argument.default(defaultValue).argParser(parseArg);
908
+ } else {
909
+ argument.default(parseArg);
910
+ }
911
+ this.addArgument(argument);
912
+ return this;
913
+ }
914
+ arguments(names) {
915
+ names.trim().split(/ +/).forEach((detail) => {
916
+ this.argument(detail);
917
+ });
918
+ return this;
919
+ }
920
+ addArgument(argument) {
921
+ const previousArgument = this.registeredArguments.slice(-1)[0];
922
+ if (previousArgument?.variadic) {
923
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
924
+ }
925
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
926
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
927
+ }
928
+ this.registeredArguments.push(argument);
929
+ return this;
930
+ }
931
+ helpCommand(enableOrNameAndArgs, description) {
932
+ if (typeof enableOrNameAndArgs === "boolean") {
933
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
934
+ if (enableOrNameAndArgs && this._defaultCommandGroup) {
935
+ this._initCommandGroup(this._getHelpCommand());
936
+ }
937
+ return this;
938
+ }
939
+ const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
940
+ const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
941
+ const helpDescription = description ?? "display help for command";
942
+ const helpCommand = this.createCommand(helpName);
943
+ helpCommand.helpOption(false);
944
+ if (helpArgs)
945
+ helpCommand.arguments(helpArgs);
946
+ if (helpDescription)
947
+ helpCommand.description(helpDescription);
948
+ this._addImplicitHelpCommand = true;
949
+ this._helpCommand = helpCommand;
950
+ if (enableOrNameAndArgs || description)
951
+ this._initCommandGroup(helpCommand);
952
+ return this;
953
+ }
954
+ addHelpCommand(helpCommand, deprecatedDescription) {
955
+ if (typeof helpCommand !== "object") {
956
+ this.helpCommand(helpCommand, deprecatedDescription);
957
+ return this;
958
+ }
959
+ this._addImplicitHelpCommand = true;
960
+ this._helpCommand = helpCommand;
961
+ this._initCommandGroup(helpCommand);
962
+ return this;
963
+ }
964
+ _getHelpCommand() {
965
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
966
+ if (hasImplicitHelpCommand) {
967
+ if (this._helpCommand === undefined) {
968
+ this.helpCommand(undefined, undefined);
969
+ }
970
+ return this._helpCommand;
971
+ }
972
+ return null;
973
+ }
974
+ hook(event, listener) {
975
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
976
+ if (!allowedValues.includes(event)) {
977
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
978
+ Expecting one of '${allowedValues.join("', '")}'`);
979
+ }
980
+ if (this._lifeCycleHooks[event]) {
981
+ this._lifeCycleHooks[event].push(listener);
982
+ } else {
983
+ this._lifeCycleHooks[event] = [listener];
984
+ }
985
+ return this;
986
+ }
987
+ exitOverride(fn) {
988
+ if (fn) {
989
+ this._exitCallback = fn;
990
+ } else {
991
+ this._exitCallback = (err) => {
992
+ if (err.code !== "commander.executeSubCommandAsync") {
993
+ throw err;
994
+ } else {
995
+ }
996
+ };
997
+ }
998
+ return this;
999
+ }
1000
+ _exit(exitCode, code, message) {
1001
+ if (this._exitCallback) {
1002
+ this._exitCallback(new CommanderError(exitCode, code, message));
1003
+ }
1004
+ process2.exit(exitCode);
1005
+ }
1006
+ action(fn) {
1007
+ const listener = (args) => {
1008
+ const expectedArgsCount = this.registeredArguments.length;
1009
+ const actionArgs = args.slice(0, expectedArgsCount);
1010
+ if (this._storeOptionsAsProperties) {
1011
+ actionArgs[expectedArgsCount] = this;
1012
+ } else {
1013
+ actionArgs[expectedArgsCount] = this.opts();
1014
+ }
1015
+ actionArgs.push(this);
1016
+ return fn.apply(this, actionArgs);
1017
+ };
1018
+ this._actionHandler = listener;
1019
+ return this;
1020
+ }
1021
+ createOption(flags, description) {
1022
+ return new Option(flags, description);
1023
+ }
1024
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1025
+ try {
1026
+ return target.parseArg(value, previous);
1027
+ } catch (err) {
1028
+ if (err.code === "commander.invalidArgument") {
1029
+ const message = `${invalidArgumentMessage} ${err.message}`;
1030
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1031
+ }
1032
+ throw err;
1033
+ }
1034
+ }
1035
+ _registerOption(option) {
1036
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1037
+ if (matchingOption) {
1038
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1039
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1040
+ - already used by option '${matchingOption.flags}'`);
1041
+ }
1042
+ this._initOptionGroup(option);
1043
+ this.options.push(option);
1044
+ }
1045
+ _registerCommand(command) {
1046
+ const knownBy = (cmd) => {
1047
+ return [cmd.name()].concat(cmd.aliases());
1048
+ };
1049
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1050
+ if (alreadyUsed) {
1051
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1052
+ const newCmd = knownBy(command).join("|");
1053
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1054
+ }
1055
+ this._initCommandGroup(command);
1056
+ this.commands.push(command);
1057
+ }
1058
+ addOption(option) {
1059
+ this._registerOption(option);
1060
+ const oname = option.name();
1061
+ const name = option.attributeName();
1062
+ if (option.negate) {
1063
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1064
+ if (!this._findOption(positiveLongFlag)) {
1065
+ this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
1066
+ }
1067
+ } else if (option.defaultValue !== undefined) {
1068
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1069
+ }
1070
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1071
+ if (val == null && option.presetArg !== undefined) {
1072
+ val = option.presetArg;
1073
+ }
1074
+ const oldValue = this.getOptionValue(name);
1075
+ if (val !== null && option.parseArg) {
1076
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1077
+ } else if (val !== null && option.variadic) {
1078
+ val = option._collectValue(val, oldValue);
1079
+ }
1080
+ if (val == null) {
1081
+ if (option.negate) {
1082
+ val = false;
1083
+ } else if (option.isBoolean() || option.optional) {
1084
+ val = true;
1085
+ } else {
1086
+ val = "";
1087
+ }
1088
+ }
1089
+ this.setOptionValueWithSource(name, val, valueSource);
1090
+ };
1091
+ this.on("option:" + oname, (val) => {
1092
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1093
+ handleOptionValue(val, invalidValueMessage, "cli");
1094
+ });
1095
+ if (option.envVar) {
1096
+ this.on("optionEnv:" + oname, (val) => {
1097
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1098
+ handleOptionValue(val, invalidValueMessage, "env");
1099
+ });
1100
+ }
1101
+ return this;
1102
+ }
1103
+ _optionEx(config, flags, description, fn, defaultValue) {
1104
+ if (typeof flags === "object" && flags instanceof Option) {
1105
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1106
+ }
1107
+ const option = this.createOption(flags, description);
1108
+ option.makeOptionMandatory(!!config.mandatory);
1109
+ if (typeof fn === "function") {
1110
+ option.default(defaultValue).argParser(fn);
1111
+ } else if (fn instanceof RegExp) {
1112
+ const regex = fn;
1113
+ fn = (val, def) => {
1114
+ const m = regex.exec(val);
1115
+ return m ? m[0] : def;
1116
+ };
1117
+ option.default(defaultValue).argParser(fn);
1118
+ } else {
1119
+ option.default(fn);
1120
+ }
1121
+ return this.addOption(option);
1122
+ }
1123
+ option(flags, description, parseArg, defaultValue) {
1124
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1125
+ }
1126
+ requiredOption(flags, description, parseArg, defaultValue) {
1127
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1128
+ }
1129
+ combineFlagAndOptionalValue(combine = true) {
1130
+ this._combineFlagAndOptionalValue = !!combine;
1131
+ return this;
1132
+ }
1133
+ allowUnknownOption(allowUnknown = true) {
1134
+ this._allowUnknownOption = !!allowUnknown;
1135
+ return this;
1136
+ }
1137
+ allowExcessArguments(allowExcess = true) {
1138
+ this._allowExcessArguments = !!allowExcess;
1139
+ return this;
1140
+ }
1141
+ enablePositionalOptions(positional = true) {
1142
+ this._enablePositionalOptions = !!positional;
1143
+ return this;
1144
+ }
1145
+ passThroughOptions(passThrough = true) {
1146
+ this._passThroughOptions = !!passThrough;
1147
+ this._checkForBrokenPassThrough();
1148
+ return this;
1149
+ }
1150
+ _checkForBrokenPassThrough() {
1151
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1152
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1153
+ }
1154
+ }
1155
+ storeOptionsAsProperties(storeAsProperties = true) {
1156
+ if (this.options.length) {
1157
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1158
+ }
1159
+ if (Object.keys(this._optionValues).length) {
1160
+ throw new Error("call .storeOptionsAsProperties() before setting option values");
1161
+ }
1162
+ this._storeOptionsAsProperties = !!storeAsProperties;
1163
+ return this;
1164
+ }
1165
+ getOptionValue(key) {
1166
+ if (this._storeOptionsAsProperties) {
1167
+ return this[key];
1168
+ }
1169
+ return this._optionValues[key];
1170
+ }
1171
+ setOptionValue(key, value) {
1172
+ return this.setOptionValueWithSource(key, value, undefined);
1173
+ }
1174
+ setOptionValueWithSource(key, value, source) {
1175
+ if (this._storeOptionsAsProperties) {
1176
+ this[key] = value;
1177
+ } else {
1178
+ this._optionValues[key] = value;
1179
+ }
1180
+ this._optionValueSources[key] = source;
1181
+ return this;
1182
+ }
1183
+ getOptionValueSource(key) {
1184
+ return this._optionValueSources[key];
1185
+ }
1186
+ getOptionValueSourceWithGlobals(key) {
1187
+ let source;
1188
+ this._getCommandAndAncestors().forEach((cmd) => {
1189
+ if (cmd.getOptionValueSource(key) !== undefined) {
1190
+ source = cmd.getOptionValueSource(key);
1191
+ }
1192
+ });
1193
+ return source;
1194
+ }
1195
+ _prepareUserArgs(argv, parseOptions) {
1196
+ if (argv !== undefined && !Array.isArray(argv)) {
1197
+ throw new Error("first parameter to parse must be array or undefined");
1198
+ }
1199
+ parseOptions = parseOptions || {};
1200
+ if (argv === undefined && parseOptions.from === undefined) {
1201
+ if (process2.versions?.electron) {
1202
+ parseOptions.from = "electron";
1203
+ }
1204
+ const execArgv = process2.execArgv ?? [];
1205
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1206
+ parseOptions.from = "eval";
1207
+ }
1208
+ }
1209
+ if (argv === undefined) {
1210
+ argv = process2.argv;
1211
+ }
1212
+ this.rawArgs = argv.slice();
1213
+ let userArgs;
1214
+ switch (parseOptions.from) {
1215
+ case undefined:
1216
+ case "node":
1217
+ this._scriptPath = argv[1];
1218
+ userArgs = argv.slice(2);
1219
+ break;
1220
+ case "electron":
1221
+ if (process2.defaultApp) {
1222
+ this._scriptPath = argv[1];
1223
+ userArgs = argv.slice(2);
1224
+ } else {
1225
+ userArgs = argv.slice(1);
1226
+ }
1227
+ break;
1228
+ case "user":
1229
+ userArgs = argv.slice(0);
1230
+ break;
1231
+ case "eval":
1232
+ userArgs = argv.slice(1);
1233
+ break;
1234
+ default:
1235
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1236
+ }
1237
+ if (!this._name && this._scriptPath)
1238
+ this.nameFromFilename(this._scriptPath);
1239
+ this._name = this._name || "program";
1240
+ return userArgs;
1241
+ }
1242
+ parse(argv, parseOptions) {
1243
+ this._prepareForParse();
1244
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1245
+ this._parseCommand([], userArgs);
1246
+ return this;
1247
+ }
1248
+ async parseAsync(argv, parseOptions) {
1249
+ this._prepareForParse();
1250
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1251
+ await this._parseCommand([], userArgs);
1252
+ return this;
1253
+ }
1254
+ _prepareForParse() {
1255
+ if (this._savedState === null) {
1256
+ this.saveStateBeforeParse();
1257
+ } else {
1258
+ this.restoreStateBeforeParse();
1259
+ }
1260
+ }
1261
+ saveStateBeforeParse() {
1262
+ this._savedState = {
1263
+ _name: this._name,
1264
+ _optionValues: { ...this._optionValues },
1265
+ _optionValueSources: { ...this._optionValueSources }
1266
+ };
1267
+ }
1268
+ restoreStateBeforeParse() {
1269
+ if (this._storeOptionsAsProperties)
1270
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1271
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1272
+ this._name = this._savedState._name;
1273
+ this._scriptPath = null;
1274
+ this.rawArgs = [];
1275
+ this._optionValues = { ...this._savedState._optionValues };
1276
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1277
+ this.args = [];
1278
+ this.processedArgs = [];
1279
+ }
1280
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1281
+ if (fs.existsSync(executableFile))
1282
+ return;
1283
+ 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";
1284
+ const executableMissing = `'${executableFile}' does not exist
1285
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1286
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1287
+ - ${executableDirMessage}`;
1288
+ throw new Error(executableMissing);
1289
+ }
1290
+ _executeSubCommand(subcommand, args) {
1291
+ args = args.slice();
1292
+ let launchWithNode = false;
1293
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1294
+ function findFile(baseDir, baseName) {
1295
+ const localBin = path.resolve(baseDir, baseName);
1296
+ if (fs.existsSync(localBin))
1297
+ return localBin;
1298
+ if (sourceExt.includes(path.extname(baseName)))
1299
+ return;
1300
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1301
+ if (foundExt)
1302
+ return `${localBin}${foundExt}`;
1303
+ return;
1304
+ }
1305
+ this._checkForMissingMandatoryOptions();
1306
+ this._checkForConflictingOptions();
1307
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1308
+ let executableDir = this._executableDir || "";
1309
+ if (this._scriptPath) {
1310
+ let resolvedScriptPath;
1311
+ try {
1312
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1313
+ } catch {
1314
+ resolvedScriptPath = this._scriptPath;
1315
+ }
1316
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1317
+ }
1318
+ if (executableDir) {
1319
+ let localFile = findFile(executableDir, executableFile);
1320
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1321
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1322
+ if (legacyName !== this._name) {
1323
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1324
+ }
1325
+ }
1326
+ executableFile = localFile || executableFile;
1327
+ }
1328
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1329
+ let proc;
1330
+ if (process2.platform !== "win32") {
1331
+ if (launchWithNode) {
1332
+ args.unshift(executableFile);
1333
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1334
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1335
+ } else {
1336
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1337
+ }
1338
+ } else {
1339
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1340
+ args.unshift(executableFile);
1341
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1342
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1343
+ }
1344
+ if (!proc.killed) {
1345
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1346
+ signals.forEach((signal) => {
1347
+ process2.on(signal, () => {
1348
+ if (proc.killed === false && proc.exitCode === null) {
1349
+ proc.kill(signal);
1350
+ }
1351
+ });
1352
+ });
1353
+ }
1354
+ const exitCallback = this._exitCallback;
1355
+ proc.on("close", (code) => {
1356
+ code = code ?? 1;
1357
+ if (!exitCallback) {
1358
+ process2.exit(code);
1359
+ } else {
1360
+ exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1361
+ }
1362
+ });
1363
+ proc.on("error", (err) => {
1364
+ if (err.code === "ENOENT") {
1365
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1366
+ } else if (err.code === "EACCES") {
1367
+ throw new Error(`'${executableFile}' not executable`);
1368
+ }
1369
+ if (!exitCallback) {
1370
+ process2.exit(1);
1371
+ } else {
1372
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1373
+ wrappedError.nestedError = err;
1374
+ exitCallback(wrappedError);
1375
+ }
1376
+ });
1377
+ this.runningCommand = proc;
1378
+ }
1379
+ _dispatchSubcommand(commandName, operands, unknown) {
1380
+ const subCommand = this._findCommand(commandName);
1381
+ if (!subCommand)
1382
+ this.help({ error: true });
1383
+ subCommand._prepareForParse();
1384
+ let promiseChain;
1385
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1386
+ promiseChain = this._chainOrCall(promiseChain, () => {
1387
+ if (subCommand._executableHandler) {
1388
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1389
+ } else {
1390
+ return subCommand._parseCommand(operands, unknown);
1391
+ }
1392
+ });
1393
+ return promiseChain;
1394
+ }
1395
+ _dispatchHelpCommand(subcommandName) {
1396
+ if (!subcommandName) {
1397
+ this.help();
1398
+ }
1399
+ const subCommand = this._findCommand(subcommandName);
1400
+ if (subCommand && !subCommand._executableHandler) {
1401
+ subCommand.help();
1402
+ }
1403
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
1404
+ }
1405
+ _checkNumberOfArguments() {
1406
+ this.registeredArguments.forEach((arg, i) => {
1407
+ if (arg.required && this.args[i] == null) {
1408
+ this.missingArgument(arg.name());
1409
+ }
1410
+ });
1411
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1412
+ return;
1413
+ }
1414
+ if (this.args.length > this.registeredArguments.length) {
1415
+ this._excessArguments(this.args);
1416
+ }
1417
+ }
1418
+ _processArguments() {
1419
+ const myParseArg = (argument, value, previous) => {
1420
+ let parsedValue = value;
1421
+ if (value !== null && argument.parseArg) {
1422
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1423
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1424
+ }
1425
+ return parsedValue;
1426
+ };
1427
+ this._checkNumberOfArguments();
1428
+ const processedArgs = [];
1429
+ this.registeredArguments.forEach((declaredArg, index) => {
1430
+ let value = declaredArg.defaultValue;
1431
+ if (declaredArg.variadic) {
1432
+ if (index < this.args.length) {
1433
+ value = this.args.slice(index);
1434
+ if (declaredArg.parseArg) {
1435
+ value = value.reduce((processed, v) => {
1436
+ return myParseArg(declaredArg, v, processed);
1437
+ }, declaredArg.defaultValue);
1438
+ }
1439
+ } else if (value === undefined) {
1440
+ value = [];
1441
+ }
1442
+ } else if (index < this.args.length) {
1443
+ value = this.args[index];
1444
+ if (declaredArg.parseArg) {
1445
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1446
+ }
1447
+ }
1448
+ processedArgs[index] = value;
1449
+ });
1450
+ this.processedArgs = processedArgs;
1451
+ }
1452
+ _chainOrCall(promise, fn) {
1453
+ if (promise?.then && typeof promise.then === "function") {
1454
+ return promise.then(() => fn());
1455
+ }
1456
+ return fn();
1457
+ }
1458
+ _chainOrCallHooks(promise, event) {
1459
+ let result = promise;
1460
+ const hooks = [];
1461
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
1462
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1463
+ hooks.push({ hookedCommand, callback });
1464
+ });
1465
+ });
1466
+ if (event === "postAction") {
1467
+ hooks.reverse();
1468
+ }
1469
+ hooks.forEach((hookDetail) => {
1470
+ result = this._chainOrCall(result, () => {
1471
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1472
+ });
1473
+ });
1474
+ return result;
1475
+ }
1476
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1477
+ let result = promise;
1478
+ if (this._lifeCycleHooks[event] !== undefined) {
1479
+ this._lifeCycleHooks[event].forEach((hook) => {
1480
+ result = this._chainOrCall(result, () => {
1481
+ return hook(this, subCommand);
1482
+ });
1483
+ });
1484
+ }
1485
+ return result;
1486
+ }
1487
+ _parseCommand(operands, unknown) {
1488
+ const parsed = this.parseOptions(unknown);
1489
+ this._parseOptionsEnv();
1490
+ this._parseOptionsImplied();
1491
+ operands = operands.concat(parsed.operands);
1492
+ unknown = parsed.unknown;
1493
+ this.args = operands.concat(unknown);
1494
+ if (operands && this._findCommand(operands[0])) {
1495
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1496
+ }
1497
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
1498
+ return this._dispatchHelpCommand(operands[1]);
1499
+ }
1500
+ if (this._defaultCommandName) {
1501
+ this._outputHelpIfRequested(unknown);
1502
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1503
+ }
1504
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1505
+ this.help({ error: true });
1506
+ }
1507
+ this._outputHelpIfRequested(parsed.unknown);
1508
+ this._checkForMissingMandatoryOptions();
1509
+ this._checkForConflictingOptions();
1510
+ const checkForUnknownOptions = () => {
1511
+ if (parsed.unknown.length > 0) {
1512
+ this.unknownOption(parsed.unknown[0]);
1513
+ }
1514
+ };
1515
+ const commandEvent = `command:${this.name()}`;
1516
+ if (this._actionHandler) {
1517
+ checkForUnknownOptions();
1518
+ this._processArguments();
1519
+ let promiseChain;
1520
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
1521
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
1522
+ if (this.parent) {
1523
+ promiseChain = this._chainOrCall(promiseChain, () => {
1524
+ this.parent.emit(commandEvent, operands, unknown);
1525
+ });
1526
+ }
1527
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
1528
+ return promiseChain;
1529
+ }
1530
+ if (this.parent?.listenerCount(commandEvent)) {
1531
+ checkForUnknownOptions();
1532
+ this._processArguments();
1533
+ this.parent.emit(commandEvent, operands, unknown);
1534
+ } else if (operands.length) {
1535
+ if (this._findCommand("*")) {
1536
+ return this._dispatchSubcommand("*", operands, unknown);
1537
+ }
1538
+ if (this.listenerCount("command:*")) {
1539
+ this.emit("command:*", operands, unknown);
1540
+ } else if (this.commands.length) {
1541
+ this.unknownCommand();
1542
+ } else {
1543
+ checkForUnknownOptions();
1544
+ this._processArguments();
1545
+ }
1546
+ } else if (this.commands.length) {
1547
+ checkForUnknownOptions();
1548
+ this.help({ error: true });
1549
+ } else {
1550
+ checkForUnknownOptions();
1551
+ this._processArguments();
1552
+ }
1553
+ }
1554
+ _findCommand(name) {
1555
+ if (!name)
1556
+ return;
1557
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
1558
+ }
1559
+ _findOption(arg) {
1560
+ return this.options.find((option) => option.is(arg));
1561
+ }
1562
+ _checkForMissingMandatoryOptions() {
1563
+ this._getCommandAndAncestors().forEach((cmd) => {
1564
+ cmd.options.forEach((anOption) => {
1565
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
1566
+ cmd.missingMandatoryOptionValue(anOption);
1567
+ }
1568
+ });
1569
+ });
1570
+ }
1571
+ _checkForConflictingLocalOptions() {
1572
+ const definedNonDefaultOptions = this.options.filter((option) => {
1573
+ const optionKey = option.attributeName();
1574
+ if (this.getOptionValue(optionKey) === undefined) {
1575
+ return false;
1576
+ }
1577
+ return this.getOptionValueSource(optionKey) !== "default";
1578
+ });
1579
+ const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
1580
+ optionsWithConflicting.forEach((option) => {
1581
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
1582
+ if (conflictingAndDefined) {
1583
+ this._conflictingOption(option, conflictingAndDefined);
1584
+ }
1585
+ });
1586
+ }
1587
+ _checkForConflictingOptions() {
1588
+ this._getCommandAndAncestors().forEach((cmd) => {
1589
+ cmd._checkForConflictingLocalOptions();
1590
+ });
1591
+ }
1592
+ parseOptions(args) {
1593
+ const operands = [];
1594
+ const unknown = [];
1595
+ let dest = operands;
1596
+ function maybeOption(arg) {
1597
+ return arg.length > 1 && arg[0] === "-";
1598
+ }
1599
+ const negativeNumberArg = (arg) => {
1600
+ if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg))
1601
+ return false;
1602
+ return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
1603
+ };
1604
+ let activeVariadicOption = null;
1605
+ let activeGroup = null;
1606
+ let i = 0;
1607
+ while (i < args.length || activeGroup) {
1608
+ const arg = activeGroup ?? args[i++];
1609
+ activeGroup = null;
1610
+ if (arg === "--") {
1611
+ if (dest === unknown)
1612
+ dest.push(arg);
1613
+ dest.push(...args.slice(i));
1614
+ break;
1615
+ }
1616
+ if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
1617
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1618
+ continue;
1619
+ }
1620
+ activeVariadicOption = null;
1621
+ if (maybeOption(arg)) {
1622
+ const option = this._findOption(arg);
1623
+ if (option) {
1624
+ if (option.required) {
1625
+ const value = args[i++];
1626
+ if (value === undefined)
1627
+ this.optionMissingArgument(option);
1628
+ this.emit(`option:${option.name()}`, value);
1629
+ } else if (option.optional) {
1630
+ let value = null;
1631
+ if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
1632
+ value = args[i++];
1633
+ }
1634
+ this.emit(`option:${option.name()}`, value);
1635
+ } else {
1636
+ this.emit(`option:${option.name()}`);
1637
+ }
1638
+ activeVariadicOption = option.variadic ? option : null;
1639
+ continue;
1640
+ }
1641
+ }
1642
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
1643
+ const option = this._findOption(`-${arg[1]}`);
1644
+ if (option) {
1645
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
1646
+ this.emit(`option:${option.name()}`, arg.slice(2));
1647
+ } else {
1648
+ this.emit(`option:${option.name()}`);
1649
+ activeGroup = `-${arg.slice(2)}`;
1650
+ }
1651
+ continue;
1652
+ }
1653
+ }
1654
+ if (/^--[^=]+=/.test(arg)) {
1655
+ const index = arg.indexOf("=");
1656
+ const option = this._findOption(arg.slice(0, index));
1657
+ if (option && (option.required || option.optional)) {
1658
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1659
+ continue;
1660
+ }
1661
+ }
1662
+ if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
1663
+ dest = unknown;
1664
+ }
1665
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
1666
+ if (this._findCommand(arg)) {
1667
+ operands.push(arg);
1668
+ unknown.push(...args.slice(i));
1669
+ break;
1670
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
1671
+ operands.push(arg, ...args.slice(i));
1672
+ break;
1673
+ } else if (this._defaultCommandName) {
1674
+ unknown.push(arg, ...args.slice(i));
1675
+ break;
1676
+ }
1677
+ }
1678
+ if (this._passThroughOptions) {
1679
+ dest.push(arg, ...args.slice(i));
1680
+ break;
1681
+ }
1682
+ dest.push(arg);
1683
+ }
1684
+ return { operands, unknown };
1685
+ }
1686
+ opts() {
1687
+ if (this._storeOptionsAsProperties) {
1688
+ const result = {};
1689
+ const len = this.options.length;
1690
+ for (let i = 0;i < len; i++) {
1691
+ const key = this.options[i].attributeName();
1692
+ result[key] = key === this._versionOptionName ? this._version : this[key];
1693
+ }
1694
+ return result;
1695
+ }
1696
+ return this._optionValues;
1697
+ }
1698
+ optsWithGlobals() {
1699
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
1700
+ }
1701
+ error(message, errorOptions) {
1702
+ this._outputConfiguration.outputError(`${message}
1703
+ `, this._outputConfiguration.writeErr);
1704
+ if (typeof this._showHelpAfterError === "string") {
1705
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
1706
+ `);
1707
+ } else if (this._showHelpAfterError) {
1708
+ this._outputConfiguration.writeErr(`
1709
+ `);
1710
+ this.outputHelp({ error: true });
1711
+ }
1712
+ const config = errorOptions || {};
1713
+ const exitCode = config.exitCode || 1;
1714
+ const code = config.code || "commander.error";
1715
+ this._exit(exitCode, code, message);
1716
+ }
1717
+ _parseOptionsEnv() {
1718
+ this.options.forEach((option) => {
1719
+ if (option.envVar && option.envVar in process2.env) {
1720
+ const optionKey = option.attributeName();
1721
+ if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
1722
+ if (option.required || option.optional) {
1723
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
1724
+ } else {
1725
+ this.emit(`optionEnv:${option.name()}`);
1726
+ }
1727
+ }
1728
+ }
1729
+ });
1730
+ }
1731
+ _parseOptionsImplied() {
1732
+ const dualHelper = new DualOptions(this.options);
1733
+ const hasCustomOptionValue = (optionKey) => {
1734
+ return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
1735
+ };
1736
+ this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
1737
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
1738
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
1739
+ });
1740
+ });
1741
+ }
1742
+ missingArgument(name) {
1743
+ const message = `error: missing required argument '${name}'`;
1744
+ this.error(message, { code: "commander.missingArgument" });
1745
+ }
1746
+ optionMissingArgument(option) {
1747
+ const message = `error: option '${option.flags}' argument missing`;
1748
+ this.error(message, { code: "commander.optionMissingArgument" });
1749
+ }
1750
+ missingMandatoryOptionValue(option) {
1751
+ const message = `error: required option '${option.flags}' not specified`;
1752
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
1753
+ }
1754
+ _conflictingOption(option, conflictingOption) {
1755
+ const findBestOptionFromValue = (option2) => {
1756
+ const optionKey = option2.attributeName();
1757
+ const optionValue = this.getOptionValue(optionKey);
1758
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1759
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1760
+ if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1761
+ return negativeOption;
1762
+ }
1763
+ return positiveOption || option2;
1764
+ };
1765
+ const getErrorMessage = (option2) => {
1766
+ const bestOption = findBestOptionFromValue(option2);
1767
+ const optionKey = bestOption.attributeName();
1768
+ const source = this.getOptionValueSource(optionKey);
1769
+ if (source === "env") {
1770
+ return `environment variable '${bestOption.envVar}'`;
1771
+ }
1772
+ return `option '${bestOption.flags}'`;
1773
+ };
1774
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
1775
+ this.error(message, { code: "commander.conflictingOption" });
1776
+ }
1777
+ unknownOption(flag) {
1778
+ if (this._allowUnknownOption)
1779
+ return;
1780
+ let suggestion = "";
1781
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
1782
+ let candidateFlags = [];
1783
+ let command = this;
1784
+ do {
1785
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
1786
+ candidateFlags = candidateFlags.concat(moreFlags);
1787
+ command = command.parent;
1788
+ } while (command && !command._enablePositionalOptions);
1789
+ suggestion = suggestSimilar(flag, candidateFlags);
1790
+ }
1791
+ const message = `error: unknown option '${flag}'${suggestion}`;
1792
+ this.error(message, { code: "commander.unknownOption" });
1793
+ }
1794
+ _excessArguments(receivedArgs) {
1795
+ if (this._allowExcessArguments)
1796
+ return;
1797
+ const expected = this.registeredArguments.length;
1798
+ const s = expected === 1 ? "" : "s";
1799
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
1800
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
1801
+ this.error(message, { code: "commander.excessArguments" });
1802
+ }
1803
+ unknownCommand() {
1804
+ const unknownName = this.args[0];
1805
+ let suggestion = "";
1806
+ if (this._showSuggestionAfterError) {
1807
+ const candidateNames = [];
1808
+ this.createHelp().visibleCommands(this).forEach((command) => {
1809
+ candidateNames.push(command.name());
1810
+ if (command.alias())
1811
+ candidateNames.push(command.alias());
1812
+ });
1813
+ suggestion = suggestSimilar(unknownName, candidateNames);
1814
+ }
1815
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
1816
+ this.error(message, { code: "commander.unknownCommand" });
1817
+ }
1818
+ version(str, flags, description) {
1819
+ if (str === undefined)
1820
+ return this._version;
1821
+ this._version = str;
1822
+ flags = flags || "-V, --version";
1823
+ description = description || "output the version number";
1824
+ const versionOption = this.createOption(flags, description);
1825
+ this._versionOptionName = versionOption.attributeName();
1826
+ this._registerOption(versionOption);
1827
+ this.on("option:" + versionOption.name(), () => {
1828
+ this._outputConfiguration.writeOut(`${str}
1829
+ `);
1830
+ this._exit(0, "commander.version", str);
1831
+ });
1832
+ return this;
1833
+ }
1834
+ description(str, argsDescription) {
1835
+ if (str === undefined && argsDescription === undefined)
1836
+ return this._description;
1837
+ this._description = str;
1838
+ if (argsDescription) {
1839
+ this._argsDescription = argsDescription;
1840
+ }
1841
+ return this;
1842
+ }
1843
+ summary(str) {
1844
+ if (str === undefined)
1845
+ return this._summary;
1846
+ this._summary = str;
1847
+ return this;
1848
+ }
1849
+ alias(alias) {
1850
+ if (alias === undefined)
1851
+ return this._aliases[0];
1852
+ let command = this;
1853
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
1854
+ command = this.commands[this.commands.length - 1];
1855
+ }
1856
+ if (alias === command._name)
1857
+ throw new Error("Command alias can't be the same as its name");
1858
+ const matchingCommand = this.parent?._findCommand(alias);
1859
+ if (matchingCommand) {
1860
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
1861
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
1862
+ }
1863
+ command._aliases.push(alias);
1864
+ return this;
1865
+ }
1866
+ aliases(aliases) {
1867
+ if (aliases === undefined)
1868
+ return this._aliases;
1869
+ aliases.forEach((alias) => this.alias(alias));
1870
+ return this;
1871
+ }
1872
+ usage(str) {
1873
+ if (str === undefined) {
1874
+ if (this._usage)
1875
+ return this._usage;
1876
+ const args = this.registeredArguments.map((arg) => {
1877
+ return humanReadableArgName(arg);
1878
+ });
1879
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
1880
+ }
1881
+ this._usage = str;
1882
+ return this;
1883
+ }
1884
+ name(str) {
1885
+ if (str === undefined)
1886
+ return this._name;
1887
+ this._name = str;
1888
+ return this;
1889
+ }
1890
+ helpGroup(heading) {
1891
+ if (heading === undefined)
1892
+ return this._helpGroupHeading ?? "";
1893
+ this._helpGroupHeading = heading;
1894
+ return this;
1895
+ }
1896
+ commandsGroup(heading) {
1897
+ if (heading === undefined)
1898
+ return this._defaultCommandGroup ?? "";
1899
+ this._defaultCommandGroup = heading;
1900
+ return this;
1901
+ }
1902
+ optionsGroup(heading) {
1903
+ if (heading === undefined)
1904
+ return this._defaultOptionGroup ?? "";
1905
+ this._defaultOptionGroup = heading;
1906
+ return this;
1907
+ }
1908
+ _initOptionGroup(option) {
1909
+ if (this._defaultOptionGroup && !option.helpGroupHeading)
1910
+ option.helpGroup(this._defaultOptionGroup);
1911
+ }
1912
+ _initCommandGroup(cmd) {
1913
+ if (this._defaultCommandGroup && !cmd.helpGroup())
1914
+ cmd.helpGroup(this._defaultCommandGroup);
1915
+ }
1916
+ nameFromFilename(filename) {
1917
+ this._name = path.basename(filename, path.extname(filename));
1918
+ return this;
1919
+ }
1920
+ executableDir(path2) {
1921
+ if (path2 === undefined)
1922
+ return this._executableDir;
1923
+ this._executableDir = path2;
1924
+ return this;
1925
+ }
1926
+ helpInformation(contextOptions) {
1927
+ const helper = this.createHelp();
1928
+ const context = this._getOutputContext(contextOptions);
1929
+ helper.prepareContext({
1930
+ error: context.error,
1931
+ helpWidth: context.helpWidth,
1932
+ outputHasColors: context.hasColors
1933
+ });
1934
+ const text = helper.formatHelp(this, helper);
1935
+ if (context.hasColors)
1936
+ return text;
1937
+ return this._outputConfiguration.stripColor(text);
1938
+ }
1939
+ _getOutputContext(contextOptions) {
1940
+ contextOptions = contextOptions || {};
1941
+ const error = !!contextOptions.error;
1942
+ let baseWrite;
1943
+ let hasColors;
1944
+ let helpWidth;
1945
+ if (error) {
1946
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
1947
+ hasColors = this._outputConfiguration.getErrHasColors();
1948
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
1949
+ } else {
1950
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
1951
+ hasColors = this._outputConfiguration.getOutHasColors();
1952
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
1953
+ }
1954
+ const write = (str) => {
1955
+ if (!hasColors)
1956
+ str = this._outputConfiguration.stripColor(str);
1957
+ return baseWrite(str);
1958
+ };
1959
+ return { error, write, hasColors, helpWidth };
1960
+ }
1961
+ outputHelp(contextOptions) {
1962
+ let deprecatedCallback;
1963
+ if (typeof contextOptions === "function") {
1964
+ deprecatedCallback = contextOptions;
1965
+ contextOptions = undefined;
1966
+ }
1967
+ const outputContext = this._getOutputContext(contextOptions);
1968
+ const eventContext = {
1969
+ error: outputContext.error,
1970
+ write: outputContext.write,
1971
+ command: this
1972
+ };
1973
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
1974
+ this.emit("beforeHelp", eventContext);
1975
+ let helpInformation = this.helpInformation({ error: outputContext.error });
1976
+ if (deprecatedCallback) {
1977
+ helpInformation = deprecatedCallback(helpInformation);
1978
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
1979
+ throw new Error("outputHelp callback must return a string or a Buffer");
1980
+ }
1981
+ }
1982
+ outputContext.write(helpInformation);
1983
+ if (this._getHelpOption()?.long) {
1984
+ this.emit(this._getHelpOption().long);
1985
+ }
1986
+ this.emit("afterHelp", eventContext);
1987
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
1988
+ }
1989
+ helpOption(flags, description) {
1990
+ if (typeof flags === "boolean") {
1991
+ if (flags) {
1992
+ if (this._helpOption === null)
1993
+ this._helpOption = undefined;
1994
+ if (this._defaultOptionGroup) {
1995
+ this._initOptionGroup(this._getHelpOption());
1996
+ }
1997
+ } else {
1998
+ this._helpOption = null;
1999
+ }
2000
+ return this;
2001
+ }
2002
+ this._helpOption = this.createOption(flags ?? "-h, --help", description ?? "display help for command");
2003
+ if (flags || description)
2004
+ this._initOptionGroup(this._helpOption);
2005
+ return this;
2006
+ }
2007
+ _getHelpOption() {
2008
+ if (this._helpOption === undefined) {
2009
+ this.helpOption(undefined, undefined);
2010
+ }
2011
+ return this._helpOption;
2012
+ }
2013
+ addHelpOption(option) {
2014
+ this._helpOption = option;
2015
+ this._initOptionGroup(option);
2016
+ return this;
2017
+ }
2018
+ help(contextOptions) {
2019
+ this.outputHelp(contextOptions);
2020
+ let exitCode = Number(process2.exitCode ?? 0);
2021
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
2022
+ exitCode = 1;
2023
+ }
2024
+ this._exit(exitCode, "commander.help", "(outputHelp)");
2025
+ }
2026
+ addHelpText(position, text) {
2027
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
2028
+ if (!allowedValues.includes(position)) {
2029
+ throw new Error(`Unexpected value for position to addHelpText.
2030
+ Expecting one of '${allowedValues.join("', '")}'`);
2031
+ }
2032
+ const helpEvent = `${position}Help`;
2033
+ this.on(helpEvent, (context) => {
2034
+ let helpStr;
2035
+ if (typeof text === "function") {
2036
+ helpStr = text({ error: context.error, command: context.command });
2037
+ } else {
2038
+ helpStr = text;
2039
+ }
2040
+ if (helpStr) {
2041
+ context.write(`${helpStr}
2042
+ `);
2043
+ }
2044
+ });
2045
+ return this;
2046
+ }
2047
+ _outputHelpIfRequested(args) {
2048
+ const helpOption = this._getHelpOption();
2049
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2050
+ if (helpRequested) {
2051
+ this.outputHelp();
2052
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2053
+ }
2054
+ }
2055
+ }
2056
+ function incrementNodeInspectorPort(args) {
2057
+ return args.map((arg) => {
2058
+ if (!arg.startsWith("--inspect")) {
2059
+ return arg;
2060
+ }
2061
+ let debugOption;
2062
+ let debugHost = "127.0.0.1";
2063
+ let debugPort = "9229";
2064
+ let match;
2065
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2066
+ debugOption = match[1];
2067
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2068
+ debugOption = match[1];
2069
+ if (/^\d+$/.test(match[3])) {
2070
+ debugPort = match[3];
2071
+ } else {
2072
+ debugHost = match[3];
2073
+ }
2074
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2075
+ debugOption = match[1];
2076
+ debugHost = match[3];
2077
+ debugPort = match[4];
2078
+ }
2079
+ if (debugOption && debugPort !== "0") {
2080
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2081
+ }
2082
+ return arg;
2083
+ });
2084
+ }
2085
+ function useColor() {
2086
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
2087
+ return false;
2088
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== undefined)
2089
+ return true;
2090
+ return;
2091
+ }
2092
+ exports.Command = Command;
2093
+ exports.useColor = useColor;
2094
+ });
2095
+
2096
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/index.js
2097
+ var require_commander = __commonJS((exports) => {
2098
+ var { Argument } = require_argument();
2099
+ var { Command } = require_command();
2100
+ var { CommanderError, InvalidArgumentError } = require_error();
2101
+ var { Help } = require_help();
2102
+ var { Option } = require_option();
2103
+ exports.program = new Command;
2104
+ exports.createCommand = (name) => new Command(name);
2105
+ exports.createOption = (flags, description) => new Option(flags, description);
2106
+ exports.createArgument = (name, description) => new Argument(name, description);
2107
+ exports.Command = Command;
2108
+ exports.Option = Option;
2109
+ exports.Argument = Argument;
2110
+ exports.Help = Help;
2111
+ exports.CommanderError = CommanderError;
2112
+ exports.InvalidArgumentError = InvalidArgumentError;
2113
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
2114
+ });
2115
+
2116
+ // ../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js
2117
+ var require_picocolors = __commonJS((exports, module) => {
2118
+ var p = process || {};
2119
+ var argv = p.argv || [];
2120
+ var env = p.env || {};
2121
+ var isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
2122
+ var formatter = (open, close, replace = open) => (input) => {
2123
+ let string = "" + input, index = string.indexOf(close, open.length);
2124
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
2125
+ };
2126
+ var replaceClose = (string, close, replace, index) => {
2127
+ let result = "", cursor = 0;
2128
+ do {
2129
+ result += string.substring(cursor, index) + replace;
2130
+ cursor = index + close.length;
2131
+ index = string.indexOf(close, cursor);
2132
+ } while (~index);
2133
+ return result + string.substring(cursor);
2134
+ };
2135
+ var createColors = (enabled = isColorSupported) => {
2136
+ let f = enabled ? formatter : () => String;
2137
+ return {
2138
+ isColorSupported: enabled,
2139
+ reset: f("\x1B[0m", "\x1B[0m"),
2140
+ bold: f("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
2141
+ dim: f("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
2142
+ italic: f("\x1B[3m", "\x1B[23m"),
2143
+ underline: f("\x1B[4m", "\x1B[24m"),
2144
+ inverse: f("\x1B[7m", "\x1B[27m"),
2145
+ hidden: f("\x1B[8m", "\x1B[28m"),
2146
+ strikethrough: f("\x1B[9m", "\x1B[29m"),
2147
+ black: f("\x1B[30m", "\x1B[39m"),
2148
+ red: f("\x1B[31m", "\x1B[39m"),
2149
+ green: f("\x1B[32m", "\x1B[39m"),
2150
+ yellow: f("\x1B[33m", "\x1B[39m"),
2151
+ blue: f("\x1B[34m", "\x1B[39m"),
2152
+ magenta: f("\x1B[35m", "\x1B[39m"),
2153
+ cyan: f("\x1B[36m", "\x1B[39m"),
2154
+ white: f("\x1B[37m", "\x1B[39m"),
2155
+ gray: f("\x1B[90m", "\x1B[39m"),
2156
+ bgBlack: f("\x1B[40m", "\x1B[49m"),
2157
+ bgRed: f("\x1B[41m", "\x1B[49m"),
2158
+ bgGreen: f("\x1B[42m", "\x1B[49m"),
2159
+ bgYellow: f("\x1B[43m", "\x1B[49m"),
2160
+ bgBlue: f("\x1B[44m", "\x1B[49m"),
2161
+ bgMagenta: f("\x1B[45m", "\x1B[49m"),
2162
+ bgCyan: f("\x1B[46m", "\x1B[49m"),
2163
+ bgWhite: f("\x1B[47m", "\x1B[49m"),
2164
+ blackBright: f("\x1B[90m", "\x1B[39m"),
2165
+ redBright: f("\x1B[91m", "\x1B[39m"),
2166
+ greenBright: f("\x1B[92m", "\x1B[39m"),
2167
+ yellowBright: f("\x1B[93m", "\x1B[39m"),
2168
+ blueBright: f("\x1B[94m", "\x1B[39m"),
2169
+ magentaBright: f("\x1B[95m", "\x1B[39m"),
2170
+ cyanBright: f("\x1B[96m", "\x1B[39m"),
2171
+ whiteBright: f("\x1B[97m", "\x1B[39m"),
2172
+ bgBlackBright: f("\x1B[100m", "\x1B[49m"),
2173
+ bgRedBright: f("\x1B[101m", "\x1B[49m"),
2174
+ bgGreenBright: f("\x1B[102m", "\x1B[49m"),
2175
+ bgYellowBright: f("\x1B[103m", "\x1B[49m"),
2176
+ bgBlueBright: f("\x1B[104m", "\x1B[49m"),
2177
+ bgMagentaBright: f("\x1B[105m", "\x1B[49m"),
2178
+ bgCyanBright: f("\x1B[106m", "\x1B[49m"),
2179
+ bgWhiteBright: f("\x1B[107m", "\x1B[49m")
2180
+ };
2181
+ };
2182
+ module.exports = createColors();
2183
+ module.exports.createColors = createColors;
2184
+ });
2185
+
2186
+ // ../../node_modules/.pnpm/commander@14.0.3/node_modules/commander/esm.mjs
2187
+ var import__ = __toESM(require_commander(), 1);
2188
+ var {
2189
+ program,
2190
+ createCommand,
2191
+ createArgument,
2192
+ createOption,
2193
+ CommanderError,
2194
+ InvalidArgumentError,
2195
+ InvalidOptionArgumentError,
2196
+ Command,
2197
+ Argument,
2198
+ Option,
2199
+ Help
2200
+ } = import__.default;
2201
+
2202
+ // ../../src/cli/config.ts
2203
+ import {
2204
+ chmodSync,
2205
+ existsSync,
2206
+ mkdirSync,
2207
+ readFileSync,
2208
+ unlinkSync,
2209
+ writeFileSync
2210
+ } from "fs";
2211
+ import { homedir } from "os";
2212
+ import { dirname, join } from "path";
2213
+
2214
+ // ../../src/lib/lumail-sdk/errors.ts
2215
+ class LumailError extends Error {
2216
+ status;
2217
+ code;
2218
+ constructor(message, status, code) {
2219
+ super(message);
2220
+ this.name = "LumailError";
2221
+ this.status = status;
2222
+ this.code = code;
2223
+ }
2224
+ }
2225
+
2226
+ class LumailAuthenticationError extends LumailError {
2227
+ constructor(message = "Invalid or missing API key") {
2228
+ super(message, 401, "AUTHENTICATION_ERROR");
2229
+ this.name = "LumailAuthenticationError";
2230
+ }
2231
+ }
2232
+
2233
+ class LumailRateLimitError extends LumailError {
2234
+ retryAfter;
2235
+ constructor(message = "Rate limit exceeded", retryAfter = null) {
2236
+ super(message, 429, "RATE_LIMIT_ERROR");
2237
+ this.name = "LumailRateLimitError";
2238
+ this.retryAfter = retryAfter;
2239
+ }
2240
+ }
2241
+
2242
+ class LumailValidationError extends LumailError {
2243
+ constructor(message) {
2244
+ super(message, 400, "VALIDATION_ERROR");
2245
+ this.name = "LumailValidationError";
2246
+ }
2247
+ }
2248
+
2249
+ class LumailNotFoundError extends LumailError {
2250
+ constructor(message = "Resource not found") {
2251
+ super(message, 404, "NOT_FOUND");
2252
+ this.name = "LumailNotFoundError";
2253
+ }
2254
+ }
2255
+
2256
+ class LumailPaymentRequiredError extends LumailError {
2257
+ constructor(message = "Plan limit reached") {
2258
+ super(message, 402, "PLAN_LIMIT_REACHED");
2259
+ this.name = "LumailPaymentRequiredError";
2260
+ }
2261
+ }
2262
+
2263
+ // ../../src/lib/lumail-sdk/client.ts
2264
+ var DEFAULT_BASE_URL = "https://lumail.io/api";
2265
+ var DEFAULT_TIMEOUT = 30000;
2266
+ var RETRY_DELAYS = [1000, 2000, 4000];
2267
+ var IDEMPOTENT_METHODS = new Set(["GET", "PUT", "DELETE"]);
2268
+
2269
+ class LumailClient {
2270
+ apiKey;
2271
+ baseUrl;
2272
+ constructor(apiKey, baseUrl) {
2273
+ if (!apiKey?.trim()) {
2274
+ throw new Error("Lumail API key is required. Get yours at lumail.io/settings");
2275
+ }
2276
+ this.apiKey = apiKey;
2277
+ this.baseUrl = (baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
2278
+ }
2279
+ async request(method, path, options) {
2280
+ const url = this.buildUrl(path, options?.params);
2281
+ const headers = {
2282
+ Authorization: `Bearer ${this.apiKey}`,
2283
+ "Content-Type": "application/json"
2284
+ };
2285
+ const isIdempotent = IDEMPOTENT_METHODS.has(method.toUpperCase());
2286
+ let lastError = null;
2287
+ const maxRetries = isIdempotent ? RETRY_DELAYS.length : 0;
2288
+ for (let attempt = 0;attempt <= maxRetries; attempt++) {
2289
+ try {
2290
+ const signal = options?.signal ?? AbortSignal.timeout(DEFAULT_TIMEOUT);
2291
+ const response = await fetch(url, {
2292
+ method,
2293
+ headers,
2294
+ body: options?.body ? JSON.stringify(options.body) : undefined,
2295
+ signal
2296
+ });
2297
+ if (response.ok) {
2298
+ const data = await response.json();
2299
+ if (data.success === false) {
2300
+ throw new LumailError(data.message ?? "Request failed", response.status, data.code);
2301
+ }
2302
+ return data;
2303
+ }
2304
+ if (response.status === 429 && isIdempotent && attempt < maxRetries) {
2305
+ await sleep(parseRetryAfter(response, RETRY_DELAYS[attempt]));
2306
+ continue;
2307
+ }
2308
+ throw await this.handleErrorResponse(response);
2309
+ } catch (error) {
2310
+ if (error instanceof LumailError) {
2311
+ throw error;
2312
+ }
2313
+ lastError = error;
2314
+ const isNetworkError = error instanceof TypeError || error.name === "AbortError";
2315
+ if (isNetworkError && isIdempotent && attempt < maxRetries) {
2316
+ await sleep(RETRY_DELAYS[attempt]);
2317
+ continue;
2318
+ }
2319
+ throw error;
2320
+ }
2321
+ }
2322
+ throw lastError ?? new LumailError("Request failed after retries", 500);
2323
+ }
2324
+ buildUrl(path, params) {
2325
+ const url = new URL(`${this.baseUrl}${path}`);
2326
+ if (params) {
2327
+ for (const [key, value] of Object.entries(params)) {
2328
+ if (value !== undefined) {
2329
+ url.searchParams.set(key, String(value));
2330
+ }
2331
+ }
2332
+ }
2333
+ return url.toString();
2334
+ }
2335
+ async handleErrorResponse(response) {
2336
+ let body = {};
2337
+ try {
2338
+ body = await response.json();
2339
+ } catch {
2340
+ }
2341
+ const message = body.message ?? body.error ?? response.statusText;
2342
+ const code = body.code;
2343
+ switch (response.status) {
2344
+ case 401:
2345
+ return new LumailAuthenticationError(message);
2346
+ case 402:
2347
+ return new LumailPaymentRequiredError(message);
2348
+ case 404:
2349
+ return new LumailNotFoundError(message);
2350
+ case 429: {
2351
+ const retryAfter = parseRetryAfter(response, null);
2352
+ return new LumailRateLimitError(message, retryAfter);
2353
+ }
2354
+ default:
2355
+ if (response.status >= 400 && response.status < 500) {
2356
+ return new LumailValidationError(message);
2357
+ }
2358
+ return new LumailError(message, response.status, code);
2359
+ }
2360
+ }
2361
+ }
2362
+ function parseRetryAfter(response, fallback) {
2363
+ const header = response.headers.get("Retry-After");
2364
+ if (!header)
2365
+ return fallback;
2366
+ const seconds = Number(header);
2367
+ if (!Number.isNaN(seconds))
2368
+ return seconds * 1000;
2369
+ const date = new Date(header).getTime();
2370
+ if (!Number.isNaN(date))
2371
+ return Math.max(0, date - Date.now());
2372
+ return fallback;
2373
+ }
2374
+ async function sleep(ms) {
2375
+ if (ms === null || ms <= 0)
2376
+ return;
2377
+ return new Promise((resolve) => setTimeout(resolve, ms));
2378
+ }
2379
+
2380
+ // ../../src/lib/lumail-sdk/resources/campaigns.ts
2381
+ class Campaigns {
2382
+ client;
2383
+ constructor(client) {
2384
+ this.client = client;
2385
+ }
2386
+ async list(params) {
2387
+ return this.client.request("GET", "/v1/campaigns", {
2388
+ params
2389
+ });
2390
+ }
2391
+ async create(params) {
2392
+ return this.client.request("POST", "/v1/campaigns", {
2393
+ body: params
2394
+ });
2395
+ }
2396
+ async get(campaignId) {
2397
+ return this.client.request("GET", `/v1/campaigns/${encodeURIComponent(campaignId)}`);
2398
+ }
2399
+ async update(campaignId, params) {
2400
+ return this.client.request("PATCH", `/v1/campaigns/${encodeURIComponent(campaignId)}`, { body: params });
2401
+ }
2402
+ async delete(campaignId) {
2403
+ return this.client.request("DELETE", `/v1/campaigns/${encodeURIComponent(campaignId)}`);
2404
+ }
2405
+ async send(campaignId, params) {
2406
+ return this.client.request("POST", `/v1/campaigns/${encodeURIComponent(campaignId)}/send`, { body: params ?? {} });
2407
+ }
2408
+ }
2409
+
2410
+ // ../../src/lib/lumail-sdk/resources/emails.ts
2411
+ class Emails {
2412
+ client;
2413
+ constructor(client) {
2414
+ this.client = client;
2415
+ }
2416
+ async send(params) {
2417
+ return this.client.request("POST", "/v1/emails", {
2418
+ body: params
2419
+ });
2420
+ }
2421
+ async verify(params) {
2422
+ return this.client.request("POST", "/v1/emails/verify", {
2423
+ body: params
2424
+ });
2425
+ }
2426
+ }
2427
+
2428
+ // ../../src/lib/lumail-sdk/resources/events.ts
2429
+ class Events {
2430
+ client;
2431
+ constructor(client) {
2432
+ this.client = client;
2433
+ }
2434
+ async create(params) {
2435
+ return this.client.request("POST", "/v1/events", {
2436
+ body: params
2437
+ });
2438
+ }
2439
+ }
2440
+
2441
+ // ../../src/lib/lumail-sdk/resources/subscribers.ts
2442
+ class Subscribers {
2443
+ client;
2444
+ constructor(client) {
2445
+ this.client = client;
2446
+ }
2447
+ async create(params) {
2448
+ return this.client.request("POST", "/v1/subscribers", {
2449
+ body: params
2450
+ });
2451
+ }
2452
+ async get(idOrEmail) {
2453
+ return this.client.request("GET", `/v1/subscribers/${encodeURIComponent(idOrEmail)}`);
2454
+ }
2455
+ async update(idOrEmail, params) {
2456
+ return this.client.request("PATCH", `/v1/subscribers/${encodeURIComponent(idOrEmail)}`, { body: params });
2457
+ }
2458
+ async delete(idOrEmail) {
2459
+ return this.client.request("DELETE", `/v1/subscribers/${encodeURIComponent(idOrEmail)}`);
2460
+ }
2461
+ async unsubscribe(idOrEmail) {
2462
+ return this.client.request("POST", `/v1/subscribers/${encodeURIComponent(idOrEmail)}/unsubscribe`);
2463
+ }
2464
+ async addTags(idOrEmail, tags) {
2465
+ return this.client.request("POST", `/v1/subscribers/${encodeURIComponent(idOrEmail)}/tags`, { body: { tags } });
2466
+ }
2467
+ async removeTags(idOrEmail, tags) {
2468
+ return this.client.request("DELETE", `/v1/subscribers/${encodeURIComponent(idOrEmail)}/tags`, { params: { tags: JSON.stringify(tags) } });
2469
+ }
2470
+ async listEvents(idOrEmail, params) {
2471
+ return this.client.request("GET", `/v1/subscribers/${encodeURIComponent(idOrEmail)}/events`, {
2472
+ params: {
2473
+ ...params,
2474
+ eventTypes: params?.eventTypes ? JSON.stringify(params.eventTypes) : undefined
2475
+ }
2476
+ });
2477
+ }
2478
+ }
2479
+
2480
+ // ../../src/lib/lumail-sdk/resources/tags.ts
2481
+ class Tags {
2482
+ client;
2483
+ constructor(client) {
2484
+ this.client = client;
2485
+ }
2486
+ async list() {
2487
+ return this.client.request("GET", "/v1/tags");
2488
+ }
2489
+ async create(params) {
2490
+ return this.client.request("POST", "/v1/tags", {
2491
+ body: params
2492
+ });
2493
+ }
2494
+ async get(idOrName) {
2495
+ return this.client.request("GET", `/v1/tags/${encodeURIComponent(idOrName)}`);
2496
+ }
2497
+ async update(idOrName, params) {
2498
+ return this.client.request("PATCH", `/v1/tags/${encodeURIComponent(idOrName)}`, { body: params });
2499
+ }
2500
+ }
2501
+
2502
+ // ../../src/lib/lumail-sdk/resources/tools.ts
2503
+ class Tools {
2504
+ client;
2505
+ constructor(client) {
2506
+ this.client = client;
2507
+ }
2508
+ async list() {
2509
+ return this.client.request("GET", "/v2/tools");
2510
+ }
2511
+ async get(toolName) {
2512
+ return this.client.request("GET", `/v2/tools/${encodeURIComponent(toolName)}`);
2513
+ }
2514
+ async run(toolName, params) {
2515
+ return this.client.request("POST", `/v2/tools/${encodeURIComponent(toolName)}`, { body: params ?? {} });
2516
+ }
2517
+ }
2518
+
2519
+ // ../../src/lib/lumail-sdk/index.ts
2520
+ class Lumail {
2521
+ subscribers;
2522
+ campaigns;
2523
+ emails;
2524
+ tags;
2525
+ events;
2526
+ tools;
2527
+ constructor(options) {
2528
+ const client = new LumailClient(options.apiKey, options.baseUrl);
2529
+ this.subscribers = new Subscribers(client);
2530
+ this.campaigns = new Campaigns(client);
2531
+ this.emails = new Emails(client);
2532
+ this.tags = new Tags(client);
2533
+ this.events = new Events(client);
2534
+ this.tools = new Tools(client);
2535
+ }
2536
+ }
2537
+
2538
+ // ../../src/cli/config.ts
2539
+ var TOKEN_PATH = join(homedir(), ".config", "lumail", "token");
2540
+ var DEFAULT_BASE_URL2 = "https://lumail.io/api";
2541
+ function hasToken() {
2542
+ return existsSync(TOKEN_PATH);
2543
+ }
2544
+ function getToken() {
2545
+ if (!hasToken()) {
2546
+ console.error("No API key configured. Run: pnpm lumail auth set <token>");
2547
+ process.exit(2);
2548
+ }
2549
+ return readFileSync(TOKEN_PATH, "utf-8").trim();
2550
+ }
2551
+ function setToken(token) {
2552
+ mkdirSync(dirname(TOKEN_PATH), { recursive: true });
2553
+ writeFileSync(TOKEN_PATH, token.trim(), { mode: 384 });
2554
+ chmodSync(TOKEN_PATH, 384);
2555
+ }
2556
+ function removeToken() {
2557
+ if (existsSync(TOKEN_PATH)) {
2558
+ unlinkSync(TOKEN_PATH);
2559
+ }
2560
+ }
2561
+ function maskToken(token) {
2562
+ if (token.length <= 8)
2563
+ return "****";
2564
+ return `${token.slice(0, 4)}...${token.slice(-4)}`;
2565
+ }
2566
+ function getLumail() {
2567
+ return new Lumail({
2568
+ apiKey: getToken(),
2569
+ baseUrl: process.env.LUMAIL_API_URL ?? DEFAULT_BASE_URL2
2570
+ });
2571
+ }
2572
+ var globalFlags = {
2573
+ json: false,
2574
+ format: "text",
2575
+ verbose: false,
2576
+ noColor: false,
2577
+ noHeader: false
2578
+ };
2579
+
2580
+ // ../../src/cli/commands/auth.ts
2581
+ var import_picocolors2 = __toESM(require_picocolors(), 1);
2582
+
2583
+ // ../../src/cli/output.ts
2584
+ var import_picocolors = __toESM(require_picocolors(), 1);
2585
+ function output(data) {
2586
+ const format = globalFlags.json ? "json" : globalFlags.format;
2587
+ switch (format) {
2588
+ case "json":
2589
+ printJson(data);
2590
+ break;
2591
+ case "csv":
2592
+ printCsv(data);
2593
+ break;
2594
+ default:
2595
+ printText(data);
2596
+ }
2597
+ }
2598
+ function unwrap(data) {
2599
+ if (typeof data === "object" && data !== null && "success" in data) {
2600
+ const { success: _, ...rest } = data;
2601
+ if ("data" in rest && Object.keys(rest).length === 1)
2602
+ return rest.data;
2603
+ return rest;
2604
+ }
2605
+ return data;
2606
+ }
2607
+ function printJson(data) {
2608
+ const unwrapped = unwrap(data);
2609
+ const envelope = { ok: true, data: unwrapped };
2610
+ if (Array.isArray(unwrapped))
2611
+ envelope.meta = { total: unwrapped.length };
2612
+ console.log(JSON.stringify(envelope, null, 2));
2613
+ }
2614
+ function printText(data) {
2615
+ const unwrapped = unwrap(data);
2616
+ if (Array.isArray(unwrapped)) {
2617
+ if (unwrapped.length === 0) {
2618
+ console.log(import_picocolors.default.dim("(no results)"));
2619
+ return;
2620
+ }
2621
+ printTable(unwrapped);
2622
+ console.log(import_picocolors.default.dim(`
2623
+ ${unwrapped.length} result${unwrapped.length === 1 ? "" : "s"}`));
2624
+ } else if (typeof unwrapped === "object" && unwrapped !== null) {
2625
+ printKeyValue(unwrapped);
2626
+ } else {
2627
+ console.log(String(unwrapped));
2628
+ }
2629
+ }
2630
+ function printKeyValue(obj) {
2631
+ const maxKey = Math.max(...Object.keys(obj).map((k) => k.length));
2632
+ for (const [k, v] of Object.entries(obj)) {
2633
+ console.log(` ${import_picocolors.default.bold(k.padEnd(maxKey))} ${fmtVal(v)}`);
2634
+ }
2635
+ }
2636
+ function fmtVal(v) {
2637
+ if (v === null || v === undefined)
2638
+ return import_picocolors.default.dim("-");
2639
+ if (typeof v === "boolean")
2640
+ return v ? import_picocolors.default.green("true") : import_picocolors.default.red("false");
2641
+ if (typeof v === "number")
2642
+ return import_picocolors.default.cyan(String(v));
2643
+ if (typeof v === "object")
2644
+ return import_picocolors.default.dim(JSON.stringify(v));
2645
+ const s = String(v);
2646
+ if (/^\d{4}-\d{2}-\d{2}/.test(s))
2647
+ return import_picocolors.default.dim(s);
2648
+ if (/^https?:\/\//.test(s))
2649
+ return import_picocolors.default.underline(import_picocolors.default.cyan(s));
2650
+ return s;
2651
+ }
2652
+ function fmtCell(v) {
2653
+ if (v === null || v === undefined)
2654
+ return import_picocolors.default.dim("-");
2655
+ if (typeof v === "boolean")
2656
+ return v ? import_picocolors.default.green("yes") : import_picocolors.default.red("no");
2657
+ if (typeof v === "number")
2658
+ return import_picocolors.default.cyan(String(v));
2659
+ if (typeof v === "object")
2660
+ return import_picocolors.default.dim(JSON.stringify(v));
2661
+ const s = String(v);
2662
+ if (/^\d{4}-\d{2}-\d{2}T/.test(s))
2663
+ return import_picocolors.default.dim(s.replace("T", " ").replace(/\.\d+Z$/, "Z"));
2664
+ return s;
2665
+ }
2666
+ function stripAnsi(s) {
2667
+ return s.replace(/\x1b\[[0-9;]*m/g, "");
2668
+ }
2669
+ function printTable(rows) {
2670
+ const cols = Object.keys(rows[0] ?? {});
2671
+ const widths = cols.map((col) => {
2672
+ const values = rows.map((r) => stripAnsi(fmtCell(r[col])).length);
2673
+ return Math.min(Math.max(col.length, ...values), 40);
2674
+ });
2675
+ if (!globalFlags.noHeader) {
2676
+ console.log(cols.map((c, i) => import_picocolors.default.bold(import_picocolors.default.white(c.padEnd(widths[i])))).join(" "));
2677
+ console.log(import_picocolors.default.dim(widths.map((w) => "-".repeat(w)).join(" ")));
2678
+ }
2679
+ for (const row of rows) {
2680
+ const line = cols.map((c, i) => {
2681
+ const formatted = fmtCell(row[c]);
2682
+ const raw = stripAnsi(formatted);
2683
+ const w = widths[i];
2684
+ if (raw.length > w)
2685
+ return formatted.slice(0, formatted.length - (raw.length - w) - 1) + import_picocolors.default.dim("...");
2686
+ return formatted + " ".repeat(Math.max(0, w - raw.length));
2687
+ });
2688
+ console.log(line.join(" "));
2689
+ }
2690
+ }
2691
+ function printCsv(data) {
2692
+ const unwrapped = unwrap(data);
2693
+ if (!Array.isArray(unwrapped) || unwrapped.length === 0) {
2694
+ console.log(JSON.stringify(unwrapped));
2695
+ return;
2696
+ }
2697
+ const cols = Object.keys(unwrapped[0] ?? {});
2698
+ if (!globalFlags.noHeader)
2699
+ console.log(cols.join(","));
2700
+ for (const row of unwrapped) {
2701
+ console.log(cols.map((c) => csvEscape(String(row[c] ?? ""))).join(","));
2702
+ }
2703
+ }
2704
+ function csvEscape(val) {
2705
+ if (val.includes(",") || val.includes('"') || val.includes(`
2706
+ `))
2707
+ return `"${val.replace(/"/g, '""')}"`;
2708
+ return val;
2709
+ }
2710
+ function handleError(error) {
2711
+ if (globalFlags.json) {
2712
+ console.log(JSON.stringify({
2713
+ ok: false,
2714
+ error: {
2715
+ message: error instanceof Error ? error.message : String(error)
2716
+ }
2717
+ }));
2718
+ } else {
2719
+ console.error(import_picocolors.default.red("Error:"), error instanceof Error ? error.message : String(error));
2720
+ }
2721
+ process.exit(1);
2722
+ }
2723
+
2724
+ // ../../src/cli/commands/auth.ts
2725
+ var authCommand = new Command("auth").description("Manage API key authentication");
2726
+ authCommand.command("set <token>").description("Save your API key").action((token) => {
2727
+ setToken(token);
2728
+ console.log(import_picocolors2.default.green("API key saved successfully."));
2729
+ });
2730
+ authCommand.command("show").description("Display saved API key").option("--raw", "Show full unmasked token").action((opts) => {
2731
+ const token = getToken();
2732
+ console.log(opts.raw ? token : maskToken(token));
2733
+ });
2734
+ authCommand.command("remove").description("Delete saved API key").action(() => {
2735
+ removeToken();
2736
+ console.log(import_picocolors2.default.green("API key removed."));
2737
+ });
2738
+ authCommand.command("test").description("Verify API key is valid").action(async () => {
2739
+ if (!hasToken()) {
2740
+ console.error("No API key configured. Run: pnpm lumail auth set <token>");
2741
+ process.exit(2);
2742
+ }
2743
+ try {
2744
+ const lumail = getLumail();
2745
+ const result = await lumail.tags.list();
2746
+ output(result);
2747
+ console.log(import_picocolors2.default.green(`
2748
+ API key is valid.`));
2749
+ } catch (error) {
2750
+ handleError(error);
2751
+ }
2752
+ });
2753
+
2754
+ // ../../src/cli/commands/subscribers.ts
2755
+ var subscribersCommand = new Command("subscribers").description("Manage subscribers");
2756
+ subscribersCommand.command("create").description("Create or update a subscriber").requiredOption("--email <email>", "Email address").option("--name <name>", "Subscriber name").option("--tags <tags...>", "Tags to add").action(async (opts) => {
2757
+ try {
2758
+ const lumail = getLumail();
2759
+ const result = await lumail.subscribers.create({
2760
+ email: opts.email,
2761
+ name: opts.name,
2762
+ tags: opts.tags
2763
+ });
2764
+ output(result);
2765
+ } catch (error) {
2766
+ handleError(error);
2767
+ }
2768
+ });
2769
+ subscribersCommand.command("get <idOrEmail>").description("Get subscriber by ID or email").action(async (idOrEmail) => {
2770
+ try {
2771
+ const lumail = getLumail();
2772
+ const result = await lumail.subscribers.get(idOrEmail);
2773
+ output(result);
2774
+ } catch (error) {
2775
+ handleError(error);
2776
+ }
2777
+ });
2778
+ subscribersCommand.command("update <idOrEmail>").description("Update a subscriber").option("--name <name>", "New name").option("--tags <tags...>", "Tags to set").option("--replace-tags", "Replace all tags instead of appending").action(async (idOrEmail, opts) => {
2779
+ try {
2780
+ const lumail = getLumail();
2781
+ const result = await lumail.subscribers.update(idOrEmail, {
2782
+ name: opts.name,
2783
+ tags: opts.tags,
2784
+ replaceTags: opts.replaceTags
2785
+ });
2786
+ output(result);
2787
+ } catch (error) {
2788
+ handleError(error);
2789
+ }
2790
+ });
2791
+ subscribersCommand.command("delete <idOrEmail>").description("Delete a subscriber").action(async (idOrEmail) => {
2792
+ try {
2793
+ const lumail = getLumail();
2794
+ const result = await lumail.subscribers.delete(idOrEmail);
2795
+ output(result);
2796
+ } catch (error) {
2797
+ handleError(error);
2798
+ }
2799
+ });
2800
+ subscribersCommand.command("unsubscribe <idOrEmail>").description("Unsubscribe a subscriber").action(async (idOrEmail) => {
2801
+ try {
2802
+ const lumail = getLumail();
2803
+ const result = await lumail.subscribers.unsubscribe(idOrEmail);
2804
+ output(result);
2805
+ } catch (error) {
2806
+ handleError(error);
2807
+ }
2808
+ });
2809
+ subscribersCommand.command("add-tags <idOrEmail>").description("Add tags to a subscriber").requiredOption("--tags <tags...>", "Tags to add").action(async (idOrEmail, opts) => {
2810
+ try {
2811
+ const lumail = getLumail();
2812
+ const result = await lumail.subscribers.addTags(idOrEmail, opts.tags);
2813
+ output(result);
2814
+ } catch (error) {
2815
+ handleError(error);
2816
+ }
2817
+ });
2818
+ subscribersCommand.command("remove-tags <idOrEmail>").description("Remove tags from a subscriber").requiredOption("--tags <tags...>", "Tags to remove").action(async (idOrEmail, opts) => {
2819
+ try {
2820
+ const lumail = getLumail();
2821
+ const result = await lumail.subscribers.removeTags(idOrEmail, opts.tags);
2822
+ output(result);
2823
+ } catch (error) {
2824
+ handleError(error);
2825
+ }
2826
+ });
2827
+ subscribersCommand.command("events <idOrEmail>").description("List subscriber events").option("--take <n>", "Number of events", "20").option("--order <order>", "Sort order: asc or desc", "desc").action(async (idOrEmail, opts) => {
2828
+ try {
2829
+ const lumail = getLumail();
2830
+ const result = await lumail.subscribers.listEvents(idOrEmail, {
2831
+ take: Number(opts.take),
2832
+ order: opts.order
2833
+ });
2834
+ output(result);
2835
+ } catch (error) {
2836
+ handleError(error);
2837
+ }
2838
+ });
2839
+
2840
+ // ../../src/cli/commands/campaigns.ts
2841
+ var campaignsCommand = new Command("campaigns").description("Manage campaigns");
2842
+ campaignsCommand.command("list").description("List campaigns").option("--status <status>", "Filter: all, DRAFT, ARCHIVED, SCHEDULED, SENT", "all").option("--page <n>", "Page number", "1").option("--limit <n>", "Results per page", "20").option("--query <q>", "Search by name or subject").action(async (opts) => {
2843
+ try {
2844
+ const lumail = getLumail();
2845
+ const result = await lumail.campaigns.list({
2846
+ status: opts.status,
2847
+ page: Number(opts.page),
2848
+ limit: Number(opts.limit),
2849
+ query: opts.query
2850
+ });
2851
+ output(result);
2852
+ } catch (error) {
2853
+ handleError(error);
2854
+ }
2855
+ });
2856
+ campaignsCommand.command("create").description("Create a new campaign").requiredOption("--subject <subject>", "Email subject").option("--name <name>", "Campaign name").option("--preview <text>", "Preview text").action(async (opts) => {
2857
+ try {
2858
+ const lumail = getLumail();
2859
+ const result = await lumail.campaigns.create({
2860
+ subject: opts.subject,
2861
+ name: opts.name,
2862
+ preview: opts.preview
2863
+ });
2864
+ output(result);
2865
+ } catch (error) {
2866
+ handleError(error);
2867
+ }
2868
+ });
2869
+ campaignsCommand.command("get <id>").description("Get campaign details").action(async (id) => {
2870
+ try {
2871
+ const lumail = getLumail();
2872
+ const result = await lumail.campaigns.get(id);
2873
+ output(result);
2874
+ } catch (error) {
2875
+ handleError(error);
2876
+ }
2877
+ });
2878
+ campaignsCommand.command("update <id>").description("Update a draft campaign").option("--subject <subject>", "New subject").option("--name <name>", "New name").option("--preview <text>", "New preview text").action(async (id, opts) => {
2879
+ try {
2880
+ const lumail = getLumail();
2881
+ const result = await lumail.campaigns.update(id, {
2882
+ subject: opts.subject,
2883
+ name: opts.name,
2884
+ preview: opts.preview
2885
+ });
2886
+ output(result);
2887
+ } catch (error) {
2888
+ handleError(error);
2889
+ }
2890
+ });
2891
+ campaignsCommand.command("delete <id>").description("Delete a draft campaign").action(async (id) => {
2892
+ try {
2893
+ const lumail = getLumail();
2894
+ const result = await lumail.campaigns.delete(id);
2895
+ output(result);
2896
+ } catch (error) {
2897
+ handleError(error);
2898
+ }
2899
+ });
2900
+ campaignsCommand.command("send <id>").description("Send or schedule a campaign").option("--scheduled-at <datetime>", "ISO 8601 datetime to schedule").option("--timezone <tz>", "Timezone", "UTC").action(async (id, opts) => {
2901
+ try {
2902
+ const lumail = getLumail();
2903
+ const result = await lumail.campaigns.send(id, {
2904
+ scheduledAt: opts.scheduledAt,
2905
+ timezone: opts.timezone
2906
+ });
2907
+ output(result);
2908
+ } catch (error) {
2909
+ handleError(error);
2910
+ }
2911
+ });
2912
+
2913
+ // ../../src/cli/commands/tags.ts
2914
+ var tagsCommand = new Command("tags").description("Manage tags");
2915
+ tagsCommand.command("list").description("List all tags").action(async () => {
2916
+ try {
2917
+ const lumail = getLumail();
2918
+ const result = await lumail.tags.list();
2919
+ output(result);
2920
+ } catch (error) {
2921
+ handleError(error);
2922
+ }
2923
+ });
2924
+ tagsCommand.command("create").description("Create a new tag").requiredOption("--name <name>", "Tag name").action(async (opts) => {
2925
+ try {
2926
+ const lumail = getLumail();
2927
+ const result = await lumail.tags.create({ name: opts.name });
2928
+ output(result);
2929
+ } catch (error) {
2930
+ handleError(error);
2931
+ }
2932
+ });
2933
+ tagsCommand.command("get <idOrName>").description("Get tag details").action(async (idOrName) => {
2934
+ try {
2935
+ const lumail = getLumail();
2936
+ const result = await lumail.tags.get(idOrName);
2937
+ output(result);
2938
+ } catch (error) {
2939
+ handleError(error);
2940
+ }
2941
+ });
2942
+ tagsCommand.command("update <idOrName>").description("Rename a tag").requiredOption("--name <name>", "New tag name").action(async (idOrName, opts) => {
2943
+ try {
2944
+ const lumail = getLumail();
2945
+ const result = await lumail.tags.update(idOrName, { name: opts.name });
2946
+ output(result);
2947
+ } catch (error) {
2948
+ handleError(error);
2949
+ }
2950
+ });
2951
+
2952
+ // ../../src/cli/commands/emails.ts
2953
+ var emailsCommand = new Command("emails").description("Send and verify emails");
2954
+ emailsCommand.command("send").description("Send a transactional email").requiredOption("--to <email>", "Recipient email").requiredOption("--from <email>", "Sender email").requiredOption("--subject <subject>", "Email subject").requiredOption("--content <content>", "Email content").option("--content-type <type>", "MARKDOWN, HTML, or TIPTAP", "MARKDOWN").option("--reply-to <email>", "Reply-to address").option("--transactional", "Mark as transactional").action(async (opts) => {
2955
+ try {
2956
+ const lumail = getLumail();
2957
+ const result = await lumail.emails.send({
2958
+ to: opts.to,
2959
+ from: opts.from,
2960
+ subject: opts.subject,
2961
+ content: opts.content,
2962
+ contentType: opts.contentType,
2963
+ replyTo: opts.replyTo,
2964
+ transactional: opts.transactional
2965
+ });
2966
+ output(result);
2967
+ } catch (error) {
2968
+ handleError(error);
2969
+ }
2970
+ });
2971
+ emailsCommand.command("verify <email>").description("Verify an email address").action(async (email) => {
2972
+ try {
2973
+ const lumail = getLumail();
2974
+ const result = await lumail.emails.verify({ email });
2975
+ output(result);
2976
+ } catch (error) {
2977
+ handleError(error);
2978
+ }
2979
+ });
2980
+
2981
+ // ../../src/cli/commands/events.ts
2982
+ var eventsCommand = new Command("events").description("Manage subscriber events");
2983
+ eventsCommand.command("create").description("Create a subscriber event").requiredOption("--type <type>", "Event type (e.g. SUBSCRIBED, TAG_ADDED)").requiredOption("--subscriber <idOrEmail>", "Subscriber ID or email").option("--data <json>", "Event data as JSON", "{}").action(async (opts) => {
2984
+ try {
2985
+ const lumail = getLumail();
2986
+ const result = await lumail.events.create({
2987
+ eventType: opts.type,
2988
+ subscriber: opts.subscriber,
2989
+ data: JSON.parse(opts.data)
2990
+ });
2991
+ output(result);
2992
+ } catch (error) {
2993
+ handleError(error);
2994
+ }
2995
+ });
2996
+
2997
+ // ../../src/cli/commands/tools.ts
2998
+ var toolsCommand = new Command("tools").description("V2 tools API - list and run tools");
2999
+ toolsCommand.command("list").description("List all available tools").option("--raw", "Show raw tool definitions").action(async (opts) => {
3000
+ try {
3001
+ const lumail = getLumail();
3002
+ const result = await lumail.tools.list();
3003
+ if (opts.raw) {
3004
+ output(result);
3005
+ } else {
3006
+ output(result.tools.map((t) => ({
3007
+ name: t.name,
3008
+ description: t.description,
3009
+ category: t.category ?? "-"
3010
+ })));
3011
+ }
3012
+ } catch (error) {
3013
+ handleError(error);
3014
+ }
3015
+ });
3016
+ toolsCommand.command("get <name>").description("Get a tool schema").action(async (name) => {
3017
+ try {
3018
+ const lumail = getLumail();
3019
+ const result = await lumail.tools.get(name);
3020
+ output(result);
3021
+ } catch (error) {
3022
+ handleError(error);
3023
+ }
3024
+ });
3025
+ toolsCommand.command("run <name>").description("Run a tool by name").option("--params <json>", "Tool parameters as JSON", "{}").action(async (name, opts) => {
3026
+ try {
3027
+ const lumail = getLumail();
3028
+ const result = await lumail.tools.run(name, JSON.parse(opts.params));
3029
+ output(result);
3030
+ } catch (error) {
3031
+ handleError(error);
3032
+ }
3033
+ });
3034
+
3035
+ // ../../src/cli/commands/setup.ts
3036
+ var import_picocolors3 = __toESM(require_picocolors(), 1);
3037
+ import { createInterface } from "readline";
3038
+ import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "fs";
3039
+ import { execSync } from "child_process";
3040
+ import { homedir as homedir2 } from "os";
3041
+ import { join as join2 } from "path";
3042
+ var SKILL_URL = "https://raw.githubusercontent.com/Melvynx/lumail-opensource/main/skills/lumail/SKILL.md";
3043
+ var SKILLS_DIR = join2(homedir2(), ".claude", "skills", "lumail");
3044
+ function prompt(question) {
3045
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
3046
+ return new Promise((resolve) => {
3047
+ rl.question(question, (answer) => {
3048
+ rl.close();
3049
+ resolve(answer.trim());
3050
+ });
3051
+ });
3052
+ }
3053
+ async function choose(question, options) {
3054
+ console.log(`
3055
+ ${import_picocolors3.default.bold(question)}
3056
+ `);
3057
+ options.forEach((opt, i) => {
3058
+ console.log(` ${import_picocolors3.default.cyan(`${i + 1})`)} ${opt}`);
3059
+ });
3060
+ console.log();
3061
+ const answer = await prompt(`${import_picocolors3.default.dim("Choice")} > `);
3062
+ const idx = parseInt(answer, 10) - 1;
3063
+ if (idx < 0 || idx >= options.length) {
3064
+ console.log(import_picocolors3.default.red("Invalid choice"));
3065
+ process.exit(1);
3066
+ }
3067
+ return idx;
3068
+ }
3069
+ async function setupMcp(token) {
3070
+ console.log(import_picocolors3.default.dim(`
3071
+ Configuring MCP server via claude mcp add...`));
3072
+ try {
3073
+ execSync(`claude mcp add --transport http lumail https://lumail.io/api/mcp/sse --header "Authorization: Bearer ${token}"`, { stdio: "inherit" });
3074
+ console.log(import_picocolors3.default.green(`
3075
+ MCP server added successfully.`));
3076
+ console.log(import_picocolors3.default.dim("Claude Code now has access to 55+ Lumail tools."));
3077
+ console.log(import_picocolors3.default.dim(`Restart Claude Code to activate.
3078
+ `));
3079
+ } catch {
3080
+ console.log(import_picocolors3.default.yellow(`
3081
+ claude mcp add failed. Is Claude Code installed?`));
3082
+ console.log(import_picocolors3.default.dim("Install manually:"));
3083
+ console.log(import_picocolors3.default.dim(` claude mcp add --transport http lumail https://lumail.io/api/mcp/sse --header "Authorization: Bearer ${token}"`));
3084
+ console.log();
3085
+ }
3086
+ }
3087
+ async function setupSkills(token) {
3088
+ console.log(import_picocolors3.default.dim(`
3089
+ Installing Lumail skill...`));
3090
+ try {
3091
+ const res = await fetch(SKILL_URL);
3092
+ if (!res.ok)
3093
+ throw new Error(`HTTP ${res.status}`);
3094
+ const content = await res.text();
3095
+ mkdirSync2(SKILLS_DIR, { recursive: true });
3096
+ writeFileSync2(join2(SKILLS_DIR, "SKILL.md"), content);
3097
+ console.log(import_picocolors3.default.green("Skill installed to ~/.claude/skills/lumail/"));
3098
+ } catch {
3099
+ console.log(import_picocolors3.default.yellow("Could not download skill from GitHub."));
3100
+ console.log(import_picocolors3.default.dim("Manual install: curl -o ~/.claude/skills/lumail/SKILL.md --create-dirs " + SKILL_URL));
3101
+ }
3102
+ setToken(token);
3103
+ console.log(import_picocolors3.default.green("API key saved."));
3104
+ console.log(import_picocolors3.default.dim(`
3105
+ Claude now knows all Lumail CLI commands. Use: lumail <command>
3106
+ `));
3107
+ }
3108
+ var setupCommand = new Command("setup").description("Set up Lumail integration - MCP server or Skills + CLI").action(async () => {
3109
+ console.log(import_picocolors3.default.bold(`
3110
+ Lumail Setup
3111
+ `));
3112
+ const mode = await choose("How do you want to integrate Lumail?", [
3113
+ `${import_picocolors3.default.bold("MCP")} - Connect Claude/Cursor via Model Context Protocol (55+ tools)`,
3114
+ `${import_picocolors3.default.bold("Skills (CLI)")} - Install Claude Code skill + CLI for terminal workflows`,
3115
+ `${import_picocolors3.default.bold("Both")} - MCP server + skill + CLI`
3116
+ ]);
3117
+ const token = await prompt(`${import_picocolors3.default.bold("API token")} ${import_picocolors3.default.dim("(from lumail.io/settings)")} > `);
3118
+ if (!token) {
3119
+ console.log(import_picocolors3.default.red("API token is required."));
3120
+ process.exit(1);
3121
+ }
3122
+ if (mode === 0 || mode === 2) {
3123
+ await setupMcp(token);
3124
+ }
3125
+ if (mode === 1 || mode === 2) {
3126
+ await setupSkills(token);
3127
+ }
3128
+ setToken(token);
3129
+ console.log(import_picocolors3.default.green(import_picocolors3.default.bold("Setup complete!")));
3130
+ console.log(import_picocolors3.default.dim(`Docs: https://lumail.io/docs/ai-integration
3131
+ `));
3132
+ });
3133
+
3134
+ // ../../src/cli/index.ts
3135
+ var program2 = new Command;
3136
+ program2.name("lumail").description("Lumail CLI - email marketing platform").version("0.1.0").option("--json", "Output as JSON", false).option("--format <fmt>", "Output format: text, json, csv", "text").option("--verbose", "Enable debug logging", false).option("--no-color", "Disable colored output").option("--no-header", "Omit table headers").hook("preAction", (_thisCmd, actionCmd) => {
3137
+ const root = actionCmd.optsWithGlobals();
3138
+ globalFlags.json = root.json ?? false;
3139
+ globalFlags.format = root.format ?? "text";
3140
+ globalFlags.verbose = root.verbose ?? false;
3141
+ globalFlags.noColor = root.color === false;
3142
+ globalFlags.noHeader = root.header === false;
3143
+ });
3144
+ program2.addCommand(setupCommand);
3145
+ program2.addCommand(authCommand);
3146
+ program2.addCommand(subscribersCommand);
3147
+ program2.addCommand(campaignsCommand);
3148
+ program2.addCommand(tagsCommand);
3149
+ program2.addCommand(emailsCommand);
3150
+ program2.addCommand(eventsCommand);
3151
+ program2.addCommand(toolsCommand);
3152
+ program2.parse();