@hasna/models 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3738 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
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
+ function __accessProp(key) {
9
+ return this[key];
10
+ }
11
+ var __toESMCache_node;
12
+ var __toESMCache_esm;
13
+ var __toESM = (mod, isNodeMode, target) => {
14
+ var canCache = mod != null && typeof mod === "object";
15
+ if (canCache) {
16
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
17
+ var cached = cache.get(mod);
18
+ if (cached)
19
+ return cached;
20
+ }
21
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
22
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
23
+ for (let key of __getOwnPropNames(mod))
24
+ if (!__hasOwnProp.call(to, key))
25
+ __defProp(to, key, {
26
+ get: __accessProp.bind(mod, key),
27
+ enumerable: true
28
+ });
29
+ if (canCache)
30
+ cache.set(mod, to);
31
+ return to;
32
+ };
33
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
34
+ var __require = import.meta.require;
35
+
36
+ // node_modules/commander/lib/error.js
37
+ var require_error = __commonJS((exports) => {
38
+ class CommanderError extends Error {
39
+ constructor(exitCode, code, message) {
40
+ super(message);
41
+ Error.captureStackTrace(this, this.constructor);
42
+ this.name = this.constructor.name;
43
+ this.code = code;
44
+ this.exitCode = exitCode;
45
+ this.nestedError = undefined;
46
+ }
47
+ }
48
+
49
+ class InvalidArgumentError extends CommanderError {
50
+ constructor(message) {
51
+ super(1, "commander.invalidArgument", message);
52
+ Error.captureStackTrace(this, this.constructor);
53
+ this.name = this.constructor.name;
54
+ }
55
+ }
56
+ exports.CommanderError = CommanderError;
57
+ exports.InvalidArgumentError = InvalidArgumentError;
58
+ });
59
+
60
+ // node_modules/commander/lib/argument.js
61
+ var require_argument = __commonJS((exports) => {
62
+ var { InvalidArgumentError } = require_error();
63
+
64
+ class Argument {
65
+ constructor(name, description) {
66
+ this.description = description || "";
67
+ this.variadic = false;
68
+ this.parseArg = undefined;
69
+ this.defaultValue = undefined;
70
+ this.defaultValueDescription = undefined;
71
+ this.argChoices = undefined;
72
+ switch (name[0]) {
73
+ case "<":
74
+ this.required = true;
75
+ this._name = name.slice(1, -1);
76
+ break;
77
+ case "[":
78
+ this.required = false;
79
+ this._name = name.slice(1, -1);
80
+ break;
81
+ default:
82
+ this.required = true;
83
+ this._name = name;
84
+ break;
85
+ }
86
+ if (this._name.length > 3 && this._name.slice(-3) === "...") {
87
+ this.variadic = true;
88
+ this._name = this._name.slice(0, -3);
89
+ }
90
+ }
91
+ name() {
92
+ return this._name;
93
+ }
94
+ _concatValue(value, previous) {
95
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
96
+ return [value];
97
+ }
98
+ return previous.concat(value);
99
+ }
100
+ default(value, description) {
101
+ this.defaultValue = value;
102
+ this.defaultValueDescription = description;
103
+ return this;
104
+ }
105
+ argParser(fn) {
106
+ this.parseArg = fn;
107
+ return this;
108
+ }
109
+ choices(values) {
110
+ this.argChoices = values.slice();
111
+ this.parseArg = (arg, previous) => {
112
+ if (!this.argChoices.includes(arg)) {
113
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
114
+ }
115
+ if (this.variadic) {
116
+ return this._concatValue(arg, previous);
117
+ }
118
+ return arg;
119
+ };
120
+ return this;
121
+ }
122
+ argRequired() {
123
+ this.required = true;
124
+ return this;
125
+ }
126
+ argOptional() {
127
+ this.required = false;
128
+ return this;
129
+ }
130
+ }
131
+ function humanReadableArgName(arg) {
132
+ const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
133
+ return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
134
+ }
135
+ exports.Argument = Argument;
136
+ exports.humanReadableArgName = humanReadableArgName;
137
+ });
138
+
139
+ // node_modules/commander/lib/help.js
140
+ var require_help = __commonJS((exports) => {
141
+ var { humanReadableArgName } = require_argument();
142
+
143
+ class Help {
144
+ constructor() {
145
+ this.helpWidth = undefined;
146
+ this.minWidthToWrap = 40;
147
+ this.sortSubcommands = false;
148
+ this.sortOptions = false;
149
+ this.showGlobalOptions = false;
150
+ }
151
+ prepareContext(contextOptions) {
152
+ this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
153
+ }
154
+ visibleCommands(cmd) {
155
+ const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
156
+ const helpCommand = cmd._getHelpCommand();
157
+ if (helpCommand && !helpCommand._hidden) {
158
+ visibleCommands.push(helpCommand);
159
+ }
160
+ if (this.sortSubcommands) {
161
+ visibleCommands.sort((a, b) => {
162
+ return a.name().localeCompare(b.name());
163
+ });
164
+ }
165
+ return visibleCommands;
166
+ }
167
+ compareOptions(a, b) {
168
+ const getSortKey = (option) => {
169
+ return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
170
+ };
171
+ return getSortKey(a).localeCompare(getSortKey(b));
172
+ }
173
+ visibleOptions(cmd) {
174
+ const visibleOptions = cmd.options.filter((option) => !option.hidden);
175
+ const helpOption = cmd._getHelpOption();
176
+ if (helpOption && !helpOption.hidden) {
177
+ const removeShort = helpOption.short && cmd._findOption(helpOption.short);
178
+ const removeLong = helpOption.long && cmd._findOption(helpOption.long);
179
+ if (!removeShort && !removeLong) {
180
+ visibleOptions.push(helpOption);
181
+ } else if (helpOption.long && !removeLong) {
182
+ visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
183
+ } else if (helpOption.short && !removeShort) {
184
+ visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
185
+ }
186
+ }
187
+ if (this.sortOptions) {
188
+ visibleOptions.sort(this.compareOptions);
189
+ }
190
+ return visibleOptions;
191
+ }
192
+ visibleGlobalOptions(cmd) {
193
+ if (!this.showGlobalOptions)
194
+ return [];
195
+ const globalOptions = [];
196
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
197
+ const visibleOptions = ancestorCmd.options.filter((option) => !option.hidden);
198
+ globalOptions.push(...visibleOptions);
199
+ }
200
+ if (this.sortOptions) {
201
+ globalOptions.sort(this.compareOptions);
202
+ }
203
+ return globalOptions;
204
+ }
205
+ visibleArguments(cmd) {
206
+ if (cmd._argsDescription) {
207
+ cmd.registeredArguments.forEach((argument) => {
208
+ argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
209
+ });
210
+ }
211
+ if (cmd.registeredArguments.find((argument) => argument.description)) {
212
+ return cmd.registeredArguments;
213
+ }
214
+ return [];
215
+ }
216
+ subcommandTerm(cmd) {
217
+ const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
218
+ return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + (args ? " " + args : "");
219
+ }
220
+ optionTerm(option) {
221
+ return option.flags;
222
+ }
223
+ argumentTerm(argument) {
224
+ return argument.name();
225
+ }
226
+ longestSubcommandTermLength(cmd, helper) {
227
+ return helper.visibleCommands(cmd).reduce((max, command) => {
228
+ return Math.max(max, this.displayWidth(helper.styleSubcommandTerm(helper.subcommandTerm(command))));
229
+ }, 0);
230
+ }
231
+ longestOptionTermLength(cmd, helper) {
232
+ return helper.visibleOptions(cmd).reduce((max, option) => {
233
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
234
+ }, 0);
235
+ }
236
+ longestGlobalOptionTermLength(cmd, helper) {
237
+ return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
238
+ return Math.max(max, this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))));
239
+ }, 0);
240
+ }
241
+ longestArgumentTermLength(cmd, helper) {
242
+ return helper.visibleArguments(cmd).reduce((max, argument) => {
243
+ return Math.max(max, this.displayWidth(helper.styleArgumentTerm(helper.argumentTerm(argument))));
244
+ }, 0);
245
+ }
246
+ commandUsage(cmd) {
247
+ let cmdName = cmd._name;
248
+ if (cmd._aliases[0]) {
249
+ cmdName = cmdName + "|" + cmd._aliases[0];
250
+ }
251
+ let ancestorCmdNames = "";
252
+ for (let ancestorCmd = cmd.parent;ancestorCmd; ancestorCmd = ancestorCmd.parent) {
253
+ ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
254
+ }
255
+ return ancestorCmdNames + cmdName + " " + cmd.usage();
256
+ }
257
+ commandDescription(cmd) {
258
+ return cmd.description();
259
+ }
260
+ subcommandDescription(cmd) {
261
+ return cmd.summary() || cmd.description();
262
+ }
263
+ optionDescription(option) {
264
+ const extraInfo = [];
265
+ if (option.argChoices) {
266
+ extraInfo.push(`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
267
+ }
268
+ if (option.defaultValue !== undefined) {
269
+ const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
270
+ if (showDefault) {
271
+ extraInfo.push(`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`);
272
+ }
273
+ }
274
+ if (option.presetArg !== undefined && option.optional) {
275
+ extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
276
+ }
277
+ if (option.envVar !== undefined) {
278
+ extraInfo.push(`env: ${option.envVar}`);
279
+ }
280
+ if (extraInfo.length > 0) {
281
+ return `${option.description} (${extraInfo.join(", ")})`;
282
+ }
283
+ return option.description;
284
+ }
285
+ argumentDescription(argument) {
286
+ const extraInfo = [];
287
+ if (argument.argChoices) {
288
+ extraInfo.push(`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`);
289
+ }
290
+ if (argument.defaultValue !== undefined) {
291
+ extraInfo.push(`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`);
292
+ }
293
+ if (extraInfo.length > 0) {
294
+ const extraDescription = `(${extraInfo.join(", ")})`;
295
+ if (argument.description) {
296
+ return `${argument.description} ${extraDescription}`;
297
+ }
298
+ return extraDescription;
299
+ }
300
+ return argument.description;
301
+ }
302
+ formatHelp(cmd, helper) {
303
+ const termWidth = helper.padWidth(cmd, helper);
304
+ const helpWidth = helper.helpWidth ?? 80;
305
+ function callFormatItem(term, description) {
306
+ return helper.formatItem(term, termWidth, description, helper);
307
+ }
308
+ let output = [
309
+ `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
310
+ ""
311
+ ];
312
+ const commandDescription = helper.commandDescription(cmd);
313
+ if (commandDescription.length > 0) {
314
+ output = output.concat([
315
+ helper.boxWrap(helper.styleCommandDescription(commandDescription), helpWidth),
316
+ ""
317
+ ]);
318
+ }
319
+ const argumentList = helper.visibleArguments(cmd).map((argument) => {
320
+ return callFormatItem(helper.styleArgumentTerm(helper.argumentTerm(argument)), helper.styleArgumentDescription(helper.argumentDescription(argument)));
321
+ });
322
+ if (argumentList.length > 0) {
323
+ output = output.concat([
324
+ helper.styleTitle("Arguments:"),
325
+ ...argumentList,
326
+ ""
327
+ ]);
328
+ }
329
+ const optionList = helper.visibleOptions(cmd).map((option) => {
330
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
331
+ });
332
+ if (optionList.length > 0) {
333
+ output = output.concat([
334
+ helper.styleTitle("Options:"),
335
+ ...optionList,
336
+ ""
337
+ ]);
338
+ }
339
+ if (helper.showGlobalOptions) {
340
+ const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
341
+ return callFormatItem(helper.styleOptionTerm(helper.optionTerm(option)), helper.styleOptionDescription(helper.optionDescription(option)));
342
+ });
343
+ if (globalOptionList.length > 0) {
344
+ output = output.concat([
345
+ helper.styleTitle("Global Options:"),
346
+ ...globalOptionList,
347
+ ""
348
+ ]);
349
+ }
350
+ }
351
+ const commandList = helper.visibleCommands(cmd).map((cmd2) => {
352
+ return callFormatItem(helper.styleSubcommandTerm(helper.subcommandTerm(cmd2)), helper.styleSubcommandDescription(helper.subcommandDescription(cmd2)));
353
+ });
354
+ if (commandList.length > 0) {
355
+ output = output.concat([
356
+ helper.styleTitle("Commands:"),
357
+ ...commandList,
358
+ ""
359
+ ]);
360
+ }
361
+ return output.join(`
362
+ `);
363
+ }
364
+ displayWidth(str) {
365
+ return stripColor(str).length;
366
+ }
367
+ styleTitle(str) {
368
+ return str;
369
+ }
370
+ styleUsage(str) {
371
+ return str.split(" ").map((word) => {
372
+ if (word === "[options]")
373
+ return this.styleOptionText(word);
374
+ if (word === "[command]")
375
+ return this.styleSubcommandText(word);
376
+ if (word[0] === "[" || word[0] === "<")
377
+ return this.styleArgumentText(word);
378
+ return this.styleCommandText(word);
379
+ }).join(" ");
380
+ }
381
+ styleCommandDescription(str) {
382
+ return this.styleDescriptionText(str);
383
+ }
384
+ styleOptionDescription(str) {
385
+ return this.styleDescriptionText(str);
386
+ }
387
+ styleSubcommandDescription(str) {
388
+ return this.styleDescriptionText(str);
389
+ }
390
+ styleArgumentDescription(str) {
391
+ return this.styleDescriptionText(str);
392
+ }
393
+ styleDescriptionText(str) {
394
+ return str;
395
+ }
396
+ styleOptionTerm(str) {
397
+ return this.styleOptionText(str);
398
+ }
399
+ styleSubcommandTerm(str) {
400
+ return str.split(" ").map((word) => {
401
+ if (word === "[options]")
402
+ return this.styleOptionText(word);
403
+ if (word[0] === "[" || word[0] === "<")
404
+ return this.styleArgumentText(word);
405
+ return this.styleSubcommandText(word);
406
+ }).join(" ");
407
+ }
408
+ styleArgumentTerm(str) {
409
+ return this.styleArgumentText(str);
410
+ }
411
+ styleOptionText(str) {
412
+ return str;
413
+ }
414
+ styleArgumentText(str) {
415
+ return str;
416
+ }
417
+ styleSubcommandText(str) {
418
+ return str;
419
+ }
420
+ styleCommandText(str) {
421
+ return str;
422
+ }
423
+ padWidth(cmd, helper) {
424
+ return Math.max(helper.longestOptionTermLength(cmd, helper), helper.longestGlobalOptionTermLength(cmd, helper), helper.longestSubcommandTermLength(cmd, helper), helper.longestArgumentTermLength(cmd, helper));
425
+ }
426
+ preformatted(str) {
427
+ return /\n[^\S\r\n]/.test(str);
428
+ }
429
+ formatItem(term, termWidth, description, helper) {
430
+ const itemIndent = 2;
431
+ const itemIndentStr = " ".repeat(itemIndent);
432
+ if (!description)
433
+ return itemIndentStr + term;
434
+ const paddedTerm = term.padEnd(termWidth + term.length - helper.displayWidth(term));
435
+ const spacerWidth = 2;
436
+ const helpWidth = this.helpWidth ?? 80;
437
+ const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
438
+ let formattedDescription;
439
+ if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
440
+ formattedDescription = description;
441
+ } else {
442
+ const wrappedDescription = helper.boxWrap(description, remainingWidth);
443
+ formattedDescription = wrappedDescription.replace(/\n/g, `
444
+ ` + " ".repeat(termWidth + spacerWidth));
445
+ }
446
+ return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
447
+ ${itemIndentStr}`);
448
+ }
449
+ boxWrap(str, width) {
450
+ if (width < this.minWidthToWrap)
451
+ return str;
452
+ const rawLines = str.split(/\r\n|\n/);
453
+ const chunkPattern = /[\s]*[^\s]+/g;
454
+ const wrappedLines = [];
455
+ rawLines.forEach((line) => {
456
+ const chunks = line.match(chunkPattern);
457
+ if (chunks === null) {
458
+ wrappedLines.push("");
459
+ return;
460
+ }
461
+ let sumChunks = [chunks.shift()];
462
+ let sumWidth = this.displayWidth(sumChunks[0]);
463
+ chunks.forEach((chunk) => {
464
+ const visibleWidth = this.displayWidth(chunk);
465
+ if (sumWidth + visibleWidth <= width) {
466
+ sumChunks.push(chunk);
467
+ sumWidth += visibleWidth;
468
+ return;
469
+ }
470
+ wrappedLines.push(sumChunks.join(""));
471
+ const nextChunk = chunk.trimStart();
472
+ sumChunks = [nextChunk];
473
+ sumWidth = this.displayWidth(nextChunk);
474
+ });
475
+ wrappedLines.push(sumChunks.join(""));
476
+ });
477
+ return wrappedLines.join(`
478
+ `);
479
+ }
480
+ }
481
+ function stripColor(str) {
482
+ const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
483
+ return str.replace(sgrPattern, "");
484
+ }
485
+ exports.Help = Help;
486
+ exports.stripColor = stripColor;
487
+ });
488
+
489
+ // node_modules/commander/lib/option.js
490
+ var require_option = __commonJS((exports) => {
491
+ var { InvalidArgumentError } = require_error();
492
+
493
+ class Option {
494
+ constructor(flags, description) {
495
+ this.flags = flags;
496
+ this.description = description || "";
497
+ this.required = flags.includes("<");
498
+ this.optional = flags.includes("[");
499
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags);
500
+ this.mandatory = false;
501
+ const optionFlags = splitOptionFlags(flags);
502
+ this.short = optionFlags.shortFlag;
503
+ this.long = optionFlags.longFlag;
504
+ this.negate = false;
505
+ if (this.long) {
506
+ this.negate = this.long.startsWith("--no-");
507
+ }
508
+ this.defaultValue = undefined;
509
+ this.defaultValueDescription = undefined;
510
+ this.presetArg = undefined;
511
+ this.envVar = undefined;
512
+ this.parseArg = undefined;
513
+ this.hidden = false;
514
+ this.argChoices = undefined;
515
+ this.conflictsWith = [];
516
+ this.implied = undefined;
517
+ }
518
+ default(value, description) {
519
+ this.defaultValue = value;
520
+ this.defaultValueDescription = description;
521
+ return this;
522
+ }
523
+ preset(arg) {
524
+ this.presetArg = arg;
525
+ return this;
526
+ }
527
+ conflicts(names) {
528
+ this.conflictsWith = this.conflictsWith.concat(names);
529
+ return this;
530
+ }
531
+ implies(impliedOptionValues) {
532
+ let newImplied = impliedOptionValues;
533
+ if (typeof impliedOptionValues === "string") {
534
+ newImplied = { [impliedOptionValues]: true };
535
+ }
536
+ this.implied = Object.assign(this.implied || {}, newImplied);
537
+ return this;
538
+ }
539
+ env(name) {
540
+ this.envVar = name;
541
+ return this;
542
+ }
543
+ argParser(fn) {
544
+ this.parseArg = fn;
545
+ return this;
546
+ }
547
+ makeOptionMandatory(mandatory = true) {
548
+ this.mandatory = !!mandatory;
549
+ return this;
550
+ }
551
+ hideHelp(hide = true) {
552
+ this.hidden = !!hide;
553
+ return this;
554
+ }
555
+ _concatValue(value, previous) {
556
+ if (previous === this.defaultValue || !Array.isArray(previous)) {
557
+ return [value];
558
+ }
559
+ return previous.concat(value);
560
+ }
561
+ choices(values) {
562
+ this.argChoices = values.slice();
563
+ this.parseArg = (arg, previous) => {
564
+ if (!this.argChoices.includes(arg)) {
565
+ throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(", ")}.`);
566
+ }
567
+ if (this.variadic) {
568
+ return this._concatValue(arg, previous);
569
+ }
570
+ return arg;
571
+ };
572
+ return this;
573
+ }
574
+ name() {
575
+ if (this.long) {
576
+ return this.long.replace(/^--/, "");
577
+ }
578
+ return this.short.replace(/^-/, "");
579
+ }
580
+ attributeName() {
581
+ if (this.negate) {
582
+ return camelcase(this.name().replace(/^no-/, ""));
583
+ }
584
+ return camelcase(this.name());
585
+ }
586
+ is(arg) {
587
+ return this.short === arg || this.long === arg;
588
+ }
589
+ isBoolean() {
590
+ return !this.required && !this.optional && !this.negate;
591
+ }
592
+ }
593
+
594
+ class DualOptions {
595
+ constructor(options) {
596
+ this.positiveOptions = new Map;
597
+ this.negativeOptions = new Map;
598
+ this.dualOptions = new Set;
599
+ options.forEach((option) => {
600
+ if (option.negate) {
601
+ this.negativeOptions.set(option.attributeName(), option);
602
+ } else {
603
+ this.positiveOptions.set(option.attributeName(), option);
604
+ }
605
+ });
606
+ this.negativeOptions.forEach((value, key) => {
607
+ if (this.positiveOptions.has(key)) {
608
+ this.dualOptions.add(key);
609
+ }
610
+ });
611
+ }
612
+ valueFromOption(value, option) {
613
+ const optionKey = option.attributeName();
614
+ if (!this.dualOptions.has(optionKey))
615
+ return true;
616
+ const preset = this.negativeOptions.get(optionKey).presetArg;
617
+ const negativeValue = preset !== undefined ? preset : false;
618
+ return option.negate === (negativeValue === value);
619
+ }
620
+ }
621
+ function camelcase(str) {
622
+ return str.split("-").reduce((str2, word) => {
623
+ return str2 + word[0].toUpperCase() + word.slice(1);
624
+ });
625
+ }
626
+ function splitOptionFlags(flags) {
627
+ let shortFlag;
628
+ let longFlag;
629
+ const shortFlagExp = /^-[^-]$/;
630
+ const longFlagExp = /^--[^-]/;
631
+ const flagParts = flags.split(/[ |,]+/).concat("guard");
632
+ if (shortFlagExp.test(flagParts[0]))
633
+ shortFlag = flagParts.shift();
634
+ if (longFlagExp.test(flagParts[0]))
635
+ longFlag = flagParts.shift();
636
+ if (!shortFlag && shortFlagExp.test(flagParts[0]))
637
+ shortFlag = flagParts.shift();
638
+ if (!shortFlag && longFlagExp.test(flagParts[0])) {
639
+ shortFlag = longFlag;
640
+ longFlag = flagParts.shift();
641
+ }
642
+ if (flagParts[0].startsWith("-")) {
643
+ const unsupportedFlag = flagParts[0];
644
+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
645
+ if (/^-[^-][^-]/.test(unsupportedFlag))
646
+ throw new Error(`${baseError}
647
+ - a short flag is a single dash and a single character
648
+ - either use a single dash and a single character (for a short flag)
649
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`);
650
+ if (shortFlagExp.test(unsupportedFlag))
651
+ throw new Error(`${baseError}
652
+ - too many short flags`);
653
+ if (longFlagExp.test(unsupportedFlag))
654
+ throw new Error(`${baseError}
655
+ - too many long flags`);
656
+ throw new Error(`${baseError}
657
+ - unrecognised flag format`);
658
+ }
659
+ if (shortFlag === undefined && longFlag === undefined)
660
+ throw new Error(`option creation failed due to no flags found in '${flags}'.`);
661
+ return { shortFlag, longFlag };
662
+ }
663
+ exports.Option = Option;
664
+ exports.DualOptions = DualOptions;
665
+ });
666
+
667
+ // node_modules/commander/lib/suggestSimilar.js
668
+ var require_suggestSimilar = __commonJS((exports) => {
669
+ var maxDistance = 3;
670
+ function editDistance(a, b) {
671
+ if (Math.abs(a.length - b.length) > maxDistance)
672
+ return Math.max(a.length, b.length);
673
+ const d = [];
674
+ for (let i = 0;i <= a.length; i++) {
675
+ d[i] = [i];
676
+ }
677
+ for (let j = 0;j <= b.length; j++) {
678
+ d[0][j] = j;
679
+ }
680
+ for (let j = 1;j <= b.length; j++) {
681
+ for (let i = 1;i <= a.length; i++) {
682
+ let cost = 1;
683
+ if (a[i - 1] === b[j - 1]) {
684
+ cost = 0;
685
+ } else {
686
+ cost = 1;
687
+ }
688
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
689
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
690
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
691
+ }
692
+ }
693
+ }
694
+ return d[a.length][b.length];
695
+ }
696
+ function suggestSimilar(word, candidates) {
697
+ if (!candidates || candidates.length === 0)
698
+ return "";
699
+ candidates = Array.from(new Set(candidates));
700
+ const searchingOptions = word.startsWith("--");
701
+ if (searchingOptions) {
702
+ word = word.slice(2);
703
+ candidates = candidates.map((candidate) => candidate.slice(2));
704
+ }
705
+ let similar = [];
706
+ let bestDistance = maxDistance;
707
+ const minSimilarity = 0.4;
708
+ candidates.forEach((candidate) => {
709
+ if (candidate.length <= 1)
710
+ return;
711
+ const distance = editDistance(word, candidate);
712
+ const length = Math.max(word.length, candidate.length);
713
+ const similarity = (length - distance) / length;
714
+ if (similarity > minSimilarity) {
715
+ if (distance < bestDistance) {
716
+ bestDistance = distance;
717
+ similar = [candidate];
718
+ } else if (distance === bestDistance) {
719
+ similar.push(candidate);
720
+ }
721
+ }
722
+ });
723
+ similar.sort((a, b) => a.localeCompare(b));
724
+ if (searchingOptions) {
725
+ similar = similar.map((candidate) => `--${candidate}`);
726
+ }
727
+ if (similar.length > 1) {
728
+ return `
729
+ (Did you mean one of ${similar.join(", ")}?)`;
730
+ }
731
+ if (similar.length === 1) {
732
+ return `
733
+ (Did you mean ${similar[0]}?)`;
734
+ }
735
+ return "";
736
+ }
737
+ exports.suggestSimilar = suggestSimilar;
738
+ });
739
+
740
+ // node_modules/commander/lib/command.js
741
+ var require_command = __commonJS((exports) => {
742
+ var EventEmitter = __require("events").EventEmitter;
743
+ var childProcess = __require("child_process");
744
+ var path = __require("path");
745
+ var fs = __require("fs");
746
+ var process2 = __require("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
+ }
804
+ copyInheritedSettings(sourceCommand) {
805
+ this._outputConfiguration = sourceCommand._outputConfiguration;
806
+ this._helpOption = sourceCommand._helpOption;
807
+ this._helpCommand = sourceCommand._helpCommand;
808
+ this._helpConfiguration = sourceCommand._helpConfiguration;
809
+ this._exitCallback = sourceCommand._exitCallback;
810
+ this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
811
+ this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
812
+ this._allowExcessArguments = sourceCommand._allowExcessArguments;
813
+ this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
814
+ this._showHelpAfterError = sourceCommand._showHelpAfterError;
815
+ this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
816
+ return this;
817
+ }
818
+ _getCommandAndAncestors() {
819
+ const result = [];
820
+ for (let command = this;command; command = command.parent) {
821
+ result.push(command);
822
+ }
823
+ return result;
824
+ }
825
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
826
+ let desc = actionOptsOrExecDesc;
827
+ let opts = execOpts;
828
+ if (typeof desc === "object" && desc !== null) {
829
+ opts = desc;
830
+ desc = null;
831
+ }
832
+ opts = opts || {};
833
+ const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
834
+ const cmd = this.createCommand(name);
835
+ if (desc) {
836
+ cmd.description(desc);
837
+ cmd._executableHandler = true;
838
+ }
839
+ if (opts.isDefault)
840
+ this._defaultCommandName = cmd._name;
841
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
842
+ cmd._executableFile = opts.executableFile || null;
843
+ if (args)
844
+ cmd.arguments(args);
845
+ this._registerCommand(cmd);
846
+ cmd.parent = this;
847
+ cmd.copyInheritedSettings(this);
848
+ if (desc)
849
+ return this;
850
+ return cmd;
851
+ }
852
+ createCommand(name) {
853
+ return new Command(name);
854
+ }
855
+ createHelp() {
856
+ return Object.assign(new Help, this.configureHelp());
857
+ }
858
+ configureHelp(configuration) {
859
+ if (configuration === undefined)
860
+ return this._helpConfiguration;
861
+ this._helpConfiguration = configuration;
862
+ return this;
863
+ }
864
+ configureOutput(configuration) {
865
+ if (configuration === undefined)
866
+ return this._outputConfiguration;
867
+ Object.assign(this._outputConfiguration, configuration);
868
+ return this;
869
+ }
870
+ showHelpAfterError(displayHelp = true) {
871
+ if (typeof displayHelp !== "string")
872
+ displayHelp = !!displayHelp;
873
+ this._showHelpAfterError = displayHelp;
874
+ return this;
875
+ }
876
+ showSuggestionAfterError(displaySuggestion = true) {
877
+ this._showSuggestionAfterError = !!displaySuggestion;
878
+ return this;
879
+ }
880
+ addCommand(cmd, opts) {
881
+ if (!cmd._name) {
882
+ throw new Error(`Command passed to .addCommand() must have a name
883
+ - specify the name in Command constructor or using .name()`);
884
+ }
885
+ opts = opts || {};
886
+ if (opts.isDefault)
887
+ this._defaultCommandName = cmd._name;
888
+ if (opts.noHelp || opts.hidden)
889
+ cmd._hidden = true;
890
+ this._registerCommand(cmd);
891
+ cmd.parent = this;
892
+ cmd._checkForBrokenPassThrough();
893
+ return this;
894
+ }
895
+ createArgument(name, description) {
896
+ return new Argument(name, description);
897
+ }
898
+ argument(name, description, fn, defaultValue) {
899
+ const argument = this.createArgument(name, description);
900
+ if (typeof fn === "function") {
901
+ argument.default(defaultValue).argParser(fn);
902
+ } else {
903
+ argument.default(fn);
904
+ }
905
+ this.addArgument(argument);
906
+ return this;
907
+ }
908
+ arguments(names) {
909
+ names.trim().split(/ +/).forEach((detail) => {
910
+ this.argument(detail);
911
+ });
912
+ return this;
913
+ }
914
+ addArgument(argument) {
915
+ const previousArgument = this.registeredArguments.slice(-1)[0];
916
+ if (previousArgument && previousArgument.variadic) {
917
+ throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);
918
+ }
919
+ if (argument.required && argument.defaultValue !== undefined && argument.parseArg === undefined) {
920
+ throw new Error(`a default value for a required argument is never used: '${argument.name()}'`);
921
+ }
922
+ this.registeredArguments.push(argument);
923
+ return this;
924
+ }
925
+ helpCommand(enableOrNameAndArgs, description) {
926
+ if (typeof enableOrNameAndArgs === "boolean") {
927
+ this._addImplicitHelpCommand = enableOrNameAndArgs;
928
+ return this;
929
+ }
930
+ enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
931
+ const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
932
+ const helpDescription = description ?? "display help for command";
933
+ const helpCommand = this.createCommand(helpName);
934
+ helpCommand.helpOption(false);
935
+ if (helpArgs)
936
+ helpCommand.arguments(helpArgs);
937
+ if (helpDescription)
938
+ helpCommand.description(helpDescription);
939
+ this._addImplicitHelpCommand = true;
940
+ this._helpCommand = helpCommand;
941
+ return this;
942
+ }
943
+ addHelpCommand(helpCommand, deprecatedDescription) {
944
+ if (typeof helpCommand !== "object") {
945
+ this.helpCommand(helpCommand, deprecatedDescription);
946
+ return this;
947
+ }
948
+ this._addImplicitHelpCommand = true;
949
+ this._helpCommand = helpCommand;
950
+ return this;
951
+ }
952
+ _getHelpCommand() {
953
+ const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
954
+ if (hasImplicitHelpCommand) {
955
+ if (this._helpCommand === undefined) {
956
+ this.helpCommand(undefined, undefined);
957
+ }
958
+ return this._helpCommand;
959
+ }
960
+ return null;
961
+ }
962
+ hook(event, listener) {
963
+ const allowedValues = ["preSubcommand", "preAction", "postAction"];
964
+ if (!allowedValues.includes(event)) {
965
+ throw new Error(`Unexpected value for event passed to hook : '${event}'.
966
+ Expecting one of '${allowedValues.join("', '")}'`);
967
+ }
968
+ if (this._lifeCycleHooks[event]) {
969
+ this._lifeCycleHooks[event].push(listener);
970
+ } else {
971
+ this._lifeCycleHooks[event] = [listener];
972
+ }
973
+ return this;
974
+ }
975
+ exitOverride(fn) {
976
+ if (fn) {
977
+ this._exitCallback = fn;
978
+ } else {
979
+ this._exitCallback = (err) => {
980
+ if (err.code !== "commander.executeSubCommandAsync") {
981
+ throw err;
982
+ }
983
+ };
984
+ }
985
+ return this;
986
+ }
987
+ _exit(exitCode, code, message) {
988
+ if (this._exitCallback) {
989
+ this._exitCallback(new CommanderError(exitCode, code, message));
990
+ }
991
+ process2.exit(exitCode);
992
+ }
993
+ action(fn) {
994
+ const listener = (args) => {
995
+ const expectedArgsCount = this.registeredArguments.length;
996
+ const actionArgs = args.slice(0, expectedArgsCount);
997
+ if (this._storeOptionsAsProperties) {
998
+ actionArgs[expectedArgsCount] = this;
999
+ } else {
1000
+ actionArgs[expectedArgsCount] = this.opts();
1001
+ }
1002
+ actionArgs.push(this);
1003
+ return fn.apply(this, actionArgs);
1004
+ };
1005
+ this._actionHandler = listener;
1006
+ return this;
1007
+ }
1008
+ createOption(flags, description) {
1009
+ return new Option(flags, description);
1010
+ }
1011
+ _callParseArg(target, value, previous, invalidArgumentMessage) {
1012
+ try {
1013
+ return target.parseArg(value, previous);
1014
+ } catch (err) {
1015
+ if (err.code === "commander.invalidArgument") {
1016
+ const message = `${invalidArgumentMessage} ${err.message}`;
1017
+ this.error(message, { exitCode: err.exitCode, code: err.code });
1018
+ }
1019
+ throw err;
1020
+ }
1021
+ }
1022
+ _registerOption(option) {
1023
+ const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1024
+ if (matchingOption) {
1025
+ const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1026
+ throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1027
+ - already used by option '${matchingOption.flags}'`);
1028
+ }
1029
+ this.options.push(option);
1030
+ }
1031
+ _registerCommand(command) {
1032
+ const knownBy = (cmd) => {
1033
+ return [cmd.name()].concat(cmd.aliases());
1034
+ };
1035
+ const alreadyUsed = knownBy(command).find((name) => this._findCommand(name));
1036
+ if (alreadyUsed) {
1037
+ const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1038
+ const newCmd = knownBy(command).join("|");
1039
+ throw new Error(`cannot add command '${newCmd}' as already have command '${existingCmd}'`);
1040
+ }
1041
+ this.commands.push(command);
1042
+ }
1043
+ addOption(option) {
1044
+ this._registerOption(option);
1045
+ const oname = option.name();
1046
+ const name = option.attributeName();
1047
+ if (option.negate) {
1048
+ const positiveLongFlag = option.long.replace(/^--no-/, "--");
1049
+ if (!this._findOption(positiveLongFlag)) {
1050
+ this.setOptionValueWithSource(name, option.defaultValue === undefined ? true : option.defaultValue, "default");
1051
+ }
1052
+ } else if (option.defaultValue !== undefined) {
1053
+ this.setOptionValueWithSource(name, option.defaultValue, "default");
1054
+ }
1055
+ const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1056
+ if (val == null && option.presetArg !== undefined) {
1057
+ val = option.presetArg;
1058
+ }
1059
+ const oldValue = this.getOptionValue(name);
1060
+ if (val !== null && option.parseArg) {
1061
+ val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1062
+ } else if (val !== null && option.variadic) {
1063
+ val = option._concatValue(val, oldValue);
1064
+ }
1065
+ if (val == null) {
1066
+ if (option.negate) {
1067
+ val = false;
1068
+ } else if (option.isBoolean() || option.optional) {
1069
+ val = true;
1070
+ } else {
1071
+ val = "";
1072
+ }
1073
+ }
1074
+ this.setOptionValueWithSource(name, val, valueSource);
1075
+ };
1076
+ this.on("option:" + oname, (val) => {
1077
+ const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1078
+ handleOptionValue(val, invalidValueMessage, "cli");
1079
+ });
1080
+ if (option.envVar) {
1081
+ this.on("optionEnv:" + oname, (val) => {
1082
+ const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1083
+ handleOptionValue(val, invalidValueMessage, "env");
1084
+ });
1085
+ }
1086
+ return this;
1087
+ }
1088
+ _optionEx(config, flags, description, fn, defaultValue) {
1089
+ if (typeof flags === "object" && flags instanceof Option) {
1090
+ throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");
1091
+ }
1092
+ const option = this.createOption(flags, description);
1093
+ option.makeOptionMandatory(!!config.mandatory);
1094
+ if (typeof fn === "function") {
1095
+ option.default(defaultValue).argParser(fn);
1096
+ } else if (fn instanceof RegExp) {
1097
+ const regex = fn;
1098
+ fn = (val, def) => {
1099
+ const m = regex.exec(val);
1100
+ return m ? m[0] : def;
1101
+ };
1102
+ option.default(defaultValue).argParser(fn);
1103
+ } else {
1104
+ option.default(fn);
1105
+ }
1106
+ return this.addOption(option);
1107
+ }
1108
+ option(flags, description, parseArg, defaultValue) {
1109
+ return this._optionEx({}, flags, description, parseArg, defaultValue);
1110
+ }
1111
+ requiredOption(flags, description, parseArg, defaultValue) {
1112
+ return this._optionEx({ mandatory: true }, flags, description, parseArg, defaultValue);
1113
+ }
1114
+ combineFlagAndOptionalValue(combine = true) {
1115
+ this._combineFlagAndOptionalValue = !!combine;
1116
+ return this;
1117
+ }
1118
+ allowUnknownOption(allowUnknown = true) {
1119
+ this._allowUnknownOption = !!allowUnknown;
1120
+ return this;
1121
+ }
1122
+ allowExcessArguments(allowExcess = true) {
1123
+ this._allowExcessArguments = !!allowExcess;
1124
+ return this;
1125
+ }
1126
+ enablePositionalOptions(positional = true) {
1127
+ this._enablePositionalOptions = !!positional;
1128
+ return this;
1129
+ }
1130
+ passThroughOptions(passThrough = true) {
1131
+ this._passThroughOptions = !!passThrough;
1132
+ this._checkForBrokenPassThrough();
1133
+ return this;
1134
+ }
1135
+ _checkForBrokenPassThrough() {
1136
+ if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1137
+ throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`);
1138
+ }
1139
+ }
1140
+ storeOptionsAsProperties(storeAsProperties = true) {
1141
+ if (this.options.length) {
1142
+ throw new Error("call .storeOptionsAsProperties() before adding options");
1143
+ }
1144
+ if (Object.keys(this._optionValues).length) {
1145
+ throw new Error("call .storeOptionsAsProperties() before setting option values");
1146
+ }
1147
+ this._storeOptionsAsProperties = !!storeAsProperties;
1148
+ return this;
1149
+ }
1150
+ getOptionValue(key) {
1151
+ if (this._storeOptionsAsProperties) {
1152
+ return this[key];
1153
+ }
1154
+ return this._optionValues[key];
1155
+ }
1156
+ setOptionValue(key, value) {
1157
+ return this.setOptionValueWithSource(key, value, undefined);
1158
+ }
1159
+ setOptionValueWithSource(key, value, source) {
1160
+ if (this._storeOptionsAsProperties) {
1161
+ this[key] = value;
1162
+ } else {
1163
+ this._optionValues[key] = value;
1164
+ }
1165
+ this._optionValueSources[key] = source;
1166
+ return this;
1167
+ }
1168
+ getOptionValueSource(key) {
1169
+ return this._optionValueSources[key];
1170
+ }
1171
+ getOptionValueSourceWithGlobals(key) {
1172
+ let source;
1173
+ this._getCommandAndAncestors().forEach((cmd) => {
1174
+ if (cmd.getOptionValueSource(key) !== undefined) {
1175
+ source = cmd.getOptionValueSource(key);
1176
+ }
1177
+ });
1178
+ return source;
1179
+ }
1180
+ _prepareUserArgs(argv, parseOptions) {
1181
+ if (argv !== undefined && !Array.isArray(argv)) {
1182
+ throw new Error("first parameter to parse must be array or undefined");
1183
+ }
1184
+ parseOptions = parseOptions || {};
1185
+ if (argv === undefined && parseOptions.from === undefined) {
1186
+ if (process2.versions?.electron) {
1187
+ parseOptions.from = "electron";
1188
+ }
1189
+ const execArgv = process2.execArgv ?? [];
1190
+ if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1191
+ parseOptions.from = "eval";
1192
+ }
1193
+ }
1194
+ if (argv === undefined) {
1195
+ argv = process2.argv;
1196
+ }
1197
+ this.rawArgs = argv.slice();
1198
+ let userArgs;
1199
+ switch (parseOptions.from) {
1200
+ case undefined:
1201
+ case "node":
1202
+ this._scriptPath = argv[1];
1203
+ userArgs = argv.slice(2);
1204
+ break;
1205
+ case "electron":
1206
+ if (process2.defaultApp) {
1207
+ this._scriptPath = argv[1];
1208
+ userArgs = argv.slice(2);
1209
+ } else {
1210
+ userArgs = argv.slice(1);
1211
+ }
1212
+ break;
1213
+ case "user":
1214
+ userArgs = argv.slice(0);
1215
+ break;
1216
+ case "eval":
1217
+ userArgs = argv.slice(1);
1218
+ break;
1219
+ default:
1220
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
1221
+ }
1222
+ if (!this._name && this._scriptPath)
1223
+ this.nameFromFilename(this._scriptPath);
1224
+ this._name = this._name || "program";
1225
+ return userArgs;
1226
+ }
1227
+ parse(argv, parseOptions) {
1228
+ this._prepareForParse();
1229
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1230
+ this._parseCommand([], userArgs);
1231
+ return this;
1232
+ }
1233
+ async parseAsync(argv, parseOptions) {
1234
+ this._prepareForParse();
1235
+ const userArgs = this._prepareUserArgs(argv, parseOptions);
1236
+ await this._parseCommand([], userArgs);
1237
+ return this;
1238
+ }
1239
+ _prepareForParse() {
1240
+ if (this._savedState === null) {
1241
+ this.saveStateBeforeParse();
1242
+ } else {
1243
+ this.restoreStateBeforeParse();
1244
+ }
1245
+ }
1246
+ saveStateBeforeParse() {
1247
+ this._savedState = {
1248
+ _name: this._name,
1249
+ _optionValues: { ...this._optionValues },
1250
+ _optionValueSources: { ...this._optionValueSources }
1251
+ };
1252
+ }
1253
+ restoreStateBeforeParse() {
1254
+ if (this._storeOptionsAsProperties)
1255
+ throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
1256
+ - either make a new Command for each call to parse, or stop storing options as properties`);
1257
+ this._name = this._savedState._name;
1258
+ this._scriptPath = null;
1259
+ this.rawArgs = [];
1260
+ this._optionValues = { ...this._savedState._optionValues };
1261
+ this._optionValueSources = { ...this._savedState._optionValueSources };
1262
+ this.args = [];
1263
+ this.processedArgs = [];
1264
+ }
1265
+ _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
1266
+ if (fs.existsSync(executableFile))
1267
+ return;
1268
+ 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";
1269
+ const executableMissing = `'${executableFile}' does not exist
1270
+ - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
1271
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
1272
+ - ${executableDirMessage}`;
1273
+ throw new Error(executableMissing);
1274
+ }
1275
+ _executeSubCommand(subcommand, args) {
1276
+ args = args.slice();
1277
+ let launchWithNode = false;
1278
+ const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
1279
+ function findFile(baseDir, baseName) {
1280
+ const localBin = path.resolve(baseDir, baseName);
1281
+ if (fs.existsSync(localBin))
1282
+ return localBin;
1283
+ if (sourceExt.includes(path.extname(baseName)))
1284
+ return;
1285
+ const foundExt = sourceExt.find((ext) => fs.existsSync(`${localBin}${ext}`));
1286
+ if (foundExt)
1287
+ return `${localBin}${foundExt}`;
1288
+ return;
1289
+ }
1290
+ this._checkForMissingMandatoryOptions();
1291
+ this._checkForConflictingOptions();
1292
+ let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
1293
+ let executableDir = this._executableDir || "";
1294
+ if (this._scriptPath) {
1295
+ let resolvedScriptPath;
1296
+ try {
1297
+ resolvedScriptPath = fs.realpathSync(this._scriptPath);
1298
+ } catch {
1299
+ resolvedScriptPath = this._scriptPath;
1300
+ }
1301
+ executableDir = path.resolve(path.dirname(resolvedScriptPath), executableDir);
1302
+ }
1303
+ if (executableDir) {
1304
+ let localFile = findFile(executableDir, executableFile);
1305
+ if (!localFile && !subcommand._executableFile && this._scriptPath) {
1306
+ const legacyName = path.basename(this._scriptPath, path.extname(this._scriptPath));
1307
+ if (legacyName !== this._name) {
1308
+ localFile = findFile(executableDir, `${legacyName}-${subcommand._name}`);
1309
+ }
1310
+ }
1311
+ executableFile = localFile || executableFile;
1312
+ }
1313
+ launchWithNode = sourceExt.includes(path.extname(executableFile));
1314
+ let proc;
1315
+ if (process2.platform !== "win32") {
1316
+ if (launchWithNode) {
1317
+ args.unshift(executableFile);
1318
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1319
+ proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
1320
+ } else {
1321
+ proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
1322
+ }
1323
+ } else {
1324
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1325
+ args.unshift(executableFile);
1326
+ args = incrementNodeInspectorPort(process2.execArgv).concat(args);
1327
+ proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
1328
+ }
1329
+ if (!proc.killed) {
1330
+ const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
1331
+ signals.forEach((signal) => {
1332
+ process2.on(signal, () => {
1333
+ if (proc.killed === false && proc.exitCode === null) {
1334
+ proc.kill(signal);
1335
+ }
1336
+ });
1337
+ });
1338
+ }
1339
+ const exitCallback = this._exitCallback;
1340
+ proc.on("close", (code) => {
1341
+ code = code ?? 1;
1342
+ if (!exitCallback) {
1343
+ process2.exit(code);
1344
+ } else {
1345
+ exitCallback(new CommanderError(code, "commander.executeSubCommandAsync", "(close)"));
1346
+ }
1347
+ });
1348
+ proc.on("error", (err) => {
1349
+ if (err.code === "ENOENT") {
1350
+ this._checkForMissingExecutable(executableFile, executableDir, subcommand._name);
1351
+ } else if (err.code === "EACCES") {
1352
+ throw new Error(`'${executableFile}' not executable`);
1353
+ }
1354
+ if (!exitCallback) {
1355
+ process2.exit(1);
1356
+ } else {
1357
+ const wrappedError = new CommanderError(1, "commander.executeSubCommandAsync", "(error)");
1358
+ wrappedError.nestedError = err;
1359
+ exitCallback(wrappedError);
1360
+ }
1361
+ });
1362
+ this.runningCommand = proc;
1363
+ }
1364
+ _dispatchSubcommand(commandName, operands, unknown) {
1365
+ const subCommand = this._findCommand(commandName);
1366
+ if (!subCommand)
1367
+ this.help({ error: true });
1368
+ subCommand._prepareForParse();
1369
+ let promiseChain;
1370
+ promiseChain = this._chainOrCallSubCommandHook(promiseChain, subCommand, "preSubcommand");
1371
+ promiseChain = this._chainOrCall(promiseChain, () => {
1372
+ if (subCommand._executableHandler) {
1373
+ this._executeSubCommand(subCommand, operands.concat(unknown));
1374
+ } else {
1375
+ return subCommand._parseCommand(operands, unknown);
1376
+ }
1377
+ });
1378
+ return promiseChain;
1379
+ }
1380
+ _dispatchHelpCommand(subcommandName) {
1381
+ if (!subcommandName) {
1382
+ this.help();
1383
+ }
1384
+ const subCommand = this._findCommand(subcommandName);
1385
+ if (subCommand && !subCommand._executableHandler) {
1386
+ subCommand.help();
1387
+ }
1388
+ return this._dispatchSubcommand(subcommandName, [], [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]);
1389
+ }
1390
+ _checkNumberOfArguments() {
1391
+ this.registeredArguments.forEach((arg, i) => {
1392
+ if (arg.required && this.args[i] == null) {
1393
+ this.missingArgument(arg.name());
1394
+ }
1395
+ });
1396
+ if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
1397
+ return;
1398
+ }
1399
+ if (this.args.length > this.registeredArguments.length) {
1400
+ this._excessArguments(this.args);
1401
+ }
1402
+ }
1403
+ _processArguments() {
1404
+ const myParseArg = (argument, value, previous) => {
1405
+ let parsedValue = value;
1406
+ if (value !== null && argument.parseArg) {
1407
+ const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
1408
+ parsedValue = this._callParseArg(argument, value, previous, invalidValueMessage);
1409
+ }
1410
+ return parsedValue;
1411
+ };
1412
+ this._checkNumberOfArguments();
1413
+ const processedArgs = [];
1414
+ this.registeredArguments.forEach((declaredArg, index) => {
1415
+ let value = declaredArg.defaultValue;
1416
+ if (declaredArg.variadic) {
1417
+ if (index < this.args.length) {
1418
+ value = this.args.slice(index);
1419
+ if (declaredArg.parseArg) {
1420
+ value = value.reduce((processed, v) => {
1421
+ return myParseArg(declaredArg, v, processed);
1422
+ }, declaredArg.defaultValue);
1423
+ }
1424
+ } else if (value === undefined) {
1425
+ value = [];
1426
+ }
1427
+ } else if (index < this.args.length) {
1428
+ value = this.args[index];
1429
+ if (declaredArg.parseArg) {
1430
+ value = myParseArg(declaredArg, value, declaredArg.defaultValue);
1431
+ }
1432
+ }
1433
+ processedArgs[index] = value;
1434
+ });
1435
+ this.processedArgs = processedArgs;
1436
+ }
1437
+ _chainOrCall(promise, fn) {
1438
+ if (promise && promise.then && typeof promise.then === "function") {
1439
+ return promise.then(() => fn());
1440
+ }
1441
+ return fn();
1442
+ }
1443
+ _chainOrCallHooks(promise, event) {
1444
+ let result = promise;
1445
+ const hooks = [];
1446
+ this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== undefined).forEach((hookedCommand) => {
1447
+ hookedCommand._lifeCycleHooks[event].forEach((callback) => {
1448
+ hooks.push({ hookedCommand, callback });
1449
+ });
1450
+ });
1451
+ if (event === "postAction") {
1452
+ hooks.reverse();
1453
+ }
1454
+ hooks.forEach((hookDetail) => {
1455
+ result = this._chainOrCall(result, () => {
1456
+ return hookDetail.callback(hookDetail.hookedCommand, this);
1457
+ });
1458
+ });
1459
+ return result;
1460
+ }
1461
+ _chainOrCallSubCommandHook(promise, subCommand, event) {
1462
+ let result = promise;
1463
+ if (this._lifeCycleHooks[event] !== undefined) {
1464
+ this._lifeCycleHooks[event].forEach((hook) => {
1465
+ result = this._chainOrCall(result, () => {
1466
+ return hook(this, subCommand);
1467
+ });
1468
+ });
1469
+ }
1470
+ return result;
1471
+ }
1472
+ _parseCommand(operands, unknown) {
1473
+ const parsed = this.parseOptions(unknown);
1474
+ this._parseOptionsEnv();
1475
+ this._parseOptionsImplied();
1476
+ operands = operands.concat(parsed.operands);
1477
+ unknown = parsed.unknown;
1478
+ this.args = operands.concat(unknown);
1479
+ if (operands && this._findCommand(operands[0])) {
1480
+ return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
1481
+ }
1482
+ if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
1483
+ return this._dispatchHelpCommand(operands[1]);
1484
+ }
1485
+ if (this._defaultCommandName) {
1486
+ this._outputHelpIfRequested(unknown);
1487
+ return this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
1488
+ }
1489
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
1490
+ this.help({ error: true });
1491
+ }
1492
+ this._outputHelpIfRequested(parsed.unknown);
1493
+ this._checkForMissingMandatoryOptions();
1494
+ this._checkForConflictingOptions();
1495
+ const checkForUnknownOptions = () => {
1496
+ if (parsed.unknown.length > 0) {
1497
+ this.unknownOption(parsed.unknown[0]);
1498
+ }
1499
+ };
1500
+ const commandEvent = `command:${this.name()}`;
1501
+ if (this._actionHandler) {
1502
+ checkForUnknownOptions();
1503
+ this._processArguments();
1504
+ let promiseChain;
1505
+ promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
1506
+ promiseChain = this._chainOrCall(promiseChain, () => this._actionHandler(this.processedArgs));
1507
+ if (this.parent) {
1508
+ promiseChain = this._chainOrCall(promiseChain, () => {
1509
+ this.parent.emit(commandEvent, operands, unknown);
1510
+ });
1511
+ }
1512
+ promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
1513
+ return promiseChain;
1514
+ }
1515
+ if (this.parent && this.parent.listenerCount(commandEvent)) {
1516
+ checkForUnknownOptions();
1517
+ this._processArguments();
1518
+ this.parent.emit(commandEvent, operands, unknown);
1519
+ } else if (operands.length) {
1520
+ if (this._findCommand("*")) {
1521
+ return this._dispatchSubcommand("*", operands, unknown);
1522
+ }
1523
+ if (this.listenerCount("command:*")) {
1524
+ this.emit("command:*", operands, unknown);
1525
+ } else if (this.commands.length) {
1526
+ this.unknownCommand();
1527
+ } else {
1528
+ checkForUnknownOptions();
1529
+ this._processArguments();
1530
+ }
1531
+ } else if (this.commands.length) {
1532
+ checkForUnknownOptions();
1533
+ this.help({ error: true });
1534
+ } else {
1535
+ checkForUnknownOptions();
1536
+ this._processArguments();
1537
+ }
1538
+ }
1539
+ _findCommand(name) {
1540
+ if (!name)
1541
+ return;
1542
+ return this.commands.find((cmd) => cmd._name === name || cmd._aliases.includes(name));
1543
+ }
1544
+ _findOption(arg) {
1545
+ return this.options.find((option) => option.is(arg));
1546
+ }
1547
+ _checkForMissingMandatoryOptions() {
1548
+ this._getCommandAndAncestors().forEach((cmd) => {
1549
+ cmd.options.forEach((anOption) => {
1550
+ if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === undefined) {
1551
+ cmd.missingMandatoryOptionValue(anOption);
1552
+ }
1553
+ });
1554
+ });
1555
+ }
1556
+ _checkForConflictingLocalOptions() {
1557
+ const definedNonDefaultOptions = this.options.filter((option) => {
1558
+ const optionKey = option.attributeName();
1559
+ if (this.getOptionValue(optionKey) === undefined) {
1560
+ return false;
1561
+ }
1562
+ return this.getOptionValueSource(optionKey) !== "default";
1563
+ });
1564
+ const optionsWithConflicting = definedNonDefaultOptions.filter((option) => option.conflictsWith.length > 0);
1565
+ optionsWithConflicting.forEach((option) => {
1566
+ const conflictingAndDefined = definedNonDefaultOptions.find((defined) => option.conflictsWith.includes(defined.attributeName()));
1567
+ if (conflictingAndDefined) {
1568
+ this._conflictingOption(option, conflictingAndDefined);
1569
+ }
1570
+ });
1571
+ }
1572
+ _checkForConflictingOptions() {
1573
+ this._getCommandAndAncestors().forEach((cmd) => {
1574
+ cmd._checkForConflictingLocalOptions();
1575
+ });
1576
+ }
1577
+ parseOptions(argv) {
1578
+ const operands = [];
1579
+ const unknown = [];
1580
+ let dest = operands;
1581
+ const args = argv.slice();
1582
+ function maybeOption(arg) {
1583
+ return arg.length > 1 && arg[0] === "-";
1584
+ }
1585
+ let activeVariadicOption = null;
1586
+ while (args.length) {
1587
+ const arg = args.shift();
1588
+ if (arg === "--") {
1589
+ if (dest === unknown)
1590
+ dest.push(arg);
1591
+ dest.push(...args);
1592
+ break;
1593
+ }
1594
+ if (activeVariadicOption && !maybeOption(arg)) {
1595
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
1596
+ continue;
1597
+ }
1598
+ activeVariadicOption = null;
1599
+ if (maybeOption(arg)) {
1600
+ const option = this._findOption(arg);
1601
+ if (option) {
1602
+ if (option.required) {
1603
+ const value = args.shift();
1604
+ if (value === undefined)
1605
+ this.optionMissingArgument(option);
1606
+ this.emit(`option:${option.name()}`, value);
1607
+ } else if (option.optional) {
1608
+ let value = null;
1609
+ if (args.length > 0 && !maybeOption(args[0])) {
1610
+ value = args.shift();
1611
+ }
1612
+ this.emit(`option:${option.name()}`, value);
1613
+ } else {
1614
+ this.emit(`option:${option.name()}`);
1615
+ }
1616
+ activeVariadicOption = option.variadic ? option : null;
1617
+ continue;
1618
+ }
1619
+ }
1620
+ if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
1621
+ const option = this._findOption(`-${arg[1]}`);
1622
+ if (option) {
1623
+ if (option.required || option.optional && this._combineFlagAndOptionalValue) {
1624
+ this.emit(`option:${option.name()}`, arg.slice(2));
1625
+ } else {
1626
+ this.emit(`option:${option.name()}`);
1627
+ args.unshift(`-${arg.slice(2)}`);
1628
+ }
1629
+ continue;
1630
+ }
1631
+ }
1632
+ if (/^--[^=]+=/.test(arg)) {
1633
+ const index = arg.indexOf("=");
1634
+ const option = this._findOption(arg.slice(0, index));
1635
+ if (option && (option.required || option.optional)) {
1636
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
1637
+ continue;
1638
+ }
1639
+ }
1640
+ if (maybeOption(arg)) {
1641
+ dest = unknown;
1642
+ }
1643
+ if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
1644
+ if (this._findCommand(arg)) {
1645
+ operands.push(arg);
1646
+ if (args.length > 0)
1647
+ unknown.push(...args);
1648
+ break;
1649
+ } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
1650
+ operands.push(arg);
1651
+ if (args.length > 0)
1652
+ operands.push(...args);
1653
+ break;
1654
+ } else if (this._defaultCommandName) {
1655
+ unknown.push(arg);
1656
+ if (args.length > 0)
1657
+ unknown.push(...args);
1658
+ break;
1659
+ }
1660
+ }
1661
+ if (this._passThroughOptions) {
1662
+ dest.push(arg);
1663
+ if (args.length > 0)
1664
+ dest.push(...args);
1665
+ break;
1666
+ }
1667
+ dest.push(arg);
1668
+ }
1669
+ return { operands, unknown };
1670
+ }
1671
+ opts() {
1672
+ if (this._storeOptionsAsProperties) {
1673
+ const result = {};
1674
+ const len = this.options.length;
1675
+ for (let i = 0;i < len; i++) {
1676
+ const key = this.options[i].attributeName();
1677
+ result[key] = key === this._versionOptionName ? this._version : this[key];
1678
+ }
1679
+ return result;
1680
+ }
1681
+ return this._optionValues;
1682
+ }
1683
+ optsWithGlobals() {
1684
+ return this._getCommandAndAncestors().reduce((combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), {});
1685
+ }
1686
+ error(message, errorOptions) {
1687
+ this._outputConfiguration.outputError(`${message}
1688
+ `, this._outputConfiguration.writeErr);
1689
+ if (typeof this._showHelpAfterError === "string") {
1690
+ this._outputConfiguration.writeErr(`${this._showHelpAfterError}
1691
+ `);
1692
+ } else if (this._showHelpAfterError) {
1693
+ this._outputConfiguration.writeErr(`
1694
+ `);
1695
+ this.outputHelp({ error: true });
1696
+ }
1697
+ const config = errorOptions || {};
1698
+ const exitCode = config.exitCode || 1;
1699
+ const code = config.code || "commander.error";
1700
+ this._exit(exitCode, code, message);
1701
+ }
1702
+ _parseOptionsEnv() {
1703
+ this.options.forEach((option) => {
1704
+ if (option.envVar && option.envVar in process2.env) {
1705
+ const optionKey = option.attributeName();
1706
+ if (this.getOptionValue(optionKey) === undefined || ["default", "config", "env"].includes(this.getOptionValueSource(optionKey))) {
1707
+ if (option.required || option.optional) {
1708
+ this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
1709
+ } else {
1710
+ this.emit(`optionEnv:${option.name()}`);
1711
+ }
1712
+ }
1713
+ }
1714
+ });
1715
+ }
1716
+ _parseOptionsImplied() {
1717
+ const dualHelper = new DualOptions(this.options);
1718
+ const hasCustomOptionValue = (optionKey) => {
1719
+ return this.getOptionValue(optionKey) !== undefined && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
1720
+ };
1721
+ this.options.filter((option) => option.implied !== undefined && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(this.getOptionValue(option.attributeName()), option)).forEach((option) => {
1722
+ Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
1723
+ this.setOptionValueWithSource(impliedKey, option.implied[impliedKey], "implied");
1724
+ });
1725
+ });
1726
+ }
1727
+ missingArgument(name) {
1728
+ const message = `error: missing required argument '${name}'`;
1729
+ this.error(message, { code: "commander.missingArgument" });
1730
+ }
1731
+ optionMissingArgument(option) {
1732
+ const message = `error: option '${option.flags}' argument missing`;
1733
+ this.error(message, { code: "commander.optionMissingArgument" });
1734
+ }
1735
+ missingMandatoryOptionValue(option) {
1736
+ const message = `error: required option '${option.flags}' not specified`;
1737
+ this.error(message, { code: "commander.missingMandatoryOptionValue" });
1738
+ }
1739
+ _conflictingOption(option, conflictingOption) {
1740
+ const findBestOptionFromValue = (option2) => {
1741
+ const optionKey = option2.attributeName();
1742
+ const optionValue = this.getOptionValue(optionKey);
1743
+ const negativeOption = this.options.find((target) => target.negate && optionKey === target.attributeName());
1744
+ const positiveOption = this.options.find((target) => !target.negate && optionKey === target.attributeName());
1745
+ if (negativeOption && (negativeOption.presetArg === undefined && optionValue === false || negativeOption.presetArg !== undefined && optionValue === negativeOption.presetArg)) {
1746
+ return negativeOption;
1747
+ }
1748
+ return positiveOption || option2;
1749
+ };
1750
+ const getErrorMessage = (option2) => {
1751
+ const bestOption = findBestOptionFromValue(option2);
1752
+ const optionKey = bestOption.attributeName();
1753
+ const source = this.getOptionValueSource(optionKey);
1754
+ if (source === "env") {
1755
+ return `environment variable '${bestOption.envVar}'`;
1756
+ }
1757
+ return `option '${bestOption.flags}'`;
1758
+ };
1759
+ const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
1760
+ this.error(message, { code: "commander.conflictingOption" });
1761
+ }
1762
+ unknownOption(flag) {
1763
+ if (this._allowUnknownOption)
1764
+ return;
1765
+ let suggestion = "";
1766
+ if (flag.startsWith("--") && this._showSuggestionAfterError) {
1767
+ let candidateFlags = [];
1768
+ let command = this;
1769
+ do {
1770
+ const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
1771
+ candidateFlags = candidateFlags.concat(moreFlags);
1772
+ command = command.parent;
1773
+ } while (command && !command._enablePositionalOptions);
1774
+ suggestion = suggestSimilar(flag, candidateFlags);
1775
+ }
1776
+ const message = `error: unknown option '${flag}'${suggestion}`;
1777
+ this.error(message, { code: "commander.unknownOption" });
1778
+ }
1779
+ _excessArguments(receivedArgs) {
1780
+ if (this._allowExcessArguments)
1781
+ return;
1782
+ const expected = this.registeredArguments.length;
1783
+ const s = expected === 1 ? "" : "s";
1784
+ const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
1785
+ const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
1786
+ this.error(message, { code: "commander.excessArguments" });
1787
+ }
1788
+ unknownCommand() {
1789
+ const unknownName = this.args[0];
1790
+ let suggestion = "";
1791
+ if (this._showSuggestionAfterError) {
1792
+ const candidateNames = [];
1793
+ this.createHelp().visibleCommands(this).forEach((command) => {
1794
+ candidateNames.push(command.name());
1795
+ if (command.alias())
1796
+ candidateNames.push(command.alias());
1797
+ });
1798
+ suggestion = suggestSimilar(unknownName, candidateNames);
1799
+ }
1800
+ const message = `error: unknown command '${unknownName}'${suggestion}`;
1801
+ this.error(message, { code: "commander.unknownCommand" });
1802
+ }
1803
+ version(str, flags, description) {
1804
+ if (str === undefined)
1805
+ return this._version;
1806
+ this._version = str;
1807
+ flags = flags || "-V, --version";
1808
+ description = description || "output the version number";
1809
+ const versionOption = this.createOption(flags, description);
1810
+ this._versionOptionName = versionOption.attributeName();
1811
+ this._registerOption(versionOption);
1812
+ this.on("option:" + versionOption.name(), () => {
1813
+ this._outputConfiguration.writeOut(`${str}
1814
+ `);
1815
+ this._exit(0, "commander.version", str);
1816
+ });
1817
+ return this;
1818
+ }
1819
+ description(str, argsDescription) {
1820
+ if (str === undefined && argsDescription === undefined)
1821
+ return this._description;
1822
+ this._description = str;
1823
+ if (argsDescription) {
1824
+ this._argsDescription = argsDescription;
1825
+ }
1826
+ return this;
1827
+ }
1828
+ summary(str) {
1829
+ if (str === undefined)
1830
+ return this._summary;
1831
+ this._summary = str;
1832
+ return this;
1833
+ }
1834
+ alias(alias) {
1835
+ if (alias === undefined)
1836
+ return this._aliases[0];
1837
+ let command = this;
1838
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
1839
+ command = this.commands[this.commands.length - 1];
1840
+ }
1841
+ if (alias === command._name)
1842
+ throw new Error("Command alias can't be the same as its name");
1843
+ const matchingCommand = this.parent?._findCommand(alias);
1844
+ if (matchingCommand) {
1845
+ const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
1846
+ throw new Error(`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`);
1847
+ }
1848
+ command._aliases.push(alias);
1849
+ return this;
1850
+ }
1851
+ aliases(aliases) {
1852
+ if (aliases === undefined)
1853
+ return this._aliases;
1854
+ aliases.forEach((alias) => this.alias(alias));
1855
+ return this;
1856
+ }
1857
+ usage(str) {
1858
+ if (str === undefined) {
1859
+ if (this._usage)
1860
+ return this._usage;
1861
+ const args = this.registeredArguments.map((arg) => {
1862
+ return humanReadableArgName(arg);
1863
+ });
1864
+ return [].concat(this.options.length || this._helpOption !== null ? "[options]" : [], this.commands.length ? "[command]" : [], this.registeredArguments.length ? args : []).join(" ");
1865
+ }
1866
+ this._usage = str;
1867
+ return this;
1868
+ }
1869
+ name(str) {
1870
+ if (str === undefined)
1871
+ return this._name;
1872
+ this._name = str;
1873
+ return this;
1874
+ }
1875
+ nameFromFilename(filename) {
1876
+ this._name = path.basename(filename, path.extname(filename));
1877
+ return this;
1878
+ }
1879
+ executableDir(path2) {
1880
+ if (path2 === undefined)
1881
+ return this._executableDir;
1882
+ this._executableDir = path2;
1883
+ return this;
1884
+ }
1885
+ helpInformation(contextOptions) {
1886
+ const helper = this.createHelp();
1887
+ const context = this._getOutputContext(contextOptions);
1888
+ helper.prepareContext({
1889
+ error: context.error,
1890
+ helpWidth: context.helpWidth,
1891
+ outputHasColors: context.hasColors
1892
+ });
1893
+ const text = helper.formatHelp(this, helper);
1894
+ if (context.hasColors)
1895
+ return text;
1896
+ return this._outputConfiguration.stripColor(text);
1897
+ }
1898
+ _getOutputContext(contextOptions) {
1899
+ contextOptions = contextOptions || {};
1900
+ const error = !!contextOptions.error;
1901
+ let baseWrite;
1902
+ let hasColors;
1903
+ let helpWidth;
1904
+ if (error) {
1905
+ baseWrite = (str) => this._outputConfiguration.writeErr(str);
1906
+ hasColors = this._outputConfiguration.getErrHasColors();
1907
+ helpWidth = this._outputConfiguration.getErrHelpWidth();
1908
+ } else {
1909
+ baseWrite = (str) => this._outputConfiguration.writeOut(str);
1910
+ hasColors = this._outputConfiguration.getOutHasColors();
1911
+ helpWidth = this._outputConfiguration.getOutHelpWidth();
1912
+ }
1913
+ const write = (str) => {
1914
+ if (!hasColors)
1915
+ str = this._outputConfiguration.stripColor(str);
1916
+ return baseWrite(str);
1917
+ };
1918
+ return { error, write, hasColors, helpWidth };
1919
+ }
1920
+ outputHelp(contextOptions) {
1921
+ let deprecatedCallback;
1922
+ if (typeof contextOptions === "function") {
1923
+ deprecatedCallback = contextOptions;
1924
+ contextOptions = undefined;
1925
+ }
1926
+ const outputContext = this._getOutputContext(contextOptions);
1927
+ const eventContext = {
1928
+ error: outputContext.error,
1929
+ write: outputContext.write,
1930
+ command: this
1931
+ };
1932
+ this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
1933
+ this.emit("beforeHelp", eventContext);
1934
+ let helpInformation = this.helpInformation({ error: outputContext.error });
1935
+ if (deprecatedCallback) {
1936
+ helpInformation = deprecatedCallback(helpInformation);
1937
+ if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
1938
+ throw new Error("outputHelp callback must return a string or a Buffer");
1939
+ }
1940
+ }
1941
+ outputContext.write(helpInformation);
1942
+ if (this._getHelpOption()?.long) {
1943
+ this.emit(this._getHelpOption().long);
1944
+ }
1945
+ this.emit("afterHelp", eventContext);
1946
+ this._getCommandAndAncestors().forEach((command) => command.emit("afterAllHelp", eventContext));
1947
+ }
1948
+ helpOption(flags, description) {
1949
+ if (typeof flags === "boolean") {
1950
+ if (flags) {
1951
+ this._helpOption = this._helpOption ?? undefined;
1952
+ } else {
1953
+ this._helpOption = null;
1954
+ }
1955
+ return this;
1956
+ }
1957
+ flags = flags ?? "-h, --help";
1958
+ description = description ?? "display help for command";
1959
+ this._helpOption = this.createOption(flags, description);
1960
+ return this;
1961
+ }
1962
+ _getHelpOption() {
1963
+ if (this._helpOption === undefined) {
1964
+ this.helpOption(undefined, undefined);
1965
+ }
1966
+ return this._helpOption;
1967
+ }
1968
+ addHelpOption(option) {
1969
+ this._helpOption = option;
1970
+ return this;
1971
+ }
1972
+ help(contextOptions) {
1973
+ this.outputHelp(contextOptions);
1974
+ let exitCode = Number(process2.exitCode ?? 0);
1975
+ if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
1976
+ exitCode = 1;
1977
+ }
1978
+ this._exit(exitCode, "commander.help", "(outputHelp)");
1979
+ }
1980
+ addHelpText(position, text) {
1981
+ const allowedValues = ["beforeAll", "before", "after", "afterAll"];
1982
+ if (!allowedValues.includes(position)) {
1983
+ throw new Error(`Unexpected value for position to addHelpText.
1984
+ Expecting one of '${allowedValues.join("', '")}'`);
1985
+ }
1986
+ const helpEvent = `${position}Help`;
1987
+ this.on(helpEvent, (context) => {
1988
+ let helpStr;
1989
+ if (typeof text === "function") {
1990
+ helpStr = text({ error: context.error, command: context.command });
1991
+ } else {
1992
+ helpStr = text;
1993
+ }
1994
+ if (helpStr) {
1995
+ context.write(`${helpStr}
1996
+ `);
1997
+ }
1998
+ });
1999
+ return this;
2000
+ }
2001
+ _outputHelpIfRequested(args) {
2002
+ const helpOption = this._getHelpOption();
2003
+ const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
2004
+ if (helpRequested) {
2005
+ this.outputHelp();
2006
+ this._exit(0, "commander.helpDisplayed", "(outputHelp)");
2007
+ }
2008
+ }
2009
+ }
2010
+ function incrementNodeInspectorPort(args) {
2011
+ return args.map((arg) => {
2012
+ if (!arg.startsWith("--inspect")) {
2013
+ return arg;
2014
+ }
2015
+ let debugOption;
2016
+ let debugHost = "127.0.0.1";
2017
+ let debugPort = "9229";
2018
+ let match;
2019
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
2020
+ debugOption = match[1];
2021
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
2022
+ debugOption = match[1];
2023
+ if (/^\d+$/.test(match[3])) {
2024
+ debugPort = match[3];
2025
+ } else {
2026
+ debugHost = match[3];
2027
+ }
2028
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
2029
+ debugOption = match[1];
2030
+ debugHost = match[3];
2031
+ debugPort = match[4];
2032
+ }
2033
+ if (debugOption && debugPort !== "0") {
2034
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
2035
+ }
2036
+ return arg;
2037
+ });
2038
+ }
2039
+ function useColor() {
2040
+ if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
2041
+ return false;
2042
+ if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== undefined)
2043
+ return true;
2044
+ return;
2045
+ }
2046
+ exports.Command = Command;
2047
+ exports.useColor = useColor;
2048
+ });
2049
+
2050
+ // node_modules/commander/index.js
2051
+ var require_commander = __commonJS((exports) => {
2052
+ var { Argument } = require_argument();
2053
+ var { Command } = require_command();
2054
+ var { CommanderError, InvalidArgumentError } = require_error();
2055
+ var { Help } = require_help();
2056
+ var { Option } = require_option();
2057
+ exports.program = new Command;
2058
+ exports.createCommand = (name) => new Command(name);
2059
+ exports.createOption = (flags, description) => new Option(flags, description);
2060
+ exports.createArgument = (name, description) => new Argument(name, description);
2061
+ exports.Command = Command;
2062
+ exports.Option = Option;
2063
+ exports.Argument = Argument;
2064
+ exports.Help = Help;
2065
+ exports.CommanderError = CommanderError;
2066
+ exports.InvalidArgumentError = InvalidArgumentError;
2067
+ exports.InvalidOptionArgumentError = InvalidArgumentError;
2068
+ });
2069
+
2070
+ // node_modules/commander/esm.mjs
2071
+ var import__ = __toESM(require_commander(), 1);
2072
+ var {
2073
+ program,
2074
+ createCommand,
2075
+ createArgument,
2076
+ createOption,
2077
+ CommanderError,
2078
+ InvalidArgumentError,
2079
+ InvalidOptionArgumentError,
2080
+ Command,
2081
+ Argument,
2082
+ Option,
2083
+ Help
2084
+ } = import__.default;
2085
+
2086
+ // node_modules/chalk/source/vendor/ansi-styles/index.js
2087
+ var ANSI_BACKGROUND_OFFSET = 10;
2088
+ var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
2089
+ var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
2090
+ var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
2091
+ var styles = {
2092
+ modifier: {
2093
+ reset: [0, 0],
2094
+ bold: [1, 22],
2095
+ dim: [2, 22],
2096
+ italic: [3, 23],
2097
+ underline: [4, 24],
2098
+ overline: [53, 55],
2099
+ inverse: [7, 27],
2100
+ hidden: [8, 28],
2101
+ strikethrough: [9, 29]
2102
+ },
2103
+ color: {
2104
+ black: [30, 39],
2105
+ red: [31, 39],
2106
+ green: [32, 39],
2107
+ yellow: [33, 39],
2108
+ blue: [34, 39],
2109
+ magenta: [35, 39],
2110
+ cyan: [36, 39],
2111
+ white: [37, 39],
2112
+ blackBright: [90, 39],
2113
+ gray: [90, 39],
2114
+ grey: [90, 39],
2115
+ redBright: [91, 39],
2116
+ greenBright: [92, 39],
2117
+ yellowBright: [93, 39],
2118
+ blueBright: [94, 39],
2119
+ magentaBright: [95, 39],
2120
+ cyanBright: [96, 39],
2121
+ whiteBright: [97, 39]
2122
+ },
2123
+ bgColor: {
2124
+ bgBlack: [40, 49],
2125
+ bgRed: [41, 49],
2126
+ bgGreen: [42, 49],
2127
+ bgYellow: [43, 49],
2128
+ bgBlue: [44, 49],
2129
+ bgMagenta: [45, 49],
2130
+ bgCyan: [46, 49],
2131
+ bgWhite: [47, 49],
2132
+ bgBlackBright: [100, 49],
2133
+ bgGray: [100, 49],
2134
+ bgGrey: [100, 49],
2135
+ bgRedBright: [101, 49],
2136
+ bgGreenBright: [102, 49],
2137
+ bgYellowBright: [103, 49],
2138
+ bgBlueBright: [104, 49],
2139
+ bgMagentaBright: [105, 49],
2140
+ bgCyanBright: [106, 49],
2141
+ bgWhiteBright: [107, 49]
2142
+ }
2143
+ };
2144
+ var modifierNames = Object.keys(styles.modifier);
2145
+ var foregroundColorNames = Object.keys(styles.color);
2146
+ var backgroundColorNames = Object.keys(styles.bgColor);
2147
+ var colorNames = [...foregroundColorNames, ...backgroundColorNames];
2148
+ function assembleStyles() {
2149
+ const codes = new Map;
2150
+ for (const [groupName, group] of Object.entries(styles)) {
2151
+ for (const [styleName, style] of Object.entries(group)) {
2152
+ styles[styleName] = {
2153
+ open: `\x1B[${style[0]}m`,
2154
+ close: `\x1B[${style[1]}m`
2155
+ };
2156
+ group[styleName] = styles[styleName];
2157
+ codes.set(style[0], style[1]);
2158
+ }
2159
+ Object.defineProperty(styles, groupName, {
2160
+ value: group,
2161
+ enumerable: false
2162
+ });
2163
+ }
2164
+ Object.defineProperty(styles, "codes", {
2165
+ value: codes,
2166
+ enumerable: false
2167
+ });
2168
+ styles.color.close = "\x1B[39m";
2169
+ styles.bgColor.close = "\x1B[49m";
2170
+ styles.color.ansi = wrapAnsi16();
2171
+ styles.color.ansi256 = wrapAnsi256();
2172
+ styles.color.ansi16m = wrapAnsi16m();
2173
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
2174
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
2175
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
2176
+ Object.defineProperties(styles, {
2177
+ rgbToAnsi256: {
2178
+ value(red, green, blue) {
2179
+ if (red === green && green === blue) {
2180
+ if (red < 8) {
2181
+ return 16;
2182
+ }
2183
+ if (red > 248) {
2184
+ return 231;
2185
+ }
2186
+ return Math.round((red - 8) / 247 * 24) + 232;
2187
+ }
2188
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
2189
+ },
2190
+ enumerable: false
2191
+ },
2192
+ hexToRgb: {
2193
+ value(hex) {
2194
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
2195
+ if (!matches) {
2196
+ return [0, 0, 0];
2197
+ }
2198
+ let [colorString] = matches;
2199
+ if (colorString.length === 3) {
2200
+ colorString = [...colorString].map((character) => character + character).join("");
2201
+ }
2202
+ const integer = Number.parseInt(colorString, 16);
2203
+ return [
2204
+ integer >> 16 & 255,
2205
+ integer >> 8 & 255,
2206
+ integer & 255
2207
+ ];
2208
+ },
2209
+ enumerable: false
2210
+ },
2211
+ hexToAnsi256: {
2212
+ value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)),
2213
+ enumerable: false
2214
+ },
2215
+ ansi256ToAnsi: {
2216
+ value(code) {
2217
+ if (code < 8) {
2218
+ return 30 + code;
2219
+ }
2220
+ if (code < 16) {
2221
+ return 90 + (code - 8);
2222
+ }
2223
+ let red;
2224
+ let green;
2225
+ let blue;
2226
+ if (code >= 232) {
2227
+ red = ((code - 232) * 10 + 8) / 255;
2228
+ green = red;
2229
+ blue = red;
2230
+ } else {
2231
+ code -= 16;
2232
+ const remainder = code % 36;
2233
+ red = Math.floor(code / 36) / 5;
2234
+ green = Math.floor(remainder / 6) / 5;
2235
+ blue = remainder % 6 / 5;
2236
+ }
2237
+ const value = Math.max(red, green, blue) * 2;
2238
+ if (value === 0) {
2239
+ return 30;
2240
+ }
2241
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
2242
+ if (value === 2) {
2243
+ result += 60;
2244
+ }
2245
+ return result;
2246
+ },
2247
+ enumerable: false
2248
+ },
2249
+ rgbToAnsi: {
2250
+ value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
2251
+ enumerable: false
2252
+ },
2253
+ hexToAnsi: {
2254
+ value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),
2255
+ enumerable: false
2256
+ }
2257
+ });
2258
+ return styles;
2259
+ }
2260
+ var ansiStyles = assembleStyles();
2261
+ var ansi_styles_default = ansiStyles;
2262
+
2263
+ // node_modules/chalk/source/vendor/supports-color/index.js
2264
+ import process2 from "process";
2265
+ import os from "os";
2266
+ import tty from "tty";
2267
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process2.argv) {
2268
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
2269
+ const position = argv.indexOf(prefix + flag);
2270
+ const terminatorPosition = argv.indexOf("--");
2271
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
2272
+ }
2273
+ var { env } = process2;
2274
+ var flagForceColor;
2275
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
2276
+ flagForceColor = 0;
2277
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
2278
+ flagForceColor = 1;
2279
+ }
2280
+ function envForceColor() {
2281
+ if ("FORCE_COLOR" in env) {
2282
+ if (env.FORCE_COLOR === "true") {
2283
+ return 1;
2284
+ }
2285
+ if (env.FORCE_COLOR === "false") {
2286
+ return 0;
2287
+ }
2288
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
2289
+ }
2290
+ }
2291
+ function translateLevel(level) {
2292
+ if (level === 0) {
2293
+ return false;
2294
+ }
2295
+ return {
2296
+ level,
2297
+ hasBasic: true,
2298
+ has256: level >= 2,
2299
+ has16m: level >= 3
2300
+ };
2301
+ }
2302
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
2303
+ const noFlagForceColor = envForceColor();
2304
+ if (noFlagForceColor !== undefined) {
2305
+ flagForceColor = noFlagForceColor;
2306
+ }
2307
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
2308
+ if (forceColor === 0) {
2309
+ return 0;
2310
+ }
2311
+ if (sniffFlags) {
2312
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
2313
+ return 3;
2314
+ }
2315
+ if (hasFlag("color=256")) {
2316
+ return 2;
2317
+ }
2318
+ }
2319
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
2320
+ return 1;
2321
+ }
2322
+ if (haveStream && !streamIsTTY && forceColor === undefined) {
2323
+ return 0;
2324
+ }
2325
+ const min = forceColor || 0;
2326
+ if (env.TERM === "dumb") {
2327
+ return min;
2328
+ }
2329
+ if (process2.platform === "win32") {
2330
+ const osRelease = os.release().split(".");
2331
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
2332
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
2333
+ }
2334
+ return 1;
2335
+ }
2336
+ if ("CI" in env) {
2337
+ if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => (key in env))) {
2338
+ return 3;
2339
+ }
2340
+ if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => (sign in env)) || env.CI_NAME === "codeship") {
2341
+ return 1;
2342
+ }
2343
+ return min;
2344
+ }
2345
+ if ("TEAMCITY_VERSION" in env) {
2346
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
2347
+ }
2348
+ if (env.COLORTERM === "truecolor") {
2349
+ return 3;
2350
+ }
2351
+ if (env.TERM === "xterm-kitty") {
2352
+ return 3;
2353
+ }
2354
+ if (env.TERM === "xterm-ghostty") {
2355
+ return 3;
2356
+ }
2357
+ if (env.TERM === "wezterm") {
2358
+ return 3;
2359
+ }
2360
+ if ("TERM_PROGRAM" in env) {
2361
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
2362
+ switch (env.TERM_PROGRAM) {
2363
+ case "iTerm.app": {
2364
+ return version >= 3 ? 3 : 2;
2365
+ }
2366
+ case "Apple_Terminal": {
2367
+ return 2;
2368
+ }
2369
+ }
2370
+ }
2371
+ if (/-256(color)?$/i.test(env.TERM)) {
2372
+ return 2;
2373
+ }
2374
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
2375
+ return 1;
2376
+ }
2377
+ if ("COLORTERM" in env) {
2378
+ return 1;
2379
+ }
2380
+ return min;
2381
+ }
2382
+ function createSupportsColor(stream, options = {}) {
2383
+ const level = _supportsColor(stream, {
2384
+ streamIsTTY: stream && stream.isTTY,
2385
+ ...options
2386
+ });
2387
+ return translateLevel(level);
2388
+ }
2389
+ var supportsColor = {
2390
+ stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
2391
+ stderr: createSupportsColor({ isTTY: tty.isatty(2) })
2392
+ };
2393
+ var supports_color_default = supportsColor;
2394
+
2395
+ // node_modules/chalk/source/utilities.js
2396
+ function stringReplaceAll(string, substring, replacer) {
2397
+ let index = string.indexOf(substring);
2398
+ if (index === -1) {
2399
+ return string;
2400
+ }
2401
+ const substringLength = substring.length;
2402
+ let endIndex = 0;
2403
+ let returnValue = "";
2404
+ do {
2405
+ returnValue += string.slice(endIndex, index) + substring + replacer;
2406
+ endIndex = index + substringLength;
2407
+ index = string.indexOf(substring, endIndex);
2408
+ } while (index !== -1);
2409
+ returnValue += string.slice(endIndex);
2410
+ return returnValue;
2411
+ }
2412
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
2413
+ let endIndex = 0;
2414
+ let returnValue = "";
2415
+ do {
2416
+ const gotCR = string[index - 1] === "\r";
2417
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? `\r
2418
+ ` : `
2419
+ `) + postfix;
2420
+ endIndex = index + 1;
2421
+ index = string.indexOf(`
2422
+ `, endIndex);
2423
+ } while (index !== -1);
2424
+ returnValue += string.slice(endIndex);
2425
+ return returnValue;
2426
+ }
2427
+
2428
+ // node_modules/chalk/source/index.js
2429
+ var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
2430
+ var GENERATOR = Symbol("GENERATOR");
2431
+ var STYLER = Symbol("STYLER");
2432
+ var IS_EMPTY = Symbol("IS_EMPTY");
2433
+ var levelMapping = [
2434
+ "ansi",
2435
+ "ansi",
2436
+ "ansi256",
2437
+ "ansi16m"
2438
+ ];
2439
+ var styles2 = Object.create(null);
2440
+ var applyOptions = (object, options = {}) => {
2441
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
2442
+ throw new Error("The `level` option should be an integer from 0 to 3");
2443
+ }
2444
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
2445
+ object.level = options.level === undefined ? colorLevel : options.level;
2446
+ };
2447
+ var chalkFactory = (options) => {
2448
+ const chalk = (...strings) => strings.join(" ");
2449
+ applyOptions(chalk, options);
2450
+ Object.setPrototypeOf(chalk, createChalk.prototype);
2451
+ return chalk;
2452
+ };
2453
+ function createChalk(options) {
2454
+ return chalkFactory(options);
2455
+ }
2456
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
2457
+ for (const [styleName, style] of Object.entries(ansi_styles_default)) {
2458
+ styles2[styleName] = {
2459
+ get() {
2460
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
2461
+ Object.defineProperty(this, styleName, { value: builder });
2462
+ return builder;
2463
+ }
2464
+ };
2465
+ }
2466
+ styles2.visible = {
2467
+ get() {
2468
+ const builder = createBuilder(this, this[STYLER], true);
2469
+ Object.defineProperty(this, "visible", { value: builder });
2470
+ return builder;
2471
+ }
2472
+ };
2473
+ var getModelAnsi = (model, level, type, ...arguments_) => {
2474
+ if (model === "rgb") {
2475
+ if (level === "ansi16m") {
2476
+ return ansi_styles_default[type].ansi16m(...arguments_);
2477
+ }
2478
+ if (level === "ansi256") {
2479
+ return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
2480
+ }
2481
+ return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
2482
+ }
2483
+ if (model === "hex") {
2484
+ return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
2485
+ }
2486
+ return ansi_styles_default[type][model](...arguments_);
2487
+ };
2488
+ var usedModels = ["rgb", "hex", "ansi256"];
2489
+ for (const model of usedModels) {
2490
+ styles2[model] = {
2491
+ get() {
2492
+ const { level } = this;
2493
+ return function(...arguments_) {
2494
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
2495
+ return createBuilder(this, styler, this[IS_EMPTY]);
2496
+ };
2497
+ }
2498
+ };
2499
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
2500
+ styles2[bgModel] = {
2501
+ get() {
2502
+ const { level } = this;
2503
+ return function(...arguments_) {
2504
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
2505
+ return createBuilder(this, styler, this[IS_EMPTY]);
2506
+ };
2507
+ }
2508
+ };
2509
+ }
2510
+ var proto = Object.defineProperties(() => {}, {
2511
+ ...styles2,
2512
+ level: {
2513
+ enumerable: true,
2514
+ get() {
2515
+ return this[GENERATOR].level;
2516
+ },
2517
+ set(level) {
2518
+ this[GENERATOR].level = level;
2519
+ }
2520
+ }
2521
+ });
2522
+ var createStyler = (open, close, parent) => {
2523
+ let openAll;
2524
+ let closeAll;
2525
+ if (parent === undefined) {
2526
+ openAll = open;
2527
+ closeAll = close;
2528
+ } else {
2529
+ openAll = parent.openAll + open;
2530
+ closeAll = close + parent.closeAll;
2531
+ }
2532
+ return {
2533
+ open,
2534
+ close,
2535
+ openAll,
2536
+ closeAll,
2537
+ parent
2538
+ };
2539
+ };
2540
+ var createBuilder = (self, _styler, _isEmpty) => {
2541
+ const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
2542
+ Object.setPrototypeOf(builder, proto);
2543
+ builder[GENERATOR] = self;
2544
+ builder[STYLER] = _styler;
2545
+ builder[IS_EMPTY] = _isEmpty;
2546
+ return builder;
2547
+ };
2548
+ var applyStyle = (self, string) => {
2549
+ if (self.level <= 0 || !string) {
2550
+ return self[IS_EMPTY] ? "" : string;
2551
+ }
2552
+ let styler = self[STYLER];
2553
+ if (styler === undefined) {
2554
+ return string;
2555
+ }
2556
+ const { openAll, closeAll } = styler;
2557
+ if (string.includes("\x1B")) {
2558
+ while (styler !== undefined) {
2559
+ string = stringReplaceAll(string, styler.close, styler.open);
2560
+ styler = styler.parent;
2561
+ }
2562
+ }
2563
+ const lfIndex = string.indexOf(`
2564
+ `);
2565
+ if (lfIndex !== -1) {
2566
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
2567
+ }
2568
+ return openAll + string + closeAll;
2569
+ };
2570
+ Object.defineProperties(createChalk.prototype, styles2);
2571
+ var chalk = createChalk();
2572
+ var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
2573
+ var source_default = chalk;
2574
+
2575
+ // src/cli/index.ts
2576
+ import { randomUUID as randomUUID2 } from "crypto";
2577
+ import { existsSync, readFileSync as readFileSync2, rmSync, statSync } from "fs";
2578
+ import { dirname as dirname4, join as join3 } from "path";
2579
+ import { fileURLToPath } from "url";
2580
+
2581
+ // src/version.ts
2582
+ function getPackageVersion() {
2583
+ return "0.0.1";
2584
+ }
2585
+
2586
+ // src/auth.ts
2587
+ import { mkdirSync, readFileSync, writeFileSync } from "fs";
2588
+ import { dirname } from "path";
2589
+ import { spawnSync } from "child_process";
2590
+
2591
+ // src/paths.ts
2592
+ import { homedir } from "os";
2593
+ import { join } from "path";
2594
+ function getModelsHome() {
2595
+ return process.env["HASNA_MODELS_HOME"] || join(homedir(), ".hasna", "models");
2596
+ }
2597
+ function getDbPath() {
2598
+ return process.env["HASNA_MODELS_DB"] || join(getModelsHome(), "models.db");
2599
+ }
2600
+ function getAuthConfigPath() {
2601
+ return join(getModelsHome(), "auth.json");
2602
+ }
2603
+ function getInstallRoot() {
2604
+ return process.env["HASNA_MODELS_INSTALLS"] || join(getModelsHome(), "installs");
2605
+ }
2606
+
2607
+ // src/auth.ts
2608
+ var HF_ENV_KEYS = [
2609
+ "HF_TOKEN",
2610
+ "HUGGINGFACE_HUB_TOKEN",
2611
+ "HUGGING_FACE_HUB_TOKEN",
2612
+ "HUGGINGFACE_TOKEN"
2613
+ ];
2614
+ var DEFAULT_HF_SECRET_KEYS = [
2615
+ "huggingface/token",
2616
+ "huggingface/live/token",
2617
+ "hf/token"
2618
+ ];
2619
+ var cachedResolution = null;
2620
+ function readAuthConfig() {
2621
+ try {
2622
+ return JSON.parse(readFileSync(getAuthConfigPath(), "utf8"));
2623
+ } catch {
2624
+ return {};
2625
+ }
2626
+ }
2627
+ function writeAuthConfig(config) {
2628
+ const path = getAuthConfigPath();
2629
+ mkdirSync(dirname(path), { recursive: true });
2630
+ writeFileSync(path, `${JSON.stringify(config, null, 2)}
2631
+ `);
2632
+ }
2633
+ function fromEnv() {
2634
+ for (const key of HF_ENV_KEYS) {
2635
+ const value = process.env[key]?.trim();
2636
+ if (value)
2637
+ return value;
2638
+ }
2639
+ return null;
2640
+ }
2641
+ function readSecret(key) {
2642
+ const result = spawnSync("secrets", ["get", key], {
2643
+ encoding: "utf8",
2644
+ env: process.env,
2645
+ timeout: 1e4,
2646
+ stdio: ["ignore", "pipe", "pipe"]
2647
+ });
2648
+ if (result.status !== 0)
2649
+ return null;
2650
+ const value = result.stdout.trim();
2651
+ return value || null;
2652
+ }
2653
+ function secretCandidates(config) {
2654
+ const configured = [
2655
+ process.env["HASNA_MODELS_HF_SECRET_KEY"],
2656
+ process.env["HF_SECRET_KEY"],
2657
+ config.huggingface?.secretKey
2658
+ ].filter((value) => Boolean(value?.trim()));
2659
+ return [...new Set([...configured, ...DEFAULT_HF_SECRET_KEYS])];
2660
+ }
2661
+ function redactAuthStatus(status) {
2662
+ const { secretKey: _secretKey, ...rest } = status;
2663
+ return rest;
2664
+ }
2665
+ function resolveHuggingFaceToken() {
2666
+ if (cachedResolution)
2667
+ return cachedResolution;
2668
+ const envToken = fromEnv();
2669
+ if (envToken) {
2670
+ cachedResolution = { token: envToken, status: { provider: "huggingface", available: true, source: "env" } };
2671
+ return cachedResolution;
2672
+ }
2673
+ const config = readAuthConfig();
2674
+ const configToken = config.huggingface?.token?.trim();
2675
+ if (configToken) {
2676
+ cachedResolution = { token: configToken, status: { provider: "huggingface", available: true, source: "config" } };
2677
+ return cachedResolution;
2678
+ }
2679
+ for (const key of secretCandidates(config)) {
2680
+ const token = readSecret(key);
2681
+ if (token) {
2682
+ cachedResolution = {
2683
+ token,
2684
+ status: {
2685
+ provider: "huggingface",
2686
+ available: true,
2687
+ source: "secrets",
2688
+ secretKey: key
2689
+ }
2690
+ };
2691
+ return cachedResolution;
2692
+ }
2693
+ }
2694
+ cachedResolution = { token: null, status: { provider: "huggingface", available: false, source: "none" } };
2695
+ return cachedResolution;
2696
+ }
2697
+ function getHuggingFaceAuthStatus() {
2698
+ return redactAuthStatus(resolveHuggingFaceToken().status);
2699
+ }
2700
+ function saveHuggingFaceSecretRef(secretKey) {
2701
+ const config = readAuthConfig();
2702
+ config.huggingface = { ...config.huggingface, secretKey };
2703
+ delete config.huggingface.token;
2704
+ writeAuthConfig(config);
2705
+ cachedResolution = null;
2706
+ return redactAuthStatus({ provider: "huggingface", available: Boolean(readSecret(secretKey)), source: "secrets", secretKey });
2707
+ }
2708
+
2709
+ // src/ref.ts
2710
+ var ENTITY_KINDS = new Set(["model", "dataset", "space"]);
2711
+ var PROVIDER_ALIASES = new Map([
2712
+ ["hf", "huggingface"],
2713
+ ["huggingface", "huggingface"]
2714
+ ]);
2715
+ function parseEntityKind(value) {
2716
+ if (ENTITY_KINDS.has(value))
2717
+ return value;
2718
+ throw new Error(`Unsupported entity kind: ${value}. Expected one of: ${[...ENTITY_KINDS].join(", ")}`);
2719
+ }
2720
+ function parseProviderRef(input, defaultKind = "model") {
2721
+ const trimmed = input.trim();
2722
+ if (!trimmed)
2723
+ throw new Error("model or dataset ref is required");
2724
+ let provider = "huggingface";
2725
+ let entityKind = parseEntityKind(defaultKind);
2726
+ let rest = trimmed;
2727
+ const prefixMatch = rest.match(/^([a-zA-Z][a-zA-Z0-9+.-]*):(.*)$/);
2728
+ if (prefixMatch && !prefixMatch[1].includes("/")) {
2729
+ const alias = PROVIDER_ALIASES.get(prefixMatch[1]);
2730
+ if (alias) {
2731
+ provider = alias;
2732
+ rest = prefixMatch[2];
2733
+ } else if (["model", "dataset", "space"].includes(prefixMatch[1])) {
2734
+ entityKind = parseEntityKind(prefixMatch[1]);
2735
+ rest = prefixMatch[2];
2736
+ } else {
2737
+ throw new Error(`Unsupported provider: ${prefixMatch[1]}`);
2738
+ }
2739
+ }
2740
+ if (rest.startsWith("model:")) {
2741
+ entityKind = parseEntityKind("model");
2742
+ rest = rest.slice("model:".length);
2743
+ } else if (rest.startsWith("dataset:")) {
2744
+ entityKind = parseEntityKind("dataset");
2745
+ rest = rest.slice("dataset:".length);
2746
+ } else if (rest.startsWith("space:")) {
2747
+ entityKind = parseEntityKind("space");
2748
+ rest = rest.slice("space:".length);
2749
+ }
2750
+ if (rest.includes(":")) {
2751
+ throw new Error(`Unsupported ref prefix in: ${input}`);
2752
+ }
2753
+ let revision = "main";
2754
+ const atIndex = rest.lastIndexOf("@");
2755
+ if (atIndex > 0) {
2756
+ revision = rest.slice(atIndex + 1);
2757
+ rest = rest.slice(0, atIndex);
2758
+ if (!revision.trim())
2759
+ throw new Error(`Revision cannot be empty in ref: ${input}`);
2760
+ } else if (rest.endsWith("@")) {
2761
+ throw new Error(`Revision cannot be empty in ref: ${input}`);
2762
+ }
2763
+ if (!rest.includes("/")) {
2764
+ throw new Error(`Expected a namespaced repo id such as owner/name, got ${input}`);
2765
+ }
2766
+ return { provider, entityKind, repoId: rest, revision };
2767
+ }
2768
+ function formatProviderRef(ref) {
2769
+ const prefix = ref.provider === "huggingface" ? "hf" : ref.provider;
2770
+ const kind = ref.entityKind === "model" ? "" : `${ref.entityKind}:`;
2771
+ return `${prefix}:${kind}${ref.repoId}@${ref.revision}`;
2772
+ }
2773
+ function encodeRepoId(repoId) {
2774
+ return repoId.split("/").map(encodeURIComponent).join("/");
2775
+ }
2776
+ function safePathSegment(value) {
2777
+ return value.replace(/[^a-zA-Z0-9._-]+/g, "__").replace(/^_+|_+$/g, "") || "unnamed";
2778
+ }
2779
+
2780
+ // src/huggingface.ts
2781
+ import { createWriteStream, mkdirSync as mkdirSync2, renameSync, unlinkSync } from "fs";
2782
+ import { dirname as dirname2, isAbsolute, join as join2, resolve, sep } from "path";
2783
+ import { pipeline } from "stream/promises";
2784
+ import { Readable } from "stream";
2785
+ import { randomUUID } from "crypto";
2786
+ var HF_ENDPOINT = process.env["HF_ENDPOINT"] || "https://huggingface.co";
2787
+ function apiBase() {
2788
+ return HF_ENDPOINT.replace(/\/+$/, "");
2789
+ }
2790
+ function headers() {
2791
+ const { token } = resolveHuggingFaceToken();
2792
+ return token ? { Authorization: `Bearer ${token}` } : {};
2793
+ }
2794
+ async function hfJson(path, init) {
2795
+ const response = await fetch(`${apiBase()}${path}`, {
2796
+ ...init,
2797
+ headers: {
2798
+ ...headers(),
2799
+ ...init?.headers ?? {}
2800
+ }
2801
+ });
2802
+ if (!response.ok) {
2803
+ const text = await response.text().catch(() => "");
2804
+ throw new Error(`Hugging Face request failed ${response.status} ${response.statusText}: ${text.slice(0, 300)}`);
2805
+ }
2806
+ return response.json();
2807
+ }
2808
+ function apiKind(kind) {
2809
+ if (kind === "dataset")
2810
+ return "datasets";
2811
+ if (kind === "space")
2812
+ return "spaces";
2813
+ return "models";
2814
+ }
2815
+ function canonicalUrl(kind, repoId) {
2816
+ const base = apiBase();
2817
+ if (kind === "dataset")
2818
+ return `${base}/datasets/${repoId}`;
2819
+ if (kind === "space")
2820
+ return `${base}/spaces/${repoId}`;
2821
+ return `${base}/${repoId}`;
2822
+ }
2823
+ function extractLicense(tags, cardData) {
2824
+ const licenseTag = tags.find((tag) => tag.startsWith("license:"));
2825
+ if (licenseTag)
2826
+ return licenseTag.slice("license:".length);
2827
+ if (cardData && typeof cardData === "object" && "license" in cardData) {
2828
+ const raw = cardData.license;
2829
+ if (Array.isArray(raw))
2830
+ return raw.map(String).join(",");
2831
+ if (typeof raw === "string")
2832
+ return raw;
2833
+ }
2834
+ return null;
2835
+ }
2836
+ function detectFormat(path) {
2837
+ const lower = path.toLowerCase();
2838
+ if (lower.endsWith(".gguf"))
2839
+ return "gguf";
2840
+ if (lower.endsWith(".safetensors"))
2841
+ return "safetensors";
2842
+ if (lower.endsWith(".bin"))
2843
+ return "pytorch-bin";
2844
+ if (lower.endsWith(".onnx"))
2845
+ return "onnx";
2846
+ if (lower.endsWith(".h5"))
2847
+ return "tensorflow";
2848
+ if (lower.endsWith(".msgpack"))
2849
+ return "flax";
2850
+ if (lower.endsWith(".parquet"))
2851
+ return "parquet";
2852
+ if (lower.endsWith(".csv"))
2853
+ return "csv";
2854
+ if (lower.endsWith(".tsv"))
2855
+ return "tsv";
2856
+ if (lower.endsWith(".txt"))
2857
+ return "text";
2858
+ if (lower.endsWith(".arrow"))
2859
+ return "arrow";
2860
+ if (lower.endsWith(".jsonl"))
2861
+ return "jsonl";
2862
+ if (lower.endsWith(".json"))
2863
+ return "json";
2864
+ return null;
2865
+ }
2866
+ function safeDestinationPath(root, filePath) {
2867
+ if (isAbsolute(filePath))
2868
+ throw new Error(`Unsafe remote file path: ${filePath}`);
2869
+ if (/^[a-zA-Z]:[\\/]/.test(filePath))
2870
+ throw new Error(`Unsafe remote file path: ${filePath}`);
2871
+ const segments = filePath.split(/[\\/]+/);
2872
+ if (segments.some((segment) => segment === ".." || segment === "")) {
2873
+ throw new Error(`Unsafe remote file path: ${filePath}`);
2874
+ }
2875
+ const resolvedRoot = resolve(root);
2876
+ const destination = resolve(resolvedRoot, ...segments);
2877
+ if (destination !== resolvedRoot && !destination.startsWith(`${resolvedRoot}${sep}`)) {
2878
+ throw new Error(`Remote file path escapes install root: ${filePath}`);
2879
+ }
2880
+ return destination;
2881
+ }
2882
+ function normalizeEntry(raw, kind) {
2883
+ const repoId = String(raw.id ?? raw.modelId ?? "");
2884
+ const tags = Array.isArray(raw.tags) ? raw.tags.map(String) : [];
2885
+ const cardData = raw.cardData;
2886
+ return {
2887
+ provider: "huggingface",
2888
+ entityKind: kind,
2889
+ repoId,
2890
+ revision: String(raw.sha ?? "main"),
2891
+ canonicalUrl: canonicalUrl(kind, repoId),
2892
+ title: repoId,
2893
+ author: typeof raw.author === "string" ? raw.author : repoId.split("/")[0],
2894
+ task: typeof raw.pipeline_tag === "string" ? raw.pipeline_tag : null,
2895
+ libraryName: typeof raw.library_name === "string" ? raw.library_name : null,
2896
+ license: extractLicense(tags, cardData),
2897
+ gated: Boolean(raw.gated),
2898
+ private: Boolean(raw.private),
2899
+ downloads: typeof raw.downloads === "number" ? raw.downloads : null,
2900
+ likes: typeof raw.likes === "number" ? raw.likes : null,
2901
+ tags,
2902
+ lastModified: typeof raw.lastModified === "string" ? raw.lastModified : null,
2903
+ metadata: raw
2904
+ };
2905
+ }
2906
+ function normalizeTreeFile(raw, ref) {
2907
+ if (raw.type && raw.type !== "file")
2908
+ return null;
2909
+ const path = String(raw.path ?? raw.rfilename ?? "");
2910
+ if (!path)
2911
+ return null;
2912
+ const lfs = raw.lfs && typeof raw.lfs === "object" ? raw.lfs : {};
2913
+ const size = typeof raw.size === "number" ? raw.size : typeof lfs.size === "number" ? lfs.size : null;
2914
+ return {
2915
+ provider: "huggingface",
2916
+ entityKind: ref.entityKind,
2917
+ repoId: ref.repoId,
2918
+ revision: ref.revision,
2919
+ path,
2920
+ size,
2921
+ oid: typeof raw.oid === "string" ? raw.oid : null,
2922
+ lfsOid: typeof lfs.oid === "string" ? lfs.oid : null,
2923
+ format: detectFormat(path),
2924
+ downloadUrl: fileDownloadUrl(ref, path),
2925
+ metadata: raw
2926
+ };
2927
+ }
2928
+ function normalizeSibling(raw, ref) {
2929
+ const path = String(raw.rfilename ?? raw.path ?? "");
2930
+ if (!path)
2931
+ return null;
2932
+ return {
2933
+ provider: "huggingface",
2934
+ entityKind: ref.entityKind,
2935
+ repoId: ref.repoId,
2936
+ revision: ref.revision,
2937
+ path,
2938
+ size: typeof raw.size === "number" ? raw.size : null,
2939
+ oid: typeof raw.oid === "string" ? raw.oid : null,
2940
+ lfsOid: null,
2941
+ format: detectFormat(path),
2942
+ downloadUrl: fileDownloadUrl(ref, path),
2943
+ metadata: raw
2944
+ };
2945
+ }
2946
+ function fileDownloadUrl(ref, path) {
2947
+ const encodedRepo = encodeRepoId(ref.repoId);
2948
+ const encodedRevision = encodeURIComponent(ref.revision || "main");
2949
+ const encodedPath = path.split("/").map(encodeURIComponent).join("/");
2950
+ const prefix = ref.entityKind === "dataset" ? "datasets/" : ref.entityKind === "space" ? "spaces/" : "";
2951
+ return `${apiBase()}/${prefix}${encodedRepo}/resolve/${encodedRevision}/${encodedPath}`;
2952
+ }
2953
+ async function searchHuggingFace(input = {}) {
2954
+ const kind = input.entityKind ?? "model";
2955
+ const params = new URLSearchParams;
2956
+ if (input.query)
2957
+ params.set("search", input.query);
2958
+ params.set("limit", String(input.limit ?? 20));
2959
+ params.set("full", "1");
2960
+ params.set("sort", input.sort ?? "downloads");
2961
+ params.set("direction", input.direction === "asc" ? "1" : "-1");
2962
+ if (input.task)
2963
+ params.append("filter", input.task);
2964
+ if (input.license)
2965
+ params.append("filter", `license:${input.license}`);
2966
+ for (const tag of input.tags ?? [])
2967
+ params.append("filter", tag);
2968
+ const raw = await hfJson(`/api/${apiKind(kind)}?${params.toString()}`);
2969
+ return raw.map((entry) => normalizeEntry(entry, kind)).filter((entry) => Boolean(entry.repoId));
2970
+ }
2971
+ async function getHuggingFaceInfo(refOrInput, defaultKind = "model") {
2972
+ const ref = typeof refOrInput === "string" ? parseProviderRef(refOrInput, defaultKind) : refOrInput;
2973
+ const raw = await hfJson(`/api/${apiKind(ref.entityKind)}/${encodeRepoId(ref.repoId)}`);
2974
+ return normalizeEntry(raw, ref.entityKind);
2975
+ }
2976
+ async function listHuggingFaceFiles(refOrInput, defaultKind = "model") {
2977
+ const ref = typeof refOrInput === "string" ? parseProviderRef(refOrInput, defaultKind) : refOrInput;
2978
+ const treePath = `/api/${apiKind(ref.entityKind)}/${encodeRepoId(ref.repoId)}/tree/${encodeURIComponent(ref.revision)}?recursive=1&expand=1`;
2979
+ try {
2980
+ const raw = await hfJson(treePath);
2981
+ return raw.map((entry) => normalizeTreeFile(entry, ref)).filter((entry) => Boolean(entry));
2982
+ } catch {
2983
+ const info = await hfJson(`/api/${apiKind(ref.entityKind)}/${encodeRepoId(ref.repoId)}`);
2984
+ const siblings = Array.isArray(info.siblings) ? info.siblings : [];
2985
+ return siblings.map((entry) => normalizeSibling(entry, ref)).filter((entry) => Boolean(entry));
2986
+ }
2987
+ }
2988
+ function matchesFilePattern(path, pattern) {
2989
+ const normalized = pattern.trim();
2990
+ if (!normalized)
2991
+ return false;
2992
+ if (normalized === path)
2993
+ return true;
2994
+ if (normalized.endsWith("/"))
2995
+ return path.startsWith(normalized);
2996
+ if (normalized.includes("*")) {
2997
+ const regex = new RegExp(`^${normalized.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*")}$`);
2998
+ return regex.test(path);
2999
+ }
3000
+ if (!normalized.includes("/")) {
3001
+ return path.split("/").pop() === normalized;
3002
+ }
3003
+ return false;
3004
+ }
3005
+ function matchAny(path, patterns) {
3006
+ if (patterns.length === 0)
3007
+ return true;
3008
+ return patterns.some((pattern) => matchesFilePattern(path, pattern));
3009
+ }
3010
+ async function createDownloadPlan(input) {
3011
+ const include = input.include ?? [];
3012
+ const exclude = input.exclude ?? [];
3013
+ const files = (await listHuggingFaceFiles(input.ref)).filter((file) => include.length === 0 || matchAny(file.path, include)).filter((file) => exclude.length === 0 || !matchAny(file.path, exclude));
3014
+ const knownBytes = files.reduce((sum, file) => sum + (file.size ?? 0), 0);
3015
+ const unknownSizeFiles = files.filter((file) => file.size == null).map((file) => file.path);
3016
+ const totalBytes = unknownSizeFiles.length > 0 ? null : knownBytes;
3017
+ const maxBytes = input.maxBytes ?? null;
3018
+ const destinationRoot = input.destinationRoot ?? join2(getInstallRoot(), input.ref.provider, input.ref.entityKind, safePathSegment(input.ref.repoId), safePathSegment(input.ref.revision));
3019
+ return {
3020
+ ref: input.ref,
3021
+ files,
3022
+ totalBytes,
3023
+ unknownSizeFiles,
3024
+ destinationRoot,
3025
+ exceedsMaxBytes: maxBytes != null && totalBytes != null && totalBytes > maxBytes,
3026
+ maxBytes
3027
+ };
3028
+ }
3029
+ async function downloadPlannedFiles(plan) {
3030
+ if (plan.exceedsMaxBytes) {
3031
+ throw new Error(`Download plan exceeds max bytes: ${plan.totalBytes} > ${plan.maxBytes}`);
3032
+ }
3033
+ if (plan.maxBytes != null && plan.unknownSizeFiles.length > 0) {
3034
+ throw new Error(`Download plan has unknown-size files under a byte cap: ${plan.unknownSizeFiles.join(", ")}`);
3035
+ }
3036
+ const downloaded = [];
3037
+ for (const file of plan.files) {
3038
+ const destination = safeDestinationPath(plan.destinationRoot, file.path);
3039
+ const tempDestination = `${destination}.partial-${randomUUID()}`;
3040
+ mkdirSync2(dirname2(destination), { recursive: true });
3041
+ const response = await fetch(file.downloadUrl, { headers: headers(), redirect: "follow" });
3042
+ if (!response.ok || !response.body) {
3043
+ const text = await response.text().catch(() => "");
3044
+ throw new Error(`Failed to download ${file.path}: ${response.status} ${response.statusText} ${text.slice(0, 200)}`);
3045
+ }
3046
+ try {
3047
+ await pipeline(Readable.fromWeb(response.body), createWriteStream(tempDestination));
3048
+ renameSync(tempDestination, destination);
3049
+ const bytes = file.size ?? Bun.file(destination).size;
3050
+ downloaded.push({ path: file.path, bytes, destination });
3051
+ } catch (error) {
3052
+ try {
3053
+ unlinkSync(tempDestination);
3054
+ } catch {}
3055
+ throw error;
3056
+ }
3057
+ }
3058
+ return downloaded;
3059
+ }
3060
+
3061
+ // src/storage.ts
3062
+ import { mkdirSync as mkdirSync3 } from "fs";
3063
+ import { dirname as dirname3 } from "path";
3064
+ import { Database } from "bun:sqlite";
3065
+ var SCHEMA_VERSION = 1;
3066
+
3067
+ class ModelsStore {
3068
+ db;
3069
+ constructor(path = getDbPath()) {
3070
+ mkdirSync3(dirname3(path), { recursive: true });
3071
+ this.db = new Database(path, { create: true });
3072
+ this.db.run("PRAGMA busy_timeout = 5000");
3073
+ this.db.run("PRAGMA journal_mode = WAL");
3074
+ this.migrate();
3075
+ }
3076
+ close() {
3077
+ this.db.close();
3078
+ }
3079
+ migrate() {
3080
+ this.db.run(`
3081
+ CREATE TABLE IF NOT EXISTS schema_meta (
3082
+ key TEXT PRIMARY KEY,
3083
+ value INTEGER NOT NULL
3084
+ )
3085
+ `);
3086
+ const row = this.db.query("SELECT value FROM schema_meta WHERE key = 'schema_version' LIMIT 1").get();
3087
+ const currentVersion = row ? Number(row.value) : 0;
3088
+ if (currentVersion >= SCHEMA_VERSION)
3089
+ return;
3090
+ this.db.run(`
3091
+ CREATE TABLE IF NOT EXISTS catalog_entries (
3092
+ provider TEXT NOT NULL,
3093
+ entity_kind TEXT NOT NULL,
3094
+ repo_id TEXT NOT NULL,
3095
+ revision TEXT NOT NULL,
3096
+ title TEXT NOT NULL,
3097
+ author TEXT,
3098
+ task TEXT,
3099
+ library_name TEXT,
3100
+ license TEXT,
3101
+ gated INTEGER NOT NULL,
3102
+ private INTEGER NOT NULL,
3103
+ downloads INTEGER,
3104
+ likes INTEGER,
3105
+ tags_json TEXT NOT NULL,
3106
+ metadata_json TEXT NOT NULL,
3107
+ canonical_url TEXT NOT NULL,
3108
+ last_modified TEXT,
3109
+ indexed_at TEXT NOT NULL,
3110
+ PRIMARY KEY (provider, entity_kind, repo_id, revision)
3111
+ )
3112
+ `);
3113
+ this.db.run(`
3114
+ CREATE TABLE IF NOT EXISTS remote_files (
3115
+ provider TEXT NOT NULL,
3116
+ entity_kind TEXT NOT NULL,
3117
+ repo_id TEXT NOT NULL,
3118
+ revision TEXT NOT NULL,
3119
+ path TEXT NOT NULL,
3120
+ size INTEGER,
3121
+ oid TEXT,
3122
+ lfs_oid TEXT,
3123
+ format TEXT,
3124
+ download_url TEXT NOT NULL,
3125
+ metadata_json TEXT NOT NULL,
3126
+ indexed_at TEXT NOT NULL,
3127
+ PRIMARY KEY (provider, entity_kind, repo_id, revision, path)
3128
+ )
3129
+ `);
3130
+ this.db.run(`
3131
+ CREATE TABLE IF NOT EXISTS installs (
3132
+ id TEXT PRIMARY KEY,
3133
+ provider TEXT NOT NULL,
3134
+ entity_kind TEXT NOT NULL,
3135
+ repo_id TEXT NOT NULL,
3136
+ revision TEXT NOT NULL,
3137
+ install_path TEXT NOT NULL,
3138
+ bytes INTEGER NOT NULL,
3139
+ files_json TEXT NOT NULL,
3140
+ status TEXT NOT NULL,
3141
+ runtime TEXT,
3142
+ metadata_json TEXT NOT NULL,
3143
+ created_at TEXT NOT NULL,
3144
+ updated_at TEXT NOT NULL
3145
+ )
3146
+ `);
3147
+ this.db.run("CREATE INDEX IF NOT EXISTS idx_catalog_downloads ON catalog_entries(downloads DESC)");
3148
+ this.db.run("CREATE INDEX IF NOT EXISTS idx_catalog_task ON catalog_entries(task)");
3149
+ this.db.run("CREATE INDEX IF NOT EXISTS idx_files_repo ON remote_files(provider, entity_kind, repo_id)");
3150
+ this.db.run("INSERT OR REPLACE INTO schema_meta (key, value) VALUES ('schema_version', ?)", [SCHEMA_VERSION]);
3151
+ }
3152
+ upsertCatalog(entries) {
3153
+ const now = new Date().toISOString();
3154
+ const stmt = this.db.prepare(`
3155
+ INSERT INTO catalog_entries (
3156
+ provider, entity_kind, repo_id, revision, title, author, task, library_name,
3157
+ license, gated, private, downloads, likes, tags_json, metadata_json,
3158
+ canonical_url, last_modified, indexed_at
3159
+ )
3160
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
3161
+ ON CONFLICT(provider, entity_kind, repo_id, revision) DO UPDATE SET
3162
+ title=excluded.title,
3163
+ author=excluded.author,
3164
+ task=excluded.task,
3165
+ library_name=excluded.library_name,
3166
+ license=excluded.license,
3167
+ gated=excluded.gated,
3168
+ private=excluded.private,
3169
+ downloads=excluded.downloads,
3170
+ likes=excluded.likes,
3171
+ tags_json=excluded.tags_json,
3172
+ metadata_json=excluded.metadata_json,
3173
+ canonical_url=excluded.canonical_url,
3174
+ last_modified=excluded.last_modified,
3175
+ indexed_at=excluded.indexed_at
3176
+ `);
3177
+ const tx = this.db.transaction((items) => {
3178
+ for (const entry of items) {
3179
+ stmt.run(entry.provider, entry.entityKind, entry.repoId, entry.revision, entry.title, entry.author ?? null, entry.task ?? null, entry.libraryName ?? null, entry.license ?? null, entry.gated ? 1 : 0, entry.private ? 1 : 0, entry.downloads ?? null, entry.likes ?? null, JSON.stringify(entry.tags), JSON.stringify(entry.metadata), entry.canonicalUrl, entry.lastModified ?? null, now);
3180
+ }
3181
+ });
3182
+ tx(entries);
3183
+ return entries.length;
3184
+ }
3185
+ upsertFiles(files) {
3186
+ const now = new Date().toISOString();
3187
+ const stmt = this.db.prepare(`
3188
+ INSERT INTO remote_files (
3189
+ provider, entity_kind, repo_id, revision, path, size, oid, lfs_oid,
3190
+ format, download_url, metadata_json, indexed_at
3191
+ )
3192
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
3193
+ ON CONFLICT(provider, entity_kind, repo_id, revision, path) DO UPDATE SET
3194
+ size=excluded.size,
3195
+ oid=excluded.oid,
3196
+ lfs_oid=excluded.lfs_oid,
3197
+ format=excluded.format,
3198
+ download_url=excluded.download_url,
3199
+ metadata_json=excluded.metadata_json,
3200
+ indexed_at=excluded.indexed_at
3201
+ `);
3202
+ const tx = this.db.transaction((items) => {
3203
+ for (const file of items) {
3204
+ stmt.run(file.provider, file.entityKind, file.repoId, file.revision, file.path, file.size ?? null, file.oid ?? null, file.lfsOid ?? null, file.format ?? null, file.downloadUrl, JSON.stringify(file.metadata), now);
3205
+ }
3206
+ });
3207
+ tx(files);
3208
+ return files.length;
3209
+ }
3210
+ recordInstall(artifact, metadata = {}) {
3211
+ this.db.prepare(`
3212
+ INSERT INTO installs (
3213
+ id, provider, entity_kind, repo_id, revision, install_path, bytes,
3214
+ files_json, status, runtime, metadata_json, created_at, updated_at
3215
+ )
3216
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
3217
+ ON CONFLICT(id) DO UPDATE SET
3218
+ bytes=excluded.bytes,
3219
+ files_json=excluded.files_json,
3220
+ status=excluded.status,
3221
+ runtime=excluded.runtime,
3222
+ metadata_json=excluded.metadata_json,
3223
+ updated_at=excluded.updated_at
3224
+ `).run(artifact.id, artifact.provider, artifact.entityKind, artifact.repoId, artifact.revision, artifact.installPath, artifact.bytes, JSON.stringify(artifact.files), artifact.status, null, JSON.stringify(metadata), artifact.createdAt, artifact.updatedAt);
3225
+ return artifact;
3226
+ }
3227
+ listInstalls() {
3228
+ const rows = this.db.query("SELECT * FROM installs ORDER BY updated_at DESC").all();
3229
+ return rows.map((row) => ({
3230
+ id: String(row.id),
3231
+ provider: String(row.provider),
3232
+ entityKind: String(row.entity_kind),
3233
+ repoId: String(row.repo_id),
3234
+ revision: String(row.revision),
3235
+ installPath: String(row.install_path),
3236
+ bytes: Number(row.bytes),
3237
+ files: JSON.parse(String(row.files_json)),
3238
+ status: String(row.status),
3239
+ createdAt: String(row.created_at),
3240
+ updatedAt: String(row.updated_at)
3241
+ }));
3242
+ }
3243
+ findInstall(repoIdOrId) {
3244
+ const row = this.db.query("SELECT * FROM installs WHERE id = ? OR repo_id = ? ORDER BY updated_at DESC LIMIT 1").get(repoIdOrId, repoIdOrId);
3245
+ if (!row)
3246
+ return null;
3247
+ return this.listInstalls().find((install) => install.id === row.id) ?? null;
3248
+ }
3249
+ deleteInstall(id) {
3250
+ const result = this.db.prepare("DELETE FROM installs WHERE id = ?").run(id);
3251
+ return result.changes > 0;
3252
+ }
3253
+ catalogStats() {
3254
+ const one = (table) => {
3255
+ const row = this.db.query(`SELECT COUNT(*) as count FROM ${table}`).get();
3256
+ return Number(row?.count ?? 0);
3257
+ };
3258
+ return {
3259
+ catalogEntries: one("catalog_entries"),
3260
+ remoteFiles: one("remote_files"),
3261
+ installs: one("installs")
3262
+ };
3263
+ }
3264
+ topCatalog(limit = 20) {
3265
+ const rows = this.db.query("SELECT * FROM catalog_entries ORDER BY COALESCE(downloads, 0) DESC, COALESCE(likes, 0) DESC LIMIT ?").all(limit);
3266
+ return rows.map((row) => ({
3267
+ provider: String(row.provider),
3268
+ entityKind: String(row.entity_kind),
3269
+ repoId: String(row.repo_id),
3270
+ revision: String(row.revision),
3271
+ canonicalUrl: String(row.canonical_url),
3272
+ title: String(row.title),
3273
+ author: row.author == null ? null : String(row.author),
3274
+ task: row.task == null ? null : String(row.task),
3275
+ libraryName: row.library_name == null ? null : String(row.library_name),
3276
+ license: row.license == null ? null : String(row.license),
3277
+ gated: Boolean(row.gated),
3278
+ private: Boolean(row.private),
3279
+ downloads: row.downloads == null ? null : Number(row.downloads),
3280
+ likes: row.likes == null ? null : Number(row.likes),
3281
+ tags: JSON.parse(String(row.tags_json)),
3282
+ lastModified: row.last_modified == null ? null : String(row.last_modified),
3283
+ metadata: JSON.parse(String(row.metadata_json))
3284
+ }));
3285
+ }
3286
+ }
3287
+
3288
+ // src/cli/index.ts
3289
+ var program2 = new Command;
3290
+ program2.name("models").description("Discover, index, download, and manage local open models and datasets").version(getPackageVersion()).option("-j, --json", "output JSON");
3291
+ function isJson(opts) {
3292
+ return Boolean(opts?.json || program2.opts().json);
3293
+ }
3294
+ function printJson(data) {
3295
+ console.log(JSON.stringify(data, null, 2));
3296
+ }
3297
+ function printResult(data, text, opts) {
3298
+ if (isJson(opts))
3299
+ printJson(data);
3300
+ else
3301
+ console.log(text);
3302
+ }
3303
+ function collect(value, previous) {
3304
+ previous.push(value);
3305
+ return previous;
3306
+ }
3307
+ function planBlockedReason(plan) {
3308
+ if (plan.files.length === 0)
3309
+ return "matched zero files";
3310
+ if (plan.exceedsMaxBytes)
3311
+ return `exceeds max bytes (${humanBytes(plan.totalBytes)} > ${humanBytes(plan.maxBytes)})`;
3312
+ if (plan.maxBytes != null && plan.unknownSizeFiles.length > 0)
3313
+ return `has unknown-size files under a byte cap: ${plan.unknownSizeFiles.join(", ")}`;
3314
+ return null;
3315
+ }
3316
+ function parsePositiveInt(value) {
3317
+ const parsed = Number.parseInt(value, 10);
3318
+ if (!Number.isFinite(parsed) || parsed < 1)
3319
+ throw new Error(`Expected a positive integer, got ${value}`);
3320
+ return parsed;
3321
+ }
3322
+ function parseBytes(value) {
3323
+ const match = value.trim().match(/^(\d+(?:\.\d+)?)(b|kb|mb|gb|tb)?$/i);
3324
+ if (!match)
3325
+ throw new Error(`Invalid byte value: ${value}`);
3326
+ const amount = Number.parseFloat(match[1]);
3327
+ const unit = (match[2] ?? "b").toLowerCase();
3328
+ const factor = unit === "tb" ? 1024 ** 4 : unit === "gb" ? 1024 ** 3 : unit === "mb" ? 1024 ** 2 : unit === "kb" ? 1024 : 1;
3329
+ return Math.floor(amount * factor);
3330
+ }
3331
+ function humanBytes(bytes) {
3332
+ if (bytes == null)
3333
+ return "unknown";
3334
+ const units = ["B", "KB", "MB", "GB", "TB"];
3335
+ let value = bytes;
3336
+ let unit = 0;
3337
+ while (value >= 1024 && unit < units.length - 1) {
3338
+ value /= 1024;
3339
+ unit += 1;
3340
+ }
3341
+ return `${value.toFixed(value >= 10 || unit === 0 ? 0 : 1)} ${units[unit]}`;
3342
+ }
3343
+ function renderEntry(entry) {
3344
+ const parts = [
3345
+ source_default.cyan(entry.repoId),
3346
+ entry.task ? source_default.gray(entry.task) : null,
3347
+ entry.license ? source_default.gray(`license:${entry.license}`) : null,
3348
+ entry.downloads != null ? source_default.gray(`downloads:${entry.downloads}`) : null
3349
+ ].filter(Boolean);
3350
+ return parts.join(" ");
3351
+ }
3352
+ function summarizeEntry(entry) {
3353
+ return {
3354
+ provider: entry.provider,
3355
+ entityKind: entry.entityKind,
3356
+ repoId: entry.repoId,
3357
+ revision: entry.revision,
3358
+ task: entry.task,
3359
+ libraryName: entry.libraryName,
3360
+ license: entry.license,
3361
+ gated: entry.gated,
3362
+ private: entry.private,
3363
+ downloads: entry.downloads,
3364
+ likes: entry.likes,
3365
+ lastModified: entry.lastModified,
3366
+ canonicalUrl: entry.canonicalUrl
3367
+ };
3368
+ }
3369
+ function renderFiles(files) {
3370
+ if (files.length === 0)
3371
+ return "files: none";
3372
+ return files.map((file) => `${file.path.padEnd(36)} ${humanBytes(file.size).padStart(10)} ${file.format ?? ""}`.trimEnd()).join(`
3373
+ `);
3374
+ }
3375
+ function renderPlan(plan) {
3376
+ return [
3377
+ `ref: ${formatProviderRef(plan.ref)}`,
3378
+ `destination: ${plan.destinationRoot}`,
3379
+ `files: ${plan.files.length}`,
3380
+ `bytes: ${humanBytes(plan.totalBytes)}`,
3381
+ plan.unknownSizeFiles.length > 0 ? `unknown-size files: ${plan.unknownSizeFiles.length}` : null,
3382
+ plan.exceedsMaxBytes ? source_default.red(`exceeds max bytes: ${humanBytes(plan.maxBytes)}`) : null
3383
+ ].filter(Boolean).join(`
3384
+ `);
3385
+ }
3386
+ function commandError(error) {
3387
+ const message = error instanceof Error ? error.message : String(error);
3388
+ if (program2.opts().json) {
3389
+ printJson({ ok: false, error: message });
3390
+ } else {
3391
+ console.error(source_default.red(message));
3392
+ }
3393
+ process.exit(1);
3394
+ }
3395
+ function searchOptions(command) {
3396
+ return command.option("--kind <kind>", "entity kind: model, dataset, or space", "model").option("--task <task>", "task or pipeline tag filter").option("--license <license>", "license tag filter").option("--tag <tag>", "additional Hub tag filter", collect, []).option("--limit <n>", "result limit", parsePositiveInt, 20).addOption(new Option("--sort <field>", "sort field").choices(["downloads", "likes", "lastModified", "createdAt", "trendingScore"]).default("downloads")).addOption(new Option("--direction <direction>", "sort direction").choices(["asc", "desc"]).default("desc"));
3397
+ }
3398
+ async function runSearch(query, opts, defaultKind) {
3399
+ const kind = parseEntityKind(String(opts.kind ?? defaultKind));
3400
+ const input = {
3401
+ query,
3402
+ entityKind: kind,
3403
+ task: opts.task,
3404
+ license: opts.license,
3405
+ tags: opts.tag,
3406
+ limit: opts.limit,
3407
+ sort: opts.sort,
3408
+ direction: opts.direction
3409
+ };
3410
+ return searchHuggingFace(input);
3411
+ }
3412
+ var providers = program2.command("providers").description("Manage provider auth and status");
3413
+ providers.command("list").description("List supported providers").option("-j, --json", "output JSON").action((opts) => {
3414
+ const data = [
3415
+ {
3416
+ id: "huggingface",
3417
+ entities: ["model", "dataset", "space"],
3418
+ capabilities: ["search", "info", "files", "selected-file-download", "best-index"]
3419
+ }
3420
+ ];
3421
+ printResult(data, data.map((provider) => `${provider.id}: ${provider.entities.join(", ")}`).join(`
3422
+ `), opts);
3423
+ });
3424
+ providers.command("status").description("Show provider credential status without printing token values").option("-j, --json", "output JSON").action((opts) => {
3425
+ const status = [redactAuthStatus(getHuggingFaceAuthStatus())];
3426
+ printResult(status, status.map((item) => `${item.provider}: ${item.available ? source_default.green(item.source) : source_default.yellow("no token")}${item.secretKey ? ` (${item.secretKey})` : ""}`).join(`
3427
+ `), opts);
3428
+ });
3429
+ providers.command("auth").argument("[provider]", "provider id", "huggingface").description("Configure provider auth by saving a local secret reference").option("--secret-key <key>", "secret key to read through the secrets CLI").option("-j, --json", "output JSON").action((provider, opts) => {
3430
+ if (provider !== "huggingface" && provider !== "hf")
3431
+ throw new Error(`Unsupported provider: ${provider}`);
3432
+ const status = opts.secretKey ? saveHuggingFaceSecretRef(opts.secretKey) : redactAuthStatus(getHuggingFaceAuthStatus());
3433
+ printResult(status, `${status.provider}: ${status.available ? source_default.green(status.source) : source_default.yellow("not configured")}${status.secretKey ? ` (${status.secretKey})` : ""}`, opts);
3434
+ });
3435
+ searchOptions(program2.command("search").argument("[query]", "search query").description("Search the remote Hugging Face catalog")).option("--index", "store returned entries in local SQLite").option("-j, --json", "output JSON").action(async (query, opts) => {
3436
+ try {
3437
+ const entries = await runSearch(query, opts, "model");
3438
+ if (opts.index)
3439
+ new ModelsStore().upsertCatalog(entries);
3440
+ printResult(entries, entries.map(renderEntry).join(`
3441
+ `) || "no results", opts);
3442
+ } catch (error) {
3443
+ commandError(error);
3444
+ }
3445
+ });
3446
+ program2.command("info").argument("<ref>", "provider ref, for example hf:sshleifer/tiny-gpt2").option("--kind <kind>", "entity kind", "model").option("--index", "store entry in local SQLite").option("-j, --json", "output JSON").description("Inspect a model or dataset").action(async (refInput, opts) => {
3447
+ try {
3448
+ const ref = parseProviderRef(refInput, opts.kind);
3449
+ const info = await getHuggingFaceInfo(ref);
3450
+ if (opts.index)
3451
+ new ModelsStore().upsertCatalog([info]);
3452
+ printResult(info, renderEntry(info), opts);
3453
+ } catch (error) {
3454
+ commandError(error);
3455
+ }
3456
+ });
3457
+ program2.command("files").argument("<ref>", "provider ref").option("--kind <kind>", "entity kind", "model").option("--index", "store files in local SQLite").option("-j, --json", "output JSON").description("List remote files for a model or dataset").action(async (refInput, opts) => {
3458
+ try {
3459
+ const ref = parseProviderRef(refInput, opts.kind);
3460
+ const files = await listHuggingFaceFiles(ref);
3461
+ if (opts.index)
3462
+ new ModelsStore().upsertFiles(files);
3463
+ printResult(files, renderFiles(files), opts);
3464
+ } catch (error) {
3465
+ commandError(error);
3466
+ }
3467
+ });
3468
+ program2.command("plan").argument("<ref>", "provider ref").option("--kind <kind>", "entity kind", "model").option("--include <pattern>", "include file path/glob; repeatable", collect, []).option("--exclude <pattern>", "exclude file path/glob; repeatable", collect, []).option("--max-bytes <bytes>", "maximum total known bytes", parseBytes, parseBytes("2gb")).option("-j, --json", "output JSON").description("Create a local download plan").action(async (refInput, opts) => {
3469
+ try {
3470
+ const ref = parseProviderRef(refInput, opts.kind);
3471
+ const plan = await createDownloadPlan({ ref, include: opts.include, exclude: opts.exclude, maxBytes: opts.maxBytes });
3472
+ const blockedReason = planBlockedReason(plan);
3473
+ printResult({ ok: blockedReason == null, status: blockedReason ? "blocked" : "ready", blockedReason, plan }, renderPlan(plan), opts);
3474
+ } catch (error) {
3475
+ commandError(error);
3476
+ }
3477
+ });
3478
+ program2.command("install").argument("<ref>", "provider ref").option("--kind <kind>", "entity kind", "model").option("--include <pattern>", "include file path/glob; repeatable", collect, []).option("--exclude <pattern>", "exclude file path/glob; repeatable", collect, []).option("--max-bytes <bytes>", "maximum total known bytes", parseBytes, parseBytes("2gb")).option("--dry-run", "preview without downloading").option("-j, --json", "output JSON").description("Install selected model or dataset files into the local store").action(async (refInput, opts) => {
3479
+ try {
3480
+ const ref = parseProviderRef(refInput, opts.kind);
3481
+ const plan = await createDownloadPlan({ ref, include: opts.include, exclude: opts.exclude, maxBytes: opts.maxBytes });
3482
+ const blockedReason = planBlockedReason(plan);
3483
+ if (opts.dryRun) {
3484
+ printResult({ ok: blockedReason == null, dryRun: true, status: blockedReason ? "blocked" : "ready", blockedReason, plan }, renderPlan(plan), opts);
3485
+ return;
3486
+ }
3487
+ if (blockedReason)
3488
+ throw new Error(`Download plan is blocked: ${blockedReason}`);
3489
+ const downloaded = await downloadPlannedFiles(plan);
3490
+ const now = new Date().toISOString();
3491
+ const artifact = {
3492
+ id: randomUUID2(),
3493
+ provider: ref.provider,
3494
+ entityKind: ref.entityKind,
3495
+ repoId: ref.repoId,
3496
+ revision: ref.revision,
3497
+ installPath: plan.destinationRoot,
3498
+ bytes: downloaded.reduce((sum, file) => sum + file.bytes, 0),
3499
+ files: downloaded.map((file) => file.path),
3500
+ status: "installed",
3501
+ createdAt: now,
3502
+ updatedAt: now
3503
+ };
3504
+ new ModelsStore().recordInstall(artifact, { plan, downloaded });
3505
+ printResult({ ok: true, install: artifact, downloaded }, `installed ${artifact.repoId} (${downloaded.length} files, ${humanBytes(artifact.bytes)})
3506
+ ${artifact.installPath}`, opts);
3507
+ } catch (error) {
3508
+ commandError(error);
3509
+ }
3510
+ });
3511
+ var index = program2.command("index").description("Index provider catalogs into local SQLite");
3512
+ index.command("hf").description("Index Hugging Face entries").argument("[query]", "optional search query").option("--kind <kind>", "entity kind", "model").option("--task <task>", "task or pipeline tag filter").option("--license <license>", "license tag filter").option("--tag <tag>", "additional Hub tag filter", collect, []).option("--limit <n>", "result limit", parsePositiveInt, 100).addOption(new Option("--sort <field>", "sort field").choices(["downloads", "likes", "lastModified", "createdAt", "trendingScore"]).default("downloads")).addOption(new Option("--direction <direction>", "sort direction").choices(["asc", "desc"]).default("desc")).option("--with-files", "also index remote file lists for returned entries").option("--include-results", "include all indexed entries in JSON output").option("-j, --json", "output JSON").action(async (query, opts) => {
3513
+ try {
3514
+ const entries = await runSearch(query, opts, opts.kind);
3515
+ const store = new ModelsStore;
3516
+ const catalogCount = store.upsertCatalog(entries);
3517
+ let fileCount = 0;
3518
+ if (opts.withFiles) {
3519
+ for (const entry of entries) {
3520
+ const files = await listHuggingFaceFiles({
3521
+ provider: entry.provider,
3522
+ entityKind: entry.entityKind,
3523
+ repoId: entry.repoId,
3524
+ revision: "main"
3525
+ });
3526
+ fileCount += store.upsertFiles(files);
3527
+ }
3528
+ }
3529
+ const result = {
3530
+ ok: true,
3531
+ catalogCount,
3532
+ fileCount,
3533
+ stats: store.catalogStats(),
3534
+ preview: entries.slice(0, 20).map(summarizeEntry),
3535
+ entries: opts.includeResults ? entries : undefined
3536
+ };
3537
+ printResult(result, `indexed ${catalogCount} catalog entries${fileCount ? ` and ${fileCount} files` : ""}`, opts);
3538
+ } catch (error) {
3539
+ commandError(error);
3540
+ }
3541
+ });
3542
+ index.command("best").description("Index top Hugging Face models by downloads").option("--limit <n>", "result limit", parsePositiveInt, 250).option("--task <task>", "task or pipeline tag filter").option("--with-files", "also index remote file lists").option("-j, --json", "output JSON").action(async (opts) => {
3543
+ try {
3544
+ const entries = await searchHuggingFace({
3545
+ entityKind: "model",
3546
+ task: opts.task,
3547
+ limit: opts.limit,
3548
+ sort: "downloads",
3549
+ direction: "desc"
3550
+ });
3551
+ const store = new ModelsStore;
3552
+ const catalogCount = store.upsertCatalog(entries);
3553
+ let fileCount = 0;
3554
+ if (opts.withFiles) {
3555
+ for (const entry of entries) {
3556
+ const files = await listHuggingFaceFiles({
3557
+ provider: entry.provider,
3558
+ entityKind: entry.entityKind,
3559
+ repoId: entry.repoId,
3560
+ revision: "main"
3561
+ });
3562
+ fileCount += store.upsertFiles(files);
3563
+ }
3564
+ }
3565
+ const result = { ok: true, catalogCount, fileCount, stats: store.catalogStats(), top: entries.slice(0, 20).map(summarizeEntry) };
3566
+ printResult(result, `indexed ${catalogCount} top models by downloads`, opts);
3567
+ } catch (error) {
3568
+ commandError(error);
3569
+ }
3570
+ });
3571
+ program2.command("list").description("List locally installed models and datasets").option("--catalog", "show top indexed catalog entries instead of installs").option("--limit <n>", "catalog limit", parsePositiveInt, 20).option("-j, --json", "output JSON").action((opts) => {
3572
+ try {
3573
+ const store = new ModelsStore;
3574
+ if (opts.catalog) {
3575
+ const entries = store.topCatalog(opts.limit);
3576
+ printResult(entries, entries.map(renderEntry).join(`
3577
+ `) || "catalog is empty", opts);
3578
+ return;
3579
+ }
3580
+ const installs = store.listInstalls();
3581
+ printResult(installs, installs.map((item) => `${item.id} ${item.repoId} ${humanBytes(item.bytes)} ${item.installPath}`).join(`
3582
+ `) || "no installs", opts);
3583
+ } catch (error) {
3584
+ commandError(error);
3585
+ }
3586
+ });
3587
+ program2.command("where").argument("<id-or-repo>", "install id or repo id").description("Show local install path").option("-j, --json", "output JSON").action((input, opts) => {
3588
+ try {
3589
+ const install = new ModelsStore().findInstall(input);
3590
+ if (!install)
3591
+ throw new Error(`Install not found: ${input}`);
3592
+ printResult(install, install.installPath, opts);
3593
+ } catch (error) {
3594
+ commandError(error);
3595
+ }
3596
+ });
3597
+ program2.command("remove").argument("<id-or-repo>", "install id or repo id").description("Remove install metadata, and optionally local files").option("--apply", "apply the removal; default is dry-run").option("--files", "also remove local files when --apply is set").option("-j, --json", "output JSON").action((input, opts) => {
3598
+ try {
3599
+ const store = new ModelsStore;
3600
+ const install = store.findInstall(input);
3601
+ if (!install)
3602
+ throw new Error(`Install not found: ${input}`);
3603
+ const result = {
3604
+ ok: true,
3605
+ dryRun: !opts.apply,
3606
+ removeFiles: Boolean(opts.files),
3607
+ install
3608
+ };
3609
+ if (!opts.apply) {
3610
+ printResult(result, `would remove metadata for ${install.id}${opts.files ? ` and files at ${install.installPath}` : ""}`, opts);
3611
+ return;
3612
+ }
3613
+ if (opts.files && existsSync(install.installPath)) {
3614
+ rmSync(install.installPath, { recursive: true, force: true });
3615
+ }
3616
+ store.deleteInstall(install.id);
3617
+ printResult(result, `removed ${install.id}${opts.files ? " and local files" : ""}`, opts);
3618
+ } catch (error) {
3619
+ commandError(error);
3620
+ }
3621
+ });
3622
+ var datasets = program2.command("datasets").description("Dataset catalog and install commands");
3623
+ searchOptions(datasets.command("search").argument("[query]", "search query").description("Search Hugging Face datasets")).option("--index", "store returned entries").option("-j, --json", "output JSON").action(async (query, opts) => {
3624
+ try {
3625
+ opts.kind = "dataset";
3626
+ const entries = await runSearch(query, opts, "dataset");
3627
+ if (opts.index)
3628
+ new ModelsStore().upsertCatalog(entries);
3629
+ printResult(entries, entries.map(renderEntry).join(`
3630
+ `) || "no results", opts);
3631
+ } catch (error) {
3632
+ commandError(error);
3633
+ }
3634
+ });
3635
+ datasets.command("info").argument("<ref>", "dataset ref, for example hf:dataset:cornell-movie-review-data/rotten_tomatoes").option("--index", "store entry").option("-j, --json", "output JSON").description("Inspect a dataset").action(async (refInput, opts) => {
3636
+ try {
3637
+ const ref = parseProviderRef(refInput, "dataset");
3638
+ const info = await getHuggingFaceInfo(ref);
3639
+ if (opts.index)
3640
+ new ModelsStore().upsertCatalog([info]);
3641
+ printResult(info, renderEntry(info), opts);
3642
+ } catch (error) {
3643
+ commandError(error);
3644
+ }
3645
+ });
3646
+ datasets.command("files").argument("<ref>", "dataset ref").option("--index", "store files").option("-j, --json", "output JSON").description("List dataset files").action(async (refInput, opts) => {
3647
+ try {
3648
+ const ref = parseProviderRef(refInput, "dataset");
3649
+ const files = await listHuggingFaceFiles(ref);
3650
+ if (opts.index)
3651
+ new ModelsStore().upsertFiles(files);
3652
+ printResult(files, renderFiles(files), opts);
3653
+ } catch (error) {
3654
+ commandError(error);
3655
+ }
3656
+ });
3657
+ datasets.command("install").argument("<ref>", "dataset ref").option("--include <pattern>", "include file path/glob; repeatable", collect, []).option("--exclude <pattern>", "exclude file path/glob; repeatable", collect, []).option("--max-bytes <bytes>", "maximum total known bytes", parseBytes, parseBytes("2gb")).option("--dry-run", "preview without downloading").option("-j, --json", "output JSON").description("Install selected dataset files into the local store").action(async (refInput, opts) => {
3658
+ try {
3659
+ const ref = parseProviderRef(refInput, "dataset");
3660
+ const plan = await createDownloadPlan({ ref, include: opts.include, exclude: opts.exclude, maxBytes: opts.maxBytes });
3661
+ const blockedReason = planBlockedReason(plan);
3662
+ if (opts.dryRun) {
3663
+ printResult({ ok: blockedReason == null, dryRun: true, status: blockedReason ? "blocked" : "ready", blockedReason, plan }, renderPlan(plan), opts);
3664
+ return;
3665
+ }
3666
+ if (blockedReason)
3667
+ throw new Error(`Download plan is blocked: ${blockedReason}`);
3668
+ const downloaded = await downloadPlannedFiles(plan);
3669
+ const now = new Date().toISOString();
3670
+ const artifact = {
3671
+ id: randomUUID2(),
3672
+ provider: ref.provider,
3673
+ entityKind: ref.entityKind,
3674
+ repoId: ref.repoId,
3675
+ revision: ref.revision,
3676
+ installPath: plan.destinationRoot,
3677
+ bytes: downloaded.reduce((sum, file) => sum + file.bytes, 0),
3678
+ files: downloaded.map((file) => file.path),
3679
+ status: "installed",
3680
+ createdAt: now,
3681
+ updatedAt: now
3682
+ };
3683
+ new ModelsStore().recordInstall(artifact, { plan, downloaded });
3684
+ printResult({ ok: true, install: artifact, downloaded }, `installed dataset ${artifact.repoId} (${downloaded.length} files, ${humanBytes(artifact.bytes)})`, opts);
3685
+ } catch (error) {
3686
+ commandError(error);
3687
+ }
3688
+ });
3689
+ program2.command("doctor").description("Check local store, auth, and basic runtime prerequisites").option("-j, --json", "output JSON").action((opts) => {
3690
+ try {
3691
+ const store = new ModelsStore;
3692
+ const dataDir = getModelsHome();
3693
+ const dbPath = getDbPath();
3694
+ const auth = redactAuthStatus(getHuggingFaceAuthStatus());
3695
+ const checks = [
3696
+ { id: "data-dir", status: "ok", detail: dataDir },
3697
+ { id: "sqlite", status: existsSync(dbPath) ? "ok" : "warn", detail: dbPath },
3698
+ { id: "huggingface-auth", status: auth.available ? "ok" : "warn", detail: auth.available ? `token available via ${auth.source}` : "anonymous Hub access only" },
3699
+ { id: "catalog", status: "ok", detail: JSON.stringify(store.catalogStats()) }
3700
+ ];
3701
+ const report = {
3702
+ ok: checks.every((check) => check.status !== "fail"),
3703
+ dataDir,
3704
+ dbPath,
3705
+ providers: [auth],
3706
+ checks
3707
+ };
3708
+ printResult(report, checks.map((check) => `${check.id.padEnd(18)} ${check.status} ${check.detail}`).join(`
3709
+ `), opts);
3710
+ } catch (error) {
3711
+ commandError(error);
3712
+ }
3713
+ });
3714
+ program2.command("manual").description("Print the local command manual").option("-j, --json", "output JSON").action((opts) => {
3715
+ const commands = [
3716
+ "models providers status --json",
3717
+ 'models search "tiny gpt2" --limit 5 --json',
3718
+ "models info hf:sshleifer/tiny-gpt2 --json",
3719
+ "models files hf:sshleifer/tiny-gpt2 --json",
3720
+ "models install hf:sshleifer/tiny-gpt2 --include config.json --include tokenizer_config.json --max-bytes 5mb --json",
3721
+ "models index best --limit 100 --json",
3722
+ "models datasets search rotten_tomatoes --limit 5 --json"
3723
+ ];
3724
+ const manual = { name: "models", version: getPackageVersion(), commands };
3725
+ printResult(manual, commands.join(`
3726
+ `), opts);
3727
+ });
3728
+ program2.command("goals").description("Print the implementation goal chain").option("-j, --json", "output JSON").action((opts) => {
3729
+ const cliDir = dirname4(fileURLToPath(import.meta.url));
3730
+ const path = join3(cliDir, "..", "..", "docs", "GOALS.md");
3731
+ const text = existsSync(path) ? readFileSync2(path, "utf8") : "Goal chain not found.";
3732
+ if (isJson(opts)) {
3733
+ printJson({ path, bytes: existsSync(path) ? statSync(path).size : 0, text });
3734
+ } else {
3735
+ console.log(text);
3736
+ }
3737
+ });
3738
+ program2.parseAsync().catch(commandError);