@adamhl8/configs 0.15.24 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/ts-import-fix +2783 -0
  2. package/package.json +9 -3
@@ -0,0 +1,2783 @@
1
+ #!/usr/bin/env node
2
+ import ve from "node:module";
3
+ import path from "node:path";
4
+ import process$1 from "node:process";
5
+ import fss from "node:fs";
6
+ import fs from "node:fs/promises";
7
+ import Ae from "fs";
8
+ var __create = Object.create;
9
+ var __defProp = Object.defineProperty;
10
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
+ var __getOwnPropNames = Object.getOwnPropertyNames;
12
+ var __getProtoOf = Object.getPrototypeOf;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
17
+ key = keys[i];
18
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
19
+ get: ((k) => from[k]).bind(null, key),
20
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
21
+ });
22
+ }
23
+ return to;
24
+ };
25
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
26
+ value: mod,
27
+ enumerable: true
28
+ }) : target, mod));
29
+ function message(message$1, ...values$1) {
30
+ const messageTerms = [];
31
+ for (let i = 0; i < message$1.length; i++) {
32
+ if (message$1[i] !== "") messageTerms.push({
33
+ type: "text",
34
+ text: message$1[i]
35
+ });
36
+ if (i >= values$1.length) continue;
37
+ const value$1 = values$1[i];
38
+ if (typeof value$1 === "string") messageTerms.push({
39
+ type: "value",
40
+ value: value$1
41
+ });
42
+ else if (Array.isArray(value$1)) messageTerms.push(...value$1);
43
+ else if (typeof value$1 === "object" && value$1 != null && "type" in value$1) messageTerms.push(value$1);
44
+ else throw new TypeError(`Invalid value type in message: ${typeof value$1}.`);
45
+ }
46
+ return messageTerms;
47
+ }
48
+ function text(text$1) {
49
+ return {
50
+ type: "text",
51
+ text: text$1
52
+ };
53
+ }
54
+ function optionName(name) {
55
+ return {
56
+ type: "optionName",
57
+ optionName: name
58
+ };
59
+ }
60
+ function optionNames(names) {
61
+ return {
62
+ type: "optionNames",
63
+ optionNames: names
64
+ };
65
+ }
66
+ function metavar(metavar$1) {
67
+ return {
68
+ type: "metavar",
69
+ metavar: metavar$1
70
+ };
71
+ }
72
+ function formatMessage(msg, options = {}) {
73
+ const colorConfig = options.colors ?? false;
74
+ const useColors = typeof colorConfig === "boolean" ? colorConfig : true;
75
+ const resetSuffix = typeof colorConfig === "object" ? colorConfig.resetSuffix ?? "" : "";
76
+ const useQuotes = options.quotes ?? true;
77
+ const resetSequence = `\x1b[0m${resetSuffix}`;
78
+ function* stream() {
79
+ const wordPattern = /\s*\S+\s*/g;
80
+ for (const term of msg) if (term.type === "text") while (true) {
81
+ const match = wordPattern.exec(term.text);
82
+ if (match == null) break;
83
+ yield {
84
+ text: match[0],
85
+ width: match[0].length
86
+ };
87
+ }
88
+ else if (term.type === "optionName") {
89
+ const name = useQuotes ? `\`${term.optionName}\`` : term.optionName;
90
+ yield {
91
+ text: useColors ? `\x1b[3m${name}${resetSequence}` : name,
92
+ width: name.length
93
+ };
94
+ } else if (term.type === "optionNames") {
95
+ const names = term.optionNames.map((name) => useQuotes ? `\`${name}\`` : name);
96
+ let i = 0;
97
+ for (const name of names) {
98
+ if (i > 0) yield {
99
+ text: "/",
100
+ width: 1
101
+ };
102
+ yield {
103
+ text: useColors ? `\x1b[3m${name}${resetSequence}` : name,
104
+ width: name.length
105
+ };
106
+ i++;
107
+ }
108
+ } else if (term.type === "metavar") {
109
+ const metavar$1 = useQuotes ? `\`${term.metavar}\`` : term.metavar;
110
+ yield {
111
+ text: useColors ? `\x1b[1m${metavar$1}${resetSequence}` : metavar$1,
112
+ width: metavar$1.length
113
+ };
114
+ } else if (term.type === "value") {
115
+ const value$1 = useQuotes ? `${JSON.stringify(term.value)}` : term.value;
116
+ yield {
117
+ text: useColors ? `\x1b[32m${value$1}${resetSequence}` : value$1,
118
+ width: value$1.length
119
+ };
120
+ } else if (term.type === "values") for (let i = 0; i < term.values.length; i++) {
121
+ if (i > 0) yield {
122
+ text: " ",
123
+ width: 1
124
+ };
125
+ const value$1 = useQuotes ? JSON.stringify(term.values[i]) : term.values[i];
126
+ yield {
127
+ text: useColors ? i <= 0 ? `\x1b[32m${value$1}` : i + 1 >= term.values.length ? `${value$1}${resetSequence}` : value$1 : value$1,
128
+ width: value$1.length
129
+ };
130
+ }
131
+ else if (term.type === "envVar") {
132
+ const envVar$1 = useQuotes ? `\`${term.envVar}\`` : term.envVar;
133
+ yield {
134
+ text: useColors ? `\x1b[1;4m${envVar$1}${resetSequence}` : envVar$1,
135
+ width: envVar$1.length
136
+ };
137
+ } else throw new TypeError(`Invalid MessageTerm type: ${term["type"]}.`);
138
+ }
139
+ let output = "";
140
+ let totalWidth = 0;
141
+ for (const { text: text$1, width } of stream()) {
142
+ if (options.maxWidth != null && totalWidth + width > options.maxWidth) {
143
+ output += "\n";
144
+ totalWidth = 0;
145
+ }
146
+ output += text$1;
147
+ totalWidth += width;
148
+ }
149
+ return output;
150
+ }
151
+ function longestMatch(...args) {
152
+ let parsers;
153
+ let options;
154
+ if (args.length > 0 && args[args.length - 1] && typeof args[args.length - 1] === "object" && !("$valueType" in args[args.length - 1])) {
155
+ options = args[args.length - 1];
156
+ parsers = args.slice(0, -1);
157
+ } else {
158
+ parsers = args;
159
+ options = void 0;
160
+ }
161
+ return {
162
+ $valueType: [],
163
+ $stateType: [],
164
+ priority: Math.max(...parsers.map((p$2) => p$2.priority)),
165
+ usage: [{
166
+ type: "exclusive",
167
+ terms: parsers.map((p$2) => p$2.usage)
168
+ }],
169
+ initialState: void 0,
170
+ complete(state) {
171
+ if (state == null) return {
172
+ success: false,
173
+ error: options?.errors?.noMatch ?? message`No matching option or command found.`
174
+ };
175
+ const [i, result] = state;
176
+ if (result.success) return parsers[i].complete(result.next.state);
177
+ return {
178
+ success: false,
179
+ error: result.error
180
+ };
181
+ },
182
+ parse(context) {
183
+ let bestMatch = null;
184
+ let error = {
185
+ consumed: 0,
186
+ error: context.buffer.length < 1 ? options?.errors?.noMatch ?? message`No matching option or command found.` : (() => {
187
+ const token = context.buffer[0];
188
+ const defaultMsg = message`Unexpected option or subcommand: ${optionName(token)}.`;
189
+ return options?.errors?.unexpectedInput != null ? typeof options.errors.unexpectedInput === "function" ? options.errors.unexpectedInput(token) : options.errors.unexpectedInput : defaultMsg;
190
+ })()
191
+ };
192
+ for (let i = 0; i < parsers.length; i++) {
193
+ const parser = parsers[i];
194
+ const result = parser.parse({
195
+ ...context,
196
+ state: context.state == null || context.state[0] !== i || !context.state[1].success ? parser.initialState : context.state[1].next.state
197
+ });
198
+ if (result.success) {
199
+ const consumed = context.buffer.length - result.next.buffer.length;
200
+ if (bestMatch === null || consumed > bestMatch.consumed) bestMatch = {
201
+ index: i,
202
+ result,
203
+ consumed
204
+ };
205
+ } else if (error.consumed < result.consumed) error = result;
206
+ }
207
+ if (bestMatch && bestMatch.result.success) return {
208
+ success: true,
209
+ next: {
210
+ ...context,
211
+ buffer: bestMatch.result.next.buffer,
212
+ optionsTerminated: bestMatch.result.next.optionsTerminated,
213
+ state: [bestMatch.index, bestMatch.result]
214
+ },
215
+ consumed: bestMatch.result.consumed
216
+ };
217
+ return {
218
+ ...error,
219
+ success: false
220
+ };
221
+ },
222
+ getDocFragments(state, _defaultValue) {
223
+ let description;
224
+ let fragments;
225
+ if (state.kind === "unavailable" || state.state == null) fragments = parsers.flatMap((p$2) => p$2.getDocFragments({ kind: "unavailable" }).fragments);
226
+ else {
227
+ const [i, result] = state.state;
228
+ if (result.success) {
229
+ const docResult = parsers[i].getDocFragments({
230
+ kind: "available",
231
+ state: result.next.state
232
+ });
233
+ description = docResult.description;
234
+ fragments = docResult.fragments;
235
+ } else fragments = parsers.flatMap((p$2) => p$2.getDocFragments({ kind: "unavailable" }).fragments);
236
+ }
237
+ return {
238
+ description,
239
+ fragments
240
+ };
241
+ }
242
+ };
243
+ }
244
+ function object(labelOrParsers, maybeParsersOrOptions, maybeOptions) {
245
+ const label = typeof labelOrParsers === "string" ? labelOrParsers : void 0;
246
+ let parsers;
247
+ let options = {};
248
+ if (typeof labelOrParsers === "string") {
249
+ parsers = maybeParsersOrOptions;
250
+ options = maybeOptions ?? {};
251
+ } else {
252
+ parsers = labelOrParsers;
253
+ options = maybeParsersOrOptions ?? {};
254
+ }
255
+ const parserPairs = Object.entries(parsers);
256
+ parserPairs.sort(([_$1, parserA], [__, parserB]) => parserB.priority - parserA.priority);
257
+ return {
258
+ $valueType: [],
259
+ $stateType: [],
260
+ priority: Math.max(...Object.values(parsers).map((p$2) => p$2.priority)),
261
+ usage: parserPairs.flatMap(([_$1, p$2]) => p$2.usage),
262
+ initialState: Object.fromEntries(Object.entries(parsers).map(([key, parser]) => [key, parser.initialState])),
263
+ parse(context) {
264
+ let error = {
265
+ consumed: 0,
266
+ error: context.buffer.length > 0 ? (() => {
267
+ const token = context.buffer[0];
268
+ const customMessage = options.errors?.unexpectedInput;
269
+ return customMessage ? typeof customMessage === "function" ? customMessage(token) : customMessage : message`Unexpected option or argument: ${token}.`;
270
+ })() : options.errors?.endOfInput ?? message`Expected an option or argument, but got end of input.`
271
+ };
272
+ let currentContext = context;
273
+ let anySuccess = false;
274
+ const allConsumed = [];
275
+ let madeProgress = true;
276
+ while (madeProgress && currentContext.buffer.length > 0) {
277
+ madeProgress = false;
278
+ for (const [field, parser] of parserPairs) {
279
+ const result = parser.parse({
280
+ ...currentContext,
281
+ state: currentContext.state && typeof currentContext.state === "object" && field in currentContext.state ? currentContext.state[field] : parser.initialState
282
+ });
283
+ if (result.success && result.consumed.length > 0) {
284
+ currentContext = {
285
+ ...currentContext,
286
+ buffer: result.next.buffer,
287
+ optionsTerminated: result.next.optionsTerminated,
288
+ state: {
289
+ ...currentContext.state,
290
+ [field]: result.next.state
291
+ }
292
+ };
293
+ allConsumed.push(...result.consumed);
294
+ anySuccess = true;
295
+ madeProgress = true;
296
+ break;
297
+ } else if (!result.success && error.consumed < result.consumed) error = result;
298
+ }
299
+ }
300
+ if (anySuccess) return {
301
+ success: true,
302
+ next: currentContext,
303
+ consumed: allConsumed
304
+ };
305
+ if (context.buffer.length === 0) {
306
+ let allCanComplete = true;
307
+ for (const [field, parser] of parserPairs) {
308
+ const fieldState = context.state && typeof context.state === "object" && field in context.state ? context.state[field] : parser.initialState;
309
+ if (!parser.complete(fieldState).success) {
310
+ allCanComplete = false;
311
+ break;
312
+ }
313
+ }
314
+ if (allCanComplete) return {
315
+ success: true,
316
+ next: context,
317
+ consumed: []
318
+ };
319
+ }
320
+ return {
321
+ ...error,
322
+ success: false
323
+ };
324
+ },
325
+ complete(state) {
326
+ const result = {};
327
+ for (const field in state) {
328
+ if (!(field in parsers)) continue;
329
+ const valueResult = parsers[field].complete(state[field]);
330
+ if (valueResult.success) result[field] = valueResult.value;
331
+ else return {
332
+ success: false,
333
+ error: valueResult.error
334
+ };
335
+ }
336
+ return {
337
+ success: true,
338
+ value: result
339
+ };
340
+ },
341
+ getDocFragments(state, defaultValue) {
342
+ const fragments = parserPairs.flatMap(([field, p$2]) => {
343
+ const fieldState = state.kind === "unavailable" ? { kind: "unavailable" } : {
344
+ kind: "available",
345
+ state: state.state[field]
346
+ };
347
+ return p$2.getDocFragments(fieldState, defaultValue?.[field]).fragments;
348
+ });
349
+ const entries = fragments.filter((d$1) => d$1.type === "entry");
350
+ const sections = [];
351
+ for (const fragment of fragments) {
352
+ if (fragment.type !== "section") continue;
353
+ if (fragment.title == null) entries.push(...fragment.entries);
354
+ else sections.push(fragment);
355
+ }
356
+ const section = {
357
+ title: label,
358
+ entries
359
+ };
360
+ sections.push(section);
361
+ return { fragments: sections.map((s$1) => ({
362
+ ...s$1,
363
+ type: "section"
364
+ })) };
365
+ }
366
+ };
367
+ }
368
+ function formatUsage(programName, usage, options = {}) {
369
+ usage = normalizeUsage(usage);
370
+ if (options.expandCommands) {
371
+ const lastTerm = usage.at(-1);
372
+ if (usage.length > 0 && usage.slice(0, -1).every((t) => t.type === "command") && lastTerm.type === "exclusive" && lastTerm.terms.every((t) => t.length > 0 && (t[0].type === "command" || t[0].type === "option" || t[0].type === "argument" || t[0].type === "optional" && t[0].terms.length === 1 && (t[0].terms[0].type === "command" || t[0].terms[0].type === "option" || t[0].terms[0].type === "argument")))) {
373
+ const lines = [];
374
+ for (let command$1 of lastTerm.terms) {
375
+ if (usage.length > 1) command$1 = [...usage.slice(0, -1), ...command$1];
376
+ lines.push(formatUsage(programName, command$1, options));
377
+ }
378
+ return lines.join("\n");
379
+ }
380
+ }
381
+ let output = options.colors ? `\x1b[1m${programName}\x1b[0m ` : `${programName} `;
382
+ let lineWidth = programName.length + 1;
383
+ for (const { text: text$1, width } of formatUsageTerms(usage, options)) {
384
+ if (options.maxWidth != null && lineWidth + width > options.maxWidth) {
385
+ output += "\n";
386
+ lineWidth = 0;
387
+ if (text$1 === " ") continue;
388
+ }
389
+ output += text$1;
390
+ lineWidth += width;
391
+ }
392
+ return output;
393
+ }
394
+ function normalizeUsage(usage) {
395
+ const terms = usage.map(normalizeUsageTerm);
396
+ terms.sort((a$1, b) => {
397
+ const aCmd = a$1.type === "command";
398
+ const bCmd = b.type === "command";
399
+ const aArg = a$1.type === "argument" || (a$1.type === "optional" || a$1.type === "multiple") && a$1.terms.at(-1)?.type === "argument";
400
+ const bArg = b.type === "argument" || (b.type === "optional" || b.type === "multiple") && b.terms.at(-1)?.type === "argument";
401
+ return aCmd === bCmd ? aArg === bArg ? 0 : aArg ? 1 : -1 : aCmd ? -1 : 1;
402
+ });
403
+ return terms;
404
+ }
405
+ function normalizeUsageTerm(term) {
406
+ if (term.type === "optional") return {
407
+ type: "optional",
408
+ terms: normalizeUsage(term.terms)
409
+ };
410
+ else if (term.type === "multiple") return {
411
+ type: "multiple",
412
+ terms: normalizeUsage(term.terms),
413
+ min: term.min
414
+ };
415
+ else if (term.type === "exclusive") {
416
+ const terms = [];
417
+ for (const usage of term.terms) {
418
+ const normalized = normalizeUsage(usage);
419
+ if (normalized.length === 1 && normalized[0].type === "exclusive") for (const subUsage of normalized[0].terms) terms.push(subUsage);
420
+ else terms.push(normalized);
421
+ }
422
+ return {
423
+ type: "exclusive",
424
+ terms
425
+ };
426
+ } else return term;
427
+ }
428
+ function* formatUsageTerms(terms, options) {
429
+ let i = 0;
430
+ for (const t of terms) {
431
+ if (i > 0) yield {
432
+ text: " ",
433
+ width: 1
434
+ };
435
+ yield* formatUsageTermInternal(t, options);
436
+ i++;
437
+ }
438
+ }
439
+ function formatUsageTerm(term, options = {}) {
440
+ let lineWidth = 0;
441
+ let output = "";
442
+ for (const { text: text$1, width } of formatUsageTermInternal(term, options)) {
443
+ if (options.maxWidth != null && lineWidth + width > options.maxWidth) {
444
+ output += "\n";
445
+ lineWidth = 0;
446
+ if (text$1 === " ") continue;
447
+ }
448
+ output += text$1;
449
+ lineWidth += width;
450
+ }
451
+ return output;
452
+ }
453
+ function* formatUsageTermInternal(term, options) {
454
+ const optionsSeparator = options.optionsSeparator ?? "/";
455
+ if (term.type === "argument") yield {
456
+ text: options?.colors ? `\x1b[4m${term.metavar}\x1b[0m` : term.metavar,
457
+ width: term.metavar.length
458
+ };
459
+ else if (term.type === "option") if (options?.onlyShortestOptions) {
460
+ const shortestName = term.names.reduce((a$1, b) => a$1.length <= b.length ? a$1 : b);
461
+ yield {
462
+ text: options?.colors ? `\x1b[3m${shortestName}\x1b[0m` : shortestName,
463
+ width: shortestName.length
464
+ };
465
+ } else {
466
+ let i = 0;
467
+ for (const optionName$1 of term.names) {
468
+ if (i > 0) yield {
469
+ text: options?.colors ? `\x1b[2m${optionsSeparator}\x1b[0m` : optionsSeparator,
470
+ width: optionsSeparator.length
471
+ };
472
+ yield {
473
+ text: options?.colors ? `\x1b[3m${optionName$1}\x1b[0m` : optionName$1,
474
+ width: optionName$1.length
475
+ };
476
+ i++;
477
+ }
478
+ if (term.metavar != null) {
479
+ yield {
480
+ text: " ",
481
+ width: 1
482
+ };
483
+ yield {
484
+ text: options?.colors ? `\x1b[4m\x1b[2m${term.metavar}\x1b[0m` : term.metavar,
485
+ width: term.metavar.length
486
+ };
487
+ }
488
+ }
489
+ else if (term.type === "command") yield {
490
+ text: options?.colors ? `\x1b[1m${term.name}\x1b[0m` : term.name,
491
+ width: term.name.length
492
+ };
493
+ else if (term.type === "optional") {
494
+ yield {
495
+ text: options?.colors ? `\x1b[2m[\x1b[0m` : "[",
496
+ width: 1
497
+ };
498
+ yield* formatUsageTerms(term.terms, options);
499
+ yield {
500
+ text: options?.colors ? `\x1b[2m]\x1b[0m` : "]",
501
+ width: 1
502
+ };
503
+ } else if (term.type === "exclusive") {
504
+ yield {
505
+ text: options?.colors ? `\x1b[2m(\x1b[0m` : "(",
506
+ width: 1
507
+ };
508
+ let i = 0;
509
+ for (const termGroup of term.terms) {
510
+ if (i > 0) {
511
+ yield {
512
+ text: " ",
513
+ width: 1
514
+ };
515
+ yield {
516
+ text: "|",
517
+ width: 1
518
+ };
519
+ yield {
520
+ text: " ",
521
+ width: 1
522
+ };
523
+ }
524
+ yield* formatUsageTerms(termGroup, options);
525
+ i++;
526
+ }
527
+ yield {
528
+ text: options?.colors ? `\x1b[2m)\x1b[0m` : ")",
529
+ width: 1
530
+ };
531
+ } else if (term.type === "multiple") {
532
+ if (term.min < 1) yield {
533
+ text: options?.colors ? `\x1b[2m[\x1b[0m` : "[",
534
+ width: 1
535
+ };
536
+ for (let i = 0; i < Math.max(1, term.min); i++) {
537
+ if (i > 0) yield {
538
+ text: " ",
539
+ width: 1
540
+ };
541
+ yield* formatUsageTerms(term.terms, options);
542
+ }
543
+ yield {
544
+ text: options?.colors ? `\x1b[2m...\x1b[0m` : "...",
545
+ width: 3
546
+ };
547
+ if (term.min < 1) yield {
548
+ text: options?.colors ? `\x1b[2m]\x1b[0m` : "]",
549
+ width: 1
550
+ };
551
+ } else throw new TypeError(`Unknown usage term type: ${term["type"]}.`);
552
+ }
553
+ function formatDocPage(programName, page, options = {}) {
554
+ const termIndent = options.termIndent ?? 2;
555
+ const termWidth = options.termWidth ?? 26;
556
+ let output = "";
557
+ if (page.brief != null) {
558
+ output += formatMessage(page.brief, {
559
+ colors: options.colors,
560
+ maxWidth: options.maxWidth,
561
+ quotes: !options.colors
562
+ });
563
+ output += "\n";
564
+ }
565
+ if (page.usage != null) {
566
+ output += "Usage: ";
567
+ output += indentLines$1(formatUsage(programName, page.usage, {
568
+ colors: options.colors,
569
+ maxWidth: options.maxWidth == null ? void 0 : options.maxWidth - 7,
570
+ expandCommands: true
571
+ }), 7);
572
+ output += "\n";
573
+ }
574
+ if (page.description != null) {
575
+ output += "\n";
576
+ output += formatMessage(page.description, {
577
+ colors: options.colors,
578
+ maxWidth: options.maxWidth,
579
+ quotes: !options.colors
580
+ });
581
+ output += "\n";
582
+ }
583
+ const sections = page.sections.toSorted((a$1, b) => a$1.title == null && b.title == null ? 0 : a$1.title == null ? -1 : 1);
584
+ for (const section of sections) {
585
+ output += "\n";
586
+ if (section.title != null) output += `${section.title}:\n`;
587
+ for (const entry of section.entries) {
588
+ const term = formatUsageTerm(entry.term, {
589
+ colors: options.colors,
590
+ optionsSeparator: ", ",
591
+ maxWidth: options.maxWidth == null ? void 0 : options.maxWidth - termIndent
592
+ });
593
+ let description = entry.description == null ? "" : formatMessage(entry.description, {
594
+ colors: options.colors,
595
+ quotes: !options.colors,
596
+ maxWidth: options.maxWidth == null ? void 0 : options.maxWidth - termIndent - termWidth - 2
597
+ });
598
+ if (options.showDefault && entry.default != null) {
599
+ const prefix = typeof options.showDefault === "object" ? options.showDefault.prefix ?? " [" : " [";
600
+ const suffix = typeof options.showDefault === "object" ? options.showDefault.suffix ?? "]" : "]";
601
+ const defaultText = `${prefix}${formatMessage(entry.default, {
602
+ colors: options.colors ? { resetSuffix: "\x1B[2m" } : false,
603
+ quotes: !options.colors
604
+ })}${suffix}`;
605
+ const formattedDefault = options.colors ? `\x1b[2m${defaultText}\x1b[0m` : defaultText;
606
+ description += formattedDefault;
607
+ }
608
+ output += `${" ".repeat(termIndent)}${ansiAwareRightPad(term, termWidth)} ${description === "" ? "" : indentLines$1(description, termIndent + termWidth + 2)}\n`;
609
+ }
610
+ }
611
+ if (page.footer != null) {
612
+ output += "\n";
613
+ output += formatMessage(page.footer, {
614
+ colors: options.colors,
615
+ maxWidth: options.maxWidth,
616
+ quotes: !options.colors
617
+ });
618
+ }
619
+ return output;
620
+ }
621
+ function indentLines$1(text$1, indent) {
622
+ return text$1.split("\n").join("\n" + " ".repeat(indent));
623
+ }
624
+ function ansiAwareRightPad(text$1, length, char = " ") {
625
+ const strippedText = text$1.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, "");
626
+ if (strippedText.length >= length) return text$1;
627
+ return text$1 + char.repeat(length - strippedText.length);
628
+ }
629
+ function optional(parser) {
630
+ return {
631
+ $valueType: [],
632
+ $stateType: [],
633
+ priority: parser.priority,
634
+ usage: [{
635
+ type: "optional",
636
+ terms: parser.usage
637
+ }],
638
+ initialState: void 0,
639
+ parse(context) {
640
+ const result = parser.parse({
641
+ ...context,
642
+ state: typeof context.state === "undefined" ? parser.initialState : context.state[0]
643
+ });
644
+ if (result.success) return {
645
+ success: true,
646
+ next: {
647
+ ...result.next,
648
+ state: [result.next.state]
649
+ },
650
+ consumed: result.consumed
651
+ };
652
+ return result;
653
+ },
654
+ complete(state) {
655
+ if (typeof state === "undefined") return {
656
+ success: true,
657
+ value: void 0
658
+ };
659
+ return parser.complete(state[0]);
660
+ },
661
+ getDocFragments(state, defaultValue) {
662
+ const innerState = state.kind === "unavailable" ? { kind: "unavailable" } : state.state === void 0 ? { kind: "unavailable" } : {
663
+ kind: "available",
664
+ state: state.state[0]
665
+ };
666
+ return parser.getDocFragments(innerState, defaultValue);
667
+ }
668
+ };
669
+ }
670
+ function multiple(parser, options = {}) {
671
+ const { min = 0, max = Infinity } = options;
672
+ return {
673
+ $valueType: [],
674
+ $stateType: [],
675
+ priority: parser.priority,
676
+ usage: [{
677
+ type: "multiple",
678
+ terms: parser.usage,
679
+ min
680
+ }],
681
+ initialState: [],
682
+ parse(context) {
683
+ let added = context.state.length < 1;
684
+ let result = parser.parse({
685
+ ...context,
686
+ state: context.state.at(-1) ?? parser.initialState
687
+ });
688
+ if (!result.success) if (!added) {
689
+ result = parser.parse({
690
+ ...context,
691
+ state: parser.initialState
692
+ });
693
+ if (!result.success) return result;
694
+ added = true;
695
+ } else return result;
696
+ return {
697
+ success: true,
698
+ next: {
699
+ ...result.next,
700
+ state: [...added ? context.state : context.state.slice(0, -1), result.next.state]
701
+ },
702
+ consumed: result.consumed
703
+ };
704
+ },
705
+ complete(state) {
706
+ const result = [];
707
+ for (const s$1 of state) {
708
+ const valueResult = parser.complete(s$1);
709
+ if (valueResult.success) result.push(valueResult.value);
710
+ else return {
711
+ success: false,
712
+ error: valueResult.error
713
+ };
714
+ }
715
+ if (result.length < min) {
716
+ const customMessage = options.errors?.tooFew;
717
+ return {
718
+ success: false,
719
+ error: customMessage ? typeof customMessage === "function" ? customMessage(min, result.length) : customMessage : message`Expected at least ${text(min.toLocaleString("en"))} values, but got only ${text(result.length.toLocaleString("en"))}.`
720
+ };
721
+ } else if (result.length > max) {
722
+ const customMessage = options.errors?.tooMany;
723
+ return {
724
+ success: false,
725
+ error: customMessage ? typeof customMessage === "function" ? customMessage(max, result.length) : customMessage : message`Expected at most ${text(max.toLocaleString("en"))} values, but got ${text(result.length.toLocaleString("en"))}.`
726
+ };
727
+ }
728
+ return {
729
+ success: true,
730
+ value: result
731
+ };
732
+ },
733
+ getDocFragments(state, defaultValue) {
734
+ const innerState = state.kind === "unavailable" ? { kind: "unavailable" } : state.state.length > 0 ? {
735
+ kind: "available",
736
+ state: state.state.at(-1)
737
+ } : { kind: "unavailable" };
738
+ return parser.getDocFragments(innerState, defaultValue != null && defaultValue.length > 0 ? defaultValue[0] : void 0);
739
+ }
740
+ };
741
+ }
742
+ function isValueParser(object$1) {
743
+ return typeof object$1 === "object" && object$1 != null && "metavar" in object$1 && typeof object$1.metavar === "string" && "parse" in object$1 && typeof object$1.parse === "function" && "format" in object$1 && typeof object$1.format === "function";
744
+ }
745
+ function string(options = {}) {
746
+ return {
747
+ metavar: options.metavar ?? "STRING",
748
+ parse(input) {
749
+ if (options.pattern != null && !options.pattern.test(input)) return {
750
+ success: false,
751
+ error: options.errors?.patternMismatch ? typeof options.errors.patternMismatch === "function" ? options.errors.patternMismatch(input, options.pattern) : options.errors.patternMismatch : message`Expected a string matching pattern ${text(options.pattern.source)}, but got ${input}.`
752
+ };
753
+ return {
754
+ success: true,
755
+ value: input
756
+ };
757
+ },
758
+ format(value) {
759
+ return value;
760
+ }
761
+ };
762
+ }
763
+ function constant(value) {
764
+ return {
765
+ $valueType: [],
766
+ $stateType: [],
767
+ priority: 0,
768
+ usage: [],
769
+ initialState: value,
770
+ parse(context) {
771
+ return {
772
+ success: true,
773
+ next: context,
774
+ consumed: []
775
+ };
776
+ },
777
+ complete(state) {
778
+ return {
779
+ success: true,
780
+ value: state
781
+ };
782
+ },
783
+ getDocFragments(_state, _defaultValue) {
784
+ return { fragments: [] };
785
+ }
786
+ };
787
+ }
788
+ function option(...args) {
789
+ const lastArg = args.at(-1);
790
+ const secondLastArg = args.at(-2);
791
+ let valueParser;
792
+ let optionNames$1;
793
+ let options = {};
794
+ if (isValueParser(lastArg)) {
795
+ valueParser = lastArg;
796
+ optionNames$1 = args.slice(0, -1);
797
+ } else if (typeof lastArg === "object" && lastArg != null) {
798
+ options = lastArg;
799
+ if (isValueParser(secondLastArg)) {
800
+ valueParser = secondLastArg;
801
+ optionNames$1 = args.slice(0, -2);
802
+ } else {
803
+ valueParser = void 0;
804
+ optionNames$1 = args.slice(0, -1);
805
+ }
806
+ } else {
807
+ optionNames$1 = args;
808
+ valueParser = void 0;
809
+ }
810
+ return {
811
+ $valueType: [],
812
+ $stateType: [],
813
+ priority: 10,
814
+ usage: [valueParser == null ? {
815
+ type: "optional",
816
+ terms: [{
817
+ type: "option",
818
+ names: optionNames$1
819
+ }]
820
+ } : {
821
+ type: "option",
822
+ names: optionNames$1,
823
+ metavar: valueParser.metavar
824
+ }],
825
+ initialState: valueParser == null ? {
826
+ success: true,
827
+ value: false
828
+ } : {
829
+ success: false,
830
+ error: options.errors?.missing ? typeof options.errors.missing === "function" ? options.errors.missing(optionNames$1) : options.errors.missing : message`Missing option ${optionNames(optionNames$1)}.`
831
+ },
832
+ parse(context) {
833
+ if (context.optionsTerminated) return {
834
+ success: false,
835
+ consumed: 0,
836
+ error: options.errors?.optionsTerminated ?? message`No more options can be parsed.`
837
+ };
838
+ else if (context.buffer.length < 1) return {
839
+ success: false,
840
+ consumed: 0,
841
+ error: options.errors?.endOfInput ?? message`Expected an option, but got end of input.`
842
+ };
843
+ if (context.buffer[0] === "--") return {
844
+ success: true,
845
+ next: {
846
+ ...context,
847
+ buffer: context.buffer.slice(1),
848
+ state: context.state,
849
+ optionsTerminated: true
850
+ },
851
+ consumed: context.buffer.slice(0, 1)
852
+ };
853
+ if (optionNames$1.includes(context.buffer[0])) {
854
+ if (context.state.success && (valueParser != null || context.state.value)) return {
855
+ success: false,
856
+ consumed: 1,
857
+ error: options.errors?.duplicate ? typeof options.errors.duplicate === "function" ? options.errors.duplicate(context.buffer[0]) : options.errors.duplicate : message`${context.buffer[0]} cannot be used multiple times.`
858
+ };
859
+ if (valueParser == null) return {
860
+ success: true,
861
+ next: {
862
+ ...context,
863
+ state: {
864
+ success: true,
865
+ value: true
866
+ },
867
+ buffer: context.buffer.slice(1)
868
+ },
869
+ consumed: context.buffer.slice(0, 1)
870
+ };
871
+ if (context.buffer.length < 2) return {
872
+ success: false,
873
+ consumed: 1,
874
+ error: message`Option ${optionName(context.buffer[0])} requires a value, but got no value.`
875
+ };
876
+ const result = valueParser.parse(context.buffer[1]);
877
+ return {
878
+ success: true,
879
+ next: {
880
+ ...context,
881
+ state: result,
882
+ buffer: context.buffer.slice(2)
883
+ },
884
+ consumed: context.buffer.slice(0, 2)
885
+ };
886
+ }
887
+ const prefixes = optionNames$1.filter((name) => name.startsWith("--") || name.startsWith("/")).map((name) => name.startsWith("/") ? `${name}:` : `${name}=`);
888
+ for (const prefix of prefixes) {
889
+ if (!context.buffer[0].startsWith(prefix)) continue;
890
+ if (context.state.success && (valueParser != null || context.state.value)) return {
891
+ success: false,
892
+ consumed: 1,
893
+ error: options.errors?.duplicate ? typeof options.errors.duplicate === "function" ? options.errors.duplicate(prefix) : options.errors.duplicate : message`${optionName(prefix)} cannot be used multiple times.`
894
+ };
895
+ const value = context.buffer[0].slice(prefix.length);
896
+ if (valueParser == null) return {
897
+ success: false,
898
+ consumed: 1,
899
+ error: options.errors?.unexpectedValue ? typeof options.errors.unexpectedValue === "function" ? options.errors.unexpectedValue(value) : options.errors.unexpectedValue : message`Option ${optionName(prefix)} is a Boolean flag, but got a value: ${value}.`
900
+ };
901
+ const result = valueParser.parse(value);
902
+ return {
903
+ success: true,
904
+ next: {
905
+ ...context,
906
+ state: result,
907
+ buffer: context.buffer.slice(1)
908
+ },
909
+ consumed: context.buffer.slice(0, 1)
910
+ };
911
+ }
912
+ if (valueParser == null) {
913
+ const shortOptions = optionNames$1.filter((name) => name.match(/^-[^-]$/));
914
+ for (const shortOption of shortOptions) {
915
+ if (!context.buffer[0].startsWith(shortOption)) continue;
916
+ if (context.state.success && (valueParser != null || context.state.value)) return {
917
+ success: false,
918
+ consumed: 1,
919
+ error: options.errors?.duplicate ? typeof options.errors.duplicate === "function" ? options.errors.duplicate(shortOption) : options.errors.duplicate : message`${optionName(shortOption)} cannot be used multiple times.`
920
+ };
921
+ return {
922
+ success: true,
923
+ next: {
924
+ ...context,
925
+ state: {
926
+ success: true,
927
+ value: true
928
+ },
929
+ buffer: [`-${context.buffer[0].slice(2)}`, ...context.buffer.slice(1)]
930
+ },
931
+ consumed: [context.buffer[0].slice(0, 2)]
932
+ };
933
+ }
934
+ }
935
+ return {
936
+ success: false,
937
+ consumed: 0,
938
+ error: message`No matched option for ${optionName(context.buffer[0])}.`
939
+ };
940
+ },
941
+ complete(state) {
942
+ if (state == null) return valueParser == null ? {
943
+ success: true,
944
+ value: false
945
+ } : {
946
+ success: false,
947
+ error: options.errors?.missing ? typeof options.errors.missing === "function" ? options.errors.missing(optionNames$1) : options.errors.missing : message`Missing option ${optionNames(optionNames$1)}.`
948
+ };
949
+ if (state.success) return state;
950
+ return {
951
+ success: false,
952
+ error: options.errors?.invalidValue ? typeof options.errors.invalidValue === "function" ? options.errors.invalidValue(state.error) : options.errors.invalidValue : message`${optionNames(optionNames$1)}: ${state.error}`
953
+ };
954
+ },
955
+ getDocFragments(_state, defaultValue) {
956
+ return {
957
+ fragments: [{
958
+ type: "entry",
959
+ term: {
960
+ type: "option",
961
+ names: optionNames$1,
962
+ metavar: valueParser?.metavar
963
+ },
964
+ description: options.description,
965
+ default: defaultValue != null && valueParser != null ? message`${valueParser.format(defaultValue)}` : void 0
966
+ }],
967
+ description: options.description
968
+ };
969
+ },
970
+ [Symbol.for("Deno.customInspect")]() {
971
+ return `option(${optionNames$1.map((o$1) => JSON.stringify(o$1)).join(", ")})`;
972
+ }
973
+ };
974
+ }
975
+ function flag(...args) {
976
+ const lastArg = args.at(-1);
977
+ let optionNames$1;
978
+ let options = {};
979
+ if (typeof lastArg === "object" && lastArg != null && !Array.isArray(lastArg)) {
980
+ options = lastArg;
981
+ optionNames$1 = args.slice(0, -1);
982
+ } else optionNames$1 = args;
983
+ return {
984
+ $valueType: [],
985
+ $stateType: [],
986
+ priority: 10,
987
+ usage: [{
988
+ type: "option",
989
+ names: optionNames$1
990
+ }],
991
+ initialState: void 0,
992
+ parse(context) {
993
+ if (context.optionsTerminated) return {
994
+ success: false,
995
+ consumed: 0,
996
+ error: options.errors?.optionsTerminated ?? message`No more options can be parsed.`
997
+ };
998
+ else if (context.buffer.length < 1) return {
999
+ success: false,
1000
+ consumed: 0,
1001
+ error: options.errors?.endOfInput ?? message`Expected an option, but got end of input.`
1002
+ };
1003
+ if (context.buffer[0] === "--") return {
1004
+ success: true,
1005
+ next: {
1006
+ ...context,
1007
+ buffer: context.buffer.slice(1),
1008
+ state: context.state,
1009
+ optionsTerminated: true
1010
+ },
1011
+ consumed: context.buffer.slice(0, 1)
1012
+ };
1013
+ if (optionNames$1.includes(context.buffer[0])) {
1014
+ if (context.state?.success) return {
1015
+ success: false,
1016
+ consumed: 1,
1017
+ error: options.errors?.duplicate ? typeof options.errors.duplicate === "function" ? options.errors.duplicate(context.buffer[0]) : options.errors.duplicate : message`${optionName(context.buffer[0])} cannot be used multiple times.`
1018
+ };
1019
+ return {
1020
+ success: true,
1021
+ next: {
1022
+ ...context,
1023
+ state: {
1024
+ success: true,
1025
+ value: true
1026
+ },
1027
+ buffer: context.buffer.slice(1)
1028
+ },
1029
+ consumed: context.buffer.slice(0, 1)
1030
+ };
1031
+ }
1032
+ const prefixes = optionNames$1.filter((name) => name.startsWith("--") || name.startsWith("/")).map((name) => name.startsWith("/") ? `${name}:` : `${name}=`);
1033
+ for (const prefix of prefixes) if (context.buffer[0].startsWith(prefix)) {
1034
+ const value = context.buffer[0].slice(prefix.length);
1035
+ return {
1036
+ success: false,
1037
+ consumed: 1,
1038
+ error: message`Flag ${optionName(prefix.slice(0, -1))} does not accept a value, but got: ${value}.`
1039
+ };
1040
+ }
1041
+ const shortOptions = optionNames$1.filter((name) => name.match(/^-[^-]$/));
1042
+ for (const shortOption of shortOptions) {
1043
+ if (!context.buffer[0].startsWith(shortOption)) continue;
1044
+ if (context.state?.success) return {
1045
+ success: false,
1046
+ consumed: 1,
1047
+ error: options.errors?.duplicate ? typeof options.errors.duplicate === "function" ? options.errors.duplicate(shortOption) : options.errors.duplicate : message`${optionName(shortOption)} cannot be used multiple times.`
1048
+ };
1049
+ return {
1050
+ success: true,
1051
+ next: {
1052
+ ...context,
1053
+ state: {
1054
+ success: true,
1055
+ value: true
1056
+ },
1057
+ buffer: [`-${context.buffer[0].slice(2)}`, ...context.buffer.slice(1)]
1058
+ },
1059
+ consumed: [context.buffer[0].slice(0, 2)]
1060
+ };
1061
+ }
1062
+ return {
1063
+ success: false,
1064
+ consumed: 0,
1065
+ error: message`No matched option for ${optionName(context.buffer[0])}.`
1066
+ };
1067
+ },
1068
+ complete(state) {
1069
+ if (state == null) return {
1070
+ success: false,
1071
+ error: options.errors?.missing ? typeof options.errors.missing === "function" ? options.errors.missing(optionNames$1) : options.errors.missing : message`Required flag ${optionNames(optionNames$1)} is missing.`
1072
+ };
1073
+ if (state.success) return {
1074
+ success: true,
1075
+ value: true
1076
+ };
1077
+ return {
1078
+ success: false,
1079
+ error: message`${optionNames(optionNames$1)}: ${state.error}`
1080
+ };
1081
+ },
1082
+ getDocFragments(_state, _defaultValue) {
1083
+ return {
1084
+ fragments: [{
1085
+ type: "entry",
1086
+ term: {
1087
+ type: "option",
1088
+ names: optionNames$1
1089
+ },
1090
+ description: options.description
1091
+ }],
1092
+ description: options.description
1093
+ };
1094
+ },
1095
+ [Symbol.for("Deno.customInspect")]() {
1096
+ return `flag(${optionNames$1.map((o$1) => JSON.stringify(o$1)).join(", ")})`;
1097
+ }
1098
+ };
1099
+ }
1100
+ function argument(valueParser, options = {}) {
1101
+ const optionPattern = /^--?[a-z0-9-]+$/i;
1102
+ const term = {
1103
+ type: "argument",
1104
+ metavar: valueParser.metavar
1105
+ };
1106
+ return {
1107
+ $valueType: [],
1108
+ $stateType: [],
1109
+ priority: 5,
1110
+ usage: [term],
1111
+ initialState: void 0,
1112
+ parse(context) {
1113
+ if (context.buffer.length < 1) return {
1114
+ success: false,
1115
+ consumed: 0,
1116
+ error: options.errors?.endOfInput ?? message`Expected an argument, but got end of input.`
1117
+ };
1118
+ let i = 0;
1119
+ let optionsTerminated = context.optionsTerminated;
1120
+ if (!optionsTerminated) {
1121
+ if (context.buffer[i] === "--") {
1122
+ optionsTerminated = true;
1123
+ i++;
1124
+ } else if (context.buffer[i].match(optionPattern)) return {
1125
+ success: false,
1126
+ consumed: i,
1127
+ error: message`Expected an argument, but got an option: ${optionName(context.buffer[i])}.`
1128
+ };
1129
+ }
1130
+ if (context.buffer.length < i + 1) return {
1131
+ success: false,
1132
+ consumed: i,
1133
+ error: message`Expected an argument, but got end of input.`
1134
+ };
1135
+ if (context.state != null) return {
1136
+ success: false,
1137
+ consumed: i,
1138
+ error: options.errors?.multiple ? typeof options.errors.multiple === "function" ? options.errors.multiple(valueParser.metavar) : options.errors.multiple : message`The argument ${metavar(valueParser.metavar)} cannot be used multiple times.`
1139
+ };
1140
+ const result = valueParser.parse(context.buffer[i]);
1141
+ return {
1142
+ success: true,
1143
+ next: {
1144
+ ...context,
1145
+ buffer: context.buffer.slice(i + 1),
1146
+ state: result,
1147
+ optionsTerminated
1148
+ },
1149
+ consumed: context.buffer.slice(0, i + 1)
1150
+ };
1151
+ },
1152
+ complete(state) {
1153
+ if (state == null) return {
1154
+ success: false,
1155
+ error: options.errors?.endOfInput ?? message`Expected a ${metavar(valueParser.metavar)}, but too few arguments.`
1156
+ };
1157
+ else if (state.success) return state;
1158
+ return {
1159
+ success: false,
1160
+ error: options.errors?.invalidValue ? typeof options.errors.invalidValue === "function" ? options.errors.invalidValue(state.error) : options.errors.invalidValue : message`${metavar(valueParser.metavar)}: ${state.error}`
1161
+ };
1162
+ },
1163
+ getDocFragments(_state, defaultValue) {
1164
+ return {
1165
+ fragments: [{
1166
+ type: "entry",
1167
+ term,
1168
+ description: options.description,
1169
+ default: defaultValue == null ? void 0 : message`${valueParser.format(defaultValue)}`
1170
+ }],
1171
+ description: options.description
1172
+ };
1173
+ },
1174
+ [Symbol.for("Deno.customInspect")]() {
1175
+ return `argument()`;
1176
+ }
1177
+ };
1178
+ }
1179
+ function command(name, parser, options = {}) {
1180
+ return {
1181
+ $valueType: [],
1182
+ $stateType: [],
1183
+ priority: 15,
1184
+ usage: [{
1185
+ type: "command",
1186
+ name
1187
+ }, ...parser.usage],
1188
+ initialState: void 0,
1189
+ parse(context) {
1190
+ if (context.state === void 0) {
1191
+ if (context.buffer.length < 1 || context.buffer[0] !== name) {
1192
+ const actual = context.buffer.length > 0 ? context.buffer[0] : null;
1193
+ const errorMessage = options.errors?.notMatched ?? message`Expected command ${optionName(name)}, but got ${actual ?? "end of input"}.`;
1194
+ return {
1195
+ success: false,
1196
+ consumed: 0,
1197
+ error: typeof errorMessage === "function" ? errorMessage(name, actual) : errorMessage
1198
+ };
1199
+ }
1200
+ return {
1201
+ success: true,
1202
+ next: {
1203
+ ...context,
1204
+ buffer: context.buffer.slice(1),
1205
+ state: ["matched", name]
1206
+ },
1207
+ consumed: context.buffer.slice(0, 1)
1208
+ };
1209
+ } else if (context.state[0] === "matched") {
1210
+ const result = parser.parse({
1211
+ ...context,
1212
+ state: parser.initialState
1213
+ });
1214
+ if (result.success) return {
1215
+ success: true,
1216
+ next: {
1217
+ ...result.next,
1218
+ state: ["parsing", result.next.state]
1219
+ },
1220
+ consumed: result.consumed
1221
+ };
1222
+ return result;
1223
+ } else if (context.state[0] === "parsing") {
1224
+ const result = parser.parse({
1225
+ ...context,
1226
+ state: context.state[1]
1227
+ });
1228
+ if (result.success) return {
1229
+ success: true,
1230
+ next: {
1231
+ ...result.next,
1232
+ state: ["parsing", result.next.state]
1233
+ },
1234
+ consumed: result.consumed
1235
+ };
1236
+ return result;
1237
+ }
1238
+ return {
1239
+ success: false,
1240
+ consumed: 0,
1241
+ error: options.errors?.invalidState ?? message`Invalid command state.`
1242
+ };
1243
+ },
1244
+ complete(state) {
1245
+ if (typeof state === "undefined") return {
1246
+ success: false,
1247
+ error: options.errors?.notFound ?? message`Command ${optionName(name)} was not matched.`
1248
+ };
1249
+ else if (state[0] === "matched") return parser.complete(parser.initialState);
1250
+ else if (state[0] === "parsing") return parser.complete(state[1]);
1251
+ return {
1252
+ success: false,
1253
+ error: options.errors?.invalidState ?? message`Invalid command state during completion.`
1254
+ };
1255
+ },
1256
+ getDocFragments(state, defaultValue) {
1257
+ if (state.kind === "unavailable" || typeof state.state === "undefined") return {
1258
+ description: options.description,
1259
+ fragments: [{
1260
+ type: "entry",
1261
+ term: {
1262
+ type: "command",
1263
+ name
1264
+ },
1265
+ description: options.description
1266
+ }]
1267
+ };
1268
+ const innerState = state.state[0] === "parsing" ? {
1269
+ kind: "available",
1270
+ state: state.state[1]
1271
+ } : { kind: "unavailable" };
1272
+ const innerFragments = parser.getDocFragments(innerState, defaultValue);
1273
+ return {
1274
+ ...innerFragments,
1275
+ description: innerFragments.description ?? options.description
1276
+ };
1277
+ },
1278
+ [Symbol.for("Deno.customInspect")]() {
1279
+ return `command(${JSON.stringify(name)})`;
1280
+ }
1281
+ };
1282
+ }
1283
+ function parse(parser, args) {
1284
+ let context = {
1285
+ buffer: args,
1286
+ optionsTerminated: false,
1287
+ state: parser.initialState
1288
+ };
1289
+ do {
1290
+ const result = parser.parse(context);
1291
+ if (!result.success) return {
1292
+ success: false,
1293
+ error: result.error
1294
+ };
1295
+ const previousBuffer = context.buffer;
1296
+ context = result.next;
1297
+ if (context.buffer.length > 0 && context.buffer.length === previousBuffer.length && context.buffer[0] === previousBuffer[0]) return {
1298
+ success: false,
1299
+ error: message`Unexpected option or argument: ${context.buffer[0]}.`
1300
+ };
1301
+ } while (context.buffer.length > 0);
1302
+ const endResult = parser.complete(context.state);
1303
+ return endResult.success ? {
1304
+ success: true,
1305
+ value: endResult.value
1306
+ } : {
1307
+ success: false,
1308
+ error: endResult.error
1309
+ };
1310
+ }
1311
+ function getDocPage(parser, args = []) {
1312
+ let context = {
1313
+ buffer: args,
1314
+ optionsTerminated: false,
1315
+ state: parser.initialState
1316
+ };
1317
+ do {
1318
+ const result = parser.parse(context);
1319
+ if (!result.success) break;
1320
+ context = result.next;
1321
+ } while (context.buffer.length > 0);
1322
+ const { description, fragments } = parser.getDocFragments({
1323
+ kind: "available",
1324
+ state: context.state
1325
+ }, void 0);
1326
+ const entries = fragments.filter((f$1) => f$1.type === "entry");
1327
+ const sections = [];
1328
+ for (const fragment of fragments) {
1329
+ if (fragment.type !== "section") continue;
1330
+ if (fragment.title == null) entries.push(...fragment.entries);
1331
+ else sections.push(fragment);
1332
+ }
1333
+ if (entries.length > 0) sections.push({ entries });
1334
+ const usage = [...normalizeUsage(parser.usage)];
1335
+ let i = 0;
1336
+ for (const arg of args) {
1337
+ const term = usage[i];
1338
+ if (usage.length > i && term.type === "exclusive") for (const termGroup of term.terms) {
1339
+ const firstTerm = termGroup[0];
1340
+ if (firstTerm?.type !== "command" || firstTerm.name !== arg) continue;
1341
+ usage.splice(i, 1, ...termGroup);
1342
+ break;
1343
+ }
1344
+ i++;
1345
+ }
1346
+ return description == null ? {
1347
+ usage,
1348
+ sections
1349
+ } : {
1350
+ usage,
1351
+ sections,
1352
+ description
1353
+ };
1354
+ }
1355
+ function createHelpParser(mode) {
1356
+ const helpCommand = command("help", multiple(argument(string({ metavar: "COMMAND" }))), { description: message`Show help information.` });
1357
+ const helpOption = flag("--help", { description: message`Show help information.` });
1358
+ switch (mode) {
1359
+ case "command": return {
1360
+ helpCommand,
1361
+ helpOption: null
1362
+ };
1363
+ case "option": return {
1364
+ helpCommand: null,
1365
+ helpOption
1366
+ };
1367
+ case "both": return {
1368
+ helpCommand,
1369
+ helpOption
1370
+ };
1371
+ }
1372
+ }
1373
+ function createVersionParser(mode) {
1374
+ const versionCommand = command("version", object({}), { description: message`Show version information.` });
1375
+ const versionOption = flag("--version", { description: message`Show version information.` });
1376
+ switch (mode) {
1377
+ case "command": return {
1378
+ versionCommand,
1379
+ versionOption: null
1380
+ };
1381
+ case "option": return {
1382
+ versionCommand: null,
1383
+ versionOption
1384
+ };
1385
+ case "both": return {
1386
+ versionCommand,
1387
+ versionOption
1388
+ };
1389
+ }
1390
+ }
1391
+ function combineWithHelpVersion(originalParser, helpParsers, versionParsers) {
1392
+ const parsers = [];
1393
+ if (helpParsers.helpOption) {
1394
+ const lenientHelpParser = {
1395
+ $valueType: [],
1396
+ $stateType: [],
1397
+ priority: 200,
1398
+ usage: helpParsers.helpOption.usage,
1399
+ initialState: null,
1400
+ parse(context) {
1401
+ const { buffer, optionsTerminated } = context;
1402
+ if (optionsTerminated) return {
1403
+ success: false,
1404
+ error: message`Options terminated.`,
1405
+ consumed: 0
1406
+ };
1407
+ let helpFound = false;
1408
+ let helpIndex = -1;
1409
+ let versionIndex = -1;
1410
+ for (let i = 0; i < buffer.length; i++) {
1411
+ if (buffer[i] === "--") break;
1412
+ if (buffer[i] === "--help") {
1413
+ helpFound = true;
1414
+ helpIndex = i;
1415
+ }
1416
+ if (buffer[i] === "--version") versionIndex = i;
1417
+ }
1418
+ if (helpFound && versionIndex > helpIndex) return {
1419
+ success: false,
1420
+ error: message`Version option wins.`,
1421
+ consumed: 0
1422
+ };
1423
+ if (helpFound) {
1424
+ const commands = [];
1425
+ for (let i = 0; i < helpIndex; i++) {
1426
+ const arg = buffer[i];
1427
+ if (!arg.startsWith("-")) commands.push(arg);
1428
+ }
1429
+ return {
1430
+ success: true,
1431
+ next: {
1432
+ ...context,
1433
+ buffer: [],
1434
+ state: {
1435
+ help: true,
1436
+ version: false,
1437
+ commands,
1438
+ helpFlag: true
1439
+ }
1440
+ },
1441
+ consumed: buffer.slice(0)
1442
+ };
1443
+ }
1444
+ return {
1445
+ success: false,
1446
+ error: message`Flag ${optionName("--help")} not found.`,
1447
+ consumed: 0
1448
+ };
1449
+ },
1450
+ complete(state) {
1451
+ return {
1452
+ success: true,
1453
+ value: state
1454
+ };
1455
+ },
1456
+ getDocFragments(state) {
1457
+ return helpParsers.helpOption?.getDocFragments(state) ?? { fragments: [] };
1458
+ }
1459
+ };
1460
+ parsers.push(lenientHelpParser);
1461
+ }
1462
+ if (versionParsers.versionOption) {
1463
+ const lenientVersionParser = {
1464
+ $valueType: [],
1465
+ $stateType: [],
1466
+ priority: 200,
1467
+ usage: versionParsers.versionOption.usage,
1468
+ initialState: null,
1469
+ parse(context) {
1470
+ const { buffer, optionsTerminated } = context;
1471
+ if (optionsTerminated) return {
1472
+ success: false,
1473
+ error: message`Options terminated.`,
1474
+ consumed: 0
1475
+ };
1476
+ let versionFound = false;
1477
+ let versionIndex = -1;
1478
+ let helpIndex = -1;
1479
+ for (let i = 0; i < buffer.length; i++) {
1480
+ if (buffer[i] === "--") break;
1481
+ if (buffer[i] === "--version") {
1482
+ versionFound = true;
1483
+ versionIndex = i;
1484
+ }
1485
+ if (buffer[i] === "--help") helpIndex = i;
1486
+ }
1487
+ if (versionFound && helpIndex > versionIndex) return {
1488
+ success: false,
1489
+ error: message`Help option wins.`,
1490
+ consumed: 0
1491
+ };
1492
+ if (versionFound) return {
1493
+ success: true,
1494
+ next: {
1495
+ ...context,
1496
+ buffer: [],
1497
+ state: {
1498
+ help: false,
1499
+ version: true,
1500
+ versionFlag: true
1501
+ }
1502
+ },
1503
+ consumed: buffer.slice(0)
1504
+ };
1505
+ return {
1506
+ success: false,
1507
+ error: message`Flag ${optionName("--version")} not found.`,
1508
+ consumed: 0
1509
+ };
1510
+ },
1511
+ complete(state) {
1512
+ return {
1513
+ success: true,
1514
+ value: state
1515
+ };
1516
+ },
1517
+ getDocFragments(state) {
1518
+ return versionParsers.versionOption?.getDocFragments(state) ?? { fragments: [] };
1519
+ }
1520
+ };
1521
+ parsers.push(lenientVersionParser);
1522
+ }
1523
+ if (versionParsers.versionCommand) parsers.push(object({
1524
+ help: constant(false),
1525
+ version: constant(true),
1526
+ result: versionParsers.versionCommand,
1527
+ helpFlag: helpParsers.helpOption ? optional(helpParsers.helpOption) : constant(false)
1528
+ }));
1529
+ if (helpParsers.helpCommand) parsers.push(object({
1530
+ help: constant(true),
1531
+ version: constant(false),
1532
+ commands: helpParsers.helpCommand
1533
+ }));
1534
+ parsers.push(object({
1535
+ help: constant(false),
1536
+ version: constant(false),
1537
+ result: originalParser
1538
+ }));
1539
+ if (parsers.length === 1) return parsers[0];
1540
+ else if (parsers.length === 2) return longestMatch(parsers[0], parsers[1]);
1541
+ else return longestMatch(...parsers);
1542
+ }
1543
+ function classifyResult(result, args) {
1544
+ if (!result.success) return {
1545
+ type: "error",
1546
+ error: result.error
1547
+ };
1548
+ const value = result.value;
1549
+ if (typeof value === "object" && value != null && "help" in value && "version" in value) {
1550
+ const parsedValue = value;
1551
+ const hasVersionOption = args.includes("--version");
1552
+ const hasVersionCommand = args.length > 0 && args[0] === "version";
1553
+ const hasHelpOption = args.includes("--help");
1554
+ const hasHelpCommand = args.length > 0 && args[0] === "help";
1555
+ if (hasVersionOption && hasHelpOption && !hasVersionCommand && !hasHelpCommand) {}
1556
+ if (hasVersionCommand && hasHelpOption && parsedValue.helpFlag) return {
1557
+ type: "help",
1558
+ commands: ["version"]
1559
+ };
1560
+ if (parsedValue.help && (hasHelpOption || hasHelpCommand)) {
1561
+ let commandContext = [];
1562
+ if (Array.isArray(parsedValue.commands)) commandContext = parsedValue.commands;
1563
+ else if (typeof parsedValue.commands === "object" && parsedValue.commands != null && "length" in parsedValue.commands) commandContext = parsedValue.commands;
1564
+ return {
1565
+ type: "help",
1566
+ commands: commandContext
1567
+ };
1568
+ }
1569
+ if ((hasVersionOption || hasVersionCommand) && (parsedValue.version || parsedValue.versionFlag)) return { type: "version" };
1570
+ return {
1571
+ type: "success",
1572
+ value: parsedValue.result ?? value
1573
+ };
1574
+ }
1575
+ return {
1576
+ type: "success",
1577
+ value
1578
+ };
1579
+ }
1580
+ function run$1(parser, programName, args, options = {}) {
1581
+ const helpMode = options.help?.mode ?? "option";
1582
+ const onHelp = options.help?.onShow ?? (() => ({}));
1583
+ const versionMode = options.version?.mode ?? "option";
1584
+ const versionValue = options.version?.value ?? "";
1585
+ const onVersion = options.version?.onShow ?? (() => ({}));
1586
+ let { colors, maxWidth, showDefault, aboveError = "usage", onError = () => {
1587
+ throw new RunError("Failed to parse command line arguments.");
1588
+ }, stderr = console.error, stdout = console.log, brief, description, footer } = options;
1589
+ const help = options.help ? helpMode : "none";
1590
+ const version = options.version ? versionMode : "none";
1591
+ const helpParsers = help === "none" ? {
1592
+ helpCommand: null,
1593
+ helpOption: null
1594
+ } : createHelpParser(help);
1595
+ const versionParsers = version === "none" ? {
1596
+ versionCommand: null,
1597
+ versionOption: null
1598
+ } : createVersionParser(version);
1599
+ const augmentedParser = help === "none" && version === "none" ? parser : combineWithHelpVersion(parser, helpParsers, versionParsers);
1600
+ const result = parse(augmentedParser, args);
1601
+ const classified = classifyResult(result, args);
1602
+ switch (classified.type) {
1603
+ case "success": return classified.value;
1604
+ case "version":
1605
+ stdout(versionValue);
1606
+ try {
1607
+ return onVersion(0);
1608
+ } catch {
1609
+ return onVersion();
1610
+ }
1611
+ case "help": {
1612
+ let helpGeneratorParser;
1613
+ const helpAsCommand = help === "command" || help === "both";
1614
+ const versionAsCommand = version === "command" || version === "both";
1615
+ if (helpAsCommand && versionAsCommand) {
1616
+ const tempHelpParsers = createHelpParser(help);
1617
+ const tempVersionParsers = createVersionParser(version);
1618
+ if (tempHelpParsers.helpCommand && tempVersionParsers.versionCommand) helpGeneratorParser = longestMatch(parser, tempHelpParsers.helpCommand, tempVersionParsers.versionCommand);
1619
+ else if (tempHelpParsers.helpCommand) helpGeneratorParser = longestMatch(parser, tempHelpParsers.helpCommand);
1620
+ else if (tempVersionParsers.versionCommand) helpGeneratorParser = longestMatch(parser, tempVersionParsers.versionCommand);
1621
+ else helpGeneratorParser = parser;
1622
+ } else if (helpAsCommand) {
1623
+ const tempHelpParsers = createHelpParser(help);
1624
+ if (tempHelpParsers.helpCommand) helpGeneratorParser = longestMatch(parser, tempHelpParsers.helpCommand);
1625
+ else helpGeneratorParser = parser;
1626
+ } else if (versionAsCommand) {
1627
+ const tempVersionParsers = createVersionParser(version);
1628
+ if (tempVersionParsers.versionCommand) helpGeneratorParser = longestMatch(parser, tempVersionParsers.versionCommand);
1629
+ else helpGeneratorParser = parser;
1630
+ } else helpGeneratorParser = parser;
1631
+ const doc = getDocPage(helpGeneratorParser, classified.commands);
1632
+ if (doc != null) {
1633
+ const augmentedDoc = {
1634
+ ...doc,
1635
+ brief: brief ?? doc.brief,
1636
+ description: description ?? doc.description,
1637
+ footer: footer ?? doc.footer
1638
+ };
1639
+ stdout(formatDocPage(programName, augmentedDoc, {
1640
+ colors,
1641
+ maxWidth,
1642
+ showDefault
1643
+ }));
1644
+ }
1645
+ try {
1646
+ return onHelp(0);
1647
+ } catch {
1648
+ return onHelp();
1649
+ }
1650
+ }
1651
+ case "error": break;
1652
+ }
1653
+ if (aboveError === "help") {
1654
+ const doc = getDocPage(args.length < 1 ? augmentedParser : parser, args);
1655
+ if (doc == null) aboveError = "usage";
1656
+ else {
1657
+ const augmentedDoc = {
1658
+ ...doc,
1659
+ brief: brief ?? doc.brief,
1660
+ description: description ?? doc.description,
1661
+ footer: footer ?? doc.footer
1662
+ };
1663
+ stderr(formatDocPage(programName, augmentedDoc, {
1664
+ colors,
1665
+ maxWidth,
1666
+ showDefault
1667
+ }));
1668
+ }
1669
+ }
1670
+ if (aboveError === "usage") stderr(`Usage: ${indentLines(formatUsage(programName, augmentedParser.usage, {
1671
+ colors,
1672
+ maxWidth: maxWidth == null ? void 0 : maxWidth - 7,
1673
+ expandCommands: true
1674
+ }), 7)}`);
1675
+ const errorMessage = formatMessage(classified.error, {
1676
+ colors,
1677
+ quotes: !colors
1678
+ });
1679
+ stderr(`Error: ${errorMessage}`);
1680
+ return onError(1);
1681
+ }
1682
+ var RunError = class extends Error {
1683
+ constructor(message$1) {
1684
+ super(message$1);
1685
+ this.name = "RunError";
1686
+ }
1687
+ };
1688
+ function indentLines(text$1, indent) {
1689
+ return text$1.split("\n").join("\n" + " ".repeat(indent));
1690
+ }
1691
+ function run(parser, options = {}) {
1692
+ const { programName = path.basename(process$1.argv[1] || "cli"), args = process$1.argv.slice(2), colors = process$1.stdout.isTTY, maxWidth = process$1.stdout.columns, showDefault, help, version, aboveError = "usage", errorExitCode = 1, brief, description, footer } = options;
1693
+ const helpConfig = help ? {
1694
+ mode: help,
1695
+ onShow: () => process$1.exit(0)
1696
+ } : void 0;
1697
+ const versionConfig = version ? {
1698
+ mode: typeof version === "string" ? "option" : version.mode ?? "option",
1699
+ value: typeof version === "string" ? version : version.value,
1700
+ onShow: () => process$1.exit(0)
1701
+ } : void 0;
1702
+ return run$1(parser, programName, args, {
1703
+ colors,
1704
+ maxWidth,
1705
+ showDefault,
1706
+ help: helpConfig,
1707
+ version: versionConfig,
1708
+ aboveError,
1709
+ brief,
1710
+ description,
1711
+ footer,
1712
+ onError() {
1713
+ return process$1.exit(errorExitCode);
1714
+ }
1715
+ });
1716
+ }
1717
+ const A = (r) => r !== null && typeof r == "object", a = (r, t) => Object.assign(/* @__PURE__ */ new Error(`[${r}]: ${t}`), { code: r }), _ = "ERR_INVALID_PACKAGE_CONFIG", E$1 = "ERR_INVALID_PACKAGE_TARGET", I = "ERR_PACKAGE_PATH_NOT_EXPORTED", R$1 = /^\d+$/, O$1 = /^(\.{1,2}|node_modules)$/i, w = /\/|\\/;
1718
+ var h$1 = ((r) => (r.Export = "exports", r.Import = "imports", r))(h$1 || {});
1719
+ const f = (r, t, e, o$1, c) => {
1720
+ if (t == null) return [];
1721
+ if (typeof t == "string") {
1722
+ const [n, ...i] = t.split(w);
1723
+ if (n === ".." || i.some((l) => O$1.test(l))) throw a(E$1, `Invalid "${r}" target "${t}" defined in the package config`);
1724
+ return [c ? t.replace(/\*/g, c) : t];
1725
+ }
1726
+ if (Array.isArray(t)) return t.flatMap((n) => f(r, n, e, o$1, c));
1727
+ if (A(t)) {
1728
+ for (const n of Object.keys(t)) {
1729
+ if (R$1.test(n)) throw a(_, "Cannot contain numeric property keys");
1730
+ if (n === "default" || o$1.includes(n)) return f(r, t[n], e, o$1, c);
1731
+ }
1732
+ return [];
1733
+ }
1734
+ throw a(E$1, `Invalid "${r}" target "${t}"`);
1735
+ }, s = "*", m = (r, t) => {
1736
+ const e = r.indexOf(s), o$1 = t.indexOf(s);
1737
+ return e === o$1 ? t.length > r.length : o$1 > e;
1738
+ };
1739
+ function d(r, t) {
1740
+ if (!t.includes(s) && r.hasOwnProperty(t)) return [t];
1741
+ let e, o$1;
1742
+ for (const c of Object.keys(r)) if (c.includes(s)) {
1743
+ const [n, i, l] = c.split(s);
1744
+ if (l === void 0 && t.startsWith(n) && t.endsWith(i)) {
1745
+ const g = t.slice(n.length, -i.length || void 0);
1746
+ g && (!e || m(e, c)) && (e = c, o$1 = g);
1747
+ }
1748
+ }
1749
+ return [e, o$1];
1750
+ }
1751
+ const p$1 = (r) => Object.keys(r).reduce((t, e) => {
1752
+ const o$1 = e === "" || e[0] !== ".";
1753
+ if (t === void 0 || t === o$1) return o$1;
1754
+ throw a(_, "\"exports\" cannot contain some keys starting with \".\" and some not");
1755
+ }, void 0), u = /^\w+:/, v = (r, t, e) => {
1756
+ if (!r) throw new Error("\"exports\" is required");
1757
+ t = t === "" ? "." : `./${t}`, (typeof r == "string" || Array.isArray(r) || A(r) && p$1(r)) && (r = { ".": r });
1758
+ const [o$1, c] = d(r, t), n = f(h$1.Export, r[o$1], t, e, c);
1759
+ if (n.length === 0) throw a(I, t === "." ? "No \"exports\" main defined" : `Package subpath '${t}' is not defined by "exports"`);
1760
+ for (const i of n) if (!i.startsWith("./") && !u.test(i)) throw a(E$1, `Invalid "exports" target "${i}" defined in the package config`);
1761
+ return n;
1762
+ };
1763
+ var de = Object.defineProperty;
1764
+ var o = (e, t) => de(e, "name", {
1765
+ value: t,
1766
+ configurable: !0
1767
+ });
1768
+ function E(e) {
1769
+ return e.startsWith("\\\\?\\") ? e : e.replace(/\\/g, "/");
1770
+ }
1771
+ o(E, "slash");
1772
+ const O = o((e) => {
1773
+ const t = fss[e];
1774
+ return (s$1, ...n) => {
1775
+ const l = `${e}:${n.join(":")}`;
1776
+ let i = s$1 == null ? void 0 : s$1.get(l);
1777
+ return i === void 0 && (i = Reflect.apply(t, fss, n), s$1?.set(l, i)), i;
1778
+ };
1779
+ }, "cacheFs"), B = O("existsSync"), _e = O("readFileSync"), P = O("statSync"), se = o((e, t, s$1) => {
1780
+ for (;;) {
1781
+ const n = path.posix.join(e, t);
1782
+ if (B(s$1, n)) return n;
1783
+ const l = path.dirname(e);
1784
+ if (l === e) return;
1785
+ e = l;
1786
+ }
1787
+ }, "findUp"), z = /^\.{1,2}(\/.*)?$/, G = o((e) => {
1788
+ const t = E(e);
1789
+ return z.test(t) ? t : `./${t}`;
1790
+ }, "normalizeRelativePath");
1791
+ function je(e, t = !1) {
1792
+ const s$1 = e.length;
1793
+ let n = 0, l = "", i = 0, u$1 = 16, f$1 = 0, r = 0, g = 0, T$1 = 0, b = 0;
1794
+ function _$1(c, k) {
1795
+ let p$2 = 0, F = 0;
1796
+ for (; p$2 < c;) {
1797
+ let j = e.charCodeAt(n);
1798
+ if (j >= 48 && j <= 57) F = F * 16 + j - 48;
1799
+ else if (j >= 65 && j <= 70) F = F * 16 + j - 65 + 10;
1800
+ else if (j >= 97 && j <= 102) F = F * 16 + j - 97 + 10;
1801
+ else break;
1802
+ n++, p$2++;
1803
+ }
1804
+ return p$2 < c && (F = -1), F;
1805
+ }
1806
+ o(_$1, "scanHexDigits");
1807
+ function d$1(c) {
1808
+ n = c, l = "", i = 0, u$1 = 16, b = 0;
1809
+ }
1810
+ o(d$1, "setPosition");
1811
+ function A$1() {
1812
+ let c = n;
1813
+ if (e.charCodeAt(n) === 48) n++;
1814
+ else for (n++; n < e.length && U(e.charCodeAt(n));) n++;
1815
+ if (n < e.length && e.charCodeAt(n) === 46) if (n++, n < e.length && U(e.charCodeAt(n))) for (n++; n < e.length && U(e.charCodeAt(n));) n++;
1816
+ else return b = 3, e.substring(c, n);
1817
+ let k = n;
1818
+ if (n < e.length && (e.charCodeAt(n) === 69 || e.charCodeAt(n) === 101)) if (n++, (n < e.length && e.charCodeAt(n) === 43 || e.charCodeAt(n) === 45) && n++, n < e.length && U(e.charCodeAt(n))) {
1819
+ for (n++; n < e.length && U(e.charCodeAt(n));) n++;
1820
+ k = n;
1821
+ } else b = 3;
1822
+ return e.substring(c, k);
1823
+ }
1824
+ o(A$1, "scanNumber");
1825
+ function w$1() {
1826
+ let c = "", k = n;
1827
+ for (;;) {
1828
+ if (n >= s$1) {
1829
+ c += e.substring(k, n), b = 2;
1830
+ break;
1831
+ }
1832
+ const p$2 = e.charCodeAt(n);
1833
+ if (p$2 === 34) {
1834
+ c += e.substring(k, n), n++;
1835
+ break;
1836
+ }
1837
+ if (p$2 === 92) {
1838
+ if (c += e.substring(k, n), n++, n >= s$1) {
1839
+ b = 2;
1840
+ break;
1841
+ }
1842
+ switch (e.charCodeAt(n++)) {
1843
+ case 34:
1844
+ c += "\"";
1845
+ break;
1846
+ case 92:
1847
+ c += "\\";
1848
+ break;
1849
+ case 47:
1850
+ c += "/";
1851
+ break;
1852
+ case 98:
1853
+ c += "\b";
1854
+ break;
1855
+ case 102:
1856
+ c += "\f";
1857
+ break;
1858
+ case 110:
1859
+ c += `
1860
+ `;
1861
+ break;
1862
+ case 114:
1863
+ c += "\r";
1864
+ break;
1865
+ case 116:
1866
+ c += " ";
1867
+ break;
1868
+ case 117:
1869
+ const j = _$1(4);
1870
+ j >= 0 ? c += String.fromCharCode(j) : b = 4;
1871
+ break;
1872
+ default: b = 5;
1873
+ }
1874
+ k = n;
1875
+ continue;
1876
+ }
1877
+ if (p$2 >= 0 && p$2 <= 31) if (x(p$2)) {
1878
+ c += e.substring(k, n), b = 2;
1879
+ break;
1880
+ } else b = 6;
1881
+ n++;
1882
+ }
1883
+ return c;
1884
+ }
1885
+ o(w$1, "scanString");
1886
+ function y() {
1887
+ if (l = "", b = 0, i = n, r = f$1, T$1 = g, n >= s$1) return i = s$1, u$1 = 17;
1888
+ let c = e.charCodeAt(n);
1889
+ if (Q(c)) {
1890
+ do
1891
+ n++, l += String.fromCharCode(c), c = e.charCodeAt(n);
1892
+ while (Q(c));
1893
+ return u$1 = 15;
1894
+ }
1895
+ if (x(c)) return n++, l += String.fromCharCode(c), c === 13 && e.charCodeAt(n) === 10 && (n++, l += `
1896
+ `), f$1++, g = n, u$1 = 14;
1897
+ switch (c) {
1898
+ case 123: return n++, u$1 = 1;
1899
+ case 125: return n++, u$1 = 2;
1900
+ case 91: return n++, u$1 = 3;
1901
+ case 93: return n++, u$1 = 4;
1902
+ case 58: return n++, u$1 = 6;
1903
+ case 44: return n++, u$1 = 5;
1904
+ case 34: return n++, l = w$1(), u$1 = 10;
1905
+ case 47:
1906
+ const k = n - 1;
1907
+ if (e.charCodeAt(n + 1) === 47) {
1908
+ for (n += 2; n < s$1 && !x(e.charCodeAt(n));) n++;
1909
+ return l = e.substring(k, n), u$1 = 12;
1910
+ }
1911
+ if (e.charCodeAt(n + 1) === 42) {
1912
+ n += 2;
1913
+ const p$2 = s$1 - 1;
1914
+ let F = !1;
1915
+ for (; n < p$2;) {
1916
+ const j = e.charCodeAt(n);
1917
+ if (j === 42 && e.charCodeAt(n + 1) === 47) {
1918
+ n += 2, F = !0;
1919
+ break;
1920
+ }
1921
+ n++, x(j) && (j === 13 && e.charCodeAt(n) === 10 && n++, f$1++, g = n);
1922
+ }
1923
+ return F || (n++, b = 1), l = e.substring(k, n), u$1 = 13;
1924
+ }
1925
+ return l += String.fromCharCode(c), n++, u$1 = 16;
1926
+ case 45: if (l += String.fromCharCode(c), n++, n === s$1 || !U(e.charCodeAt(n))) return u$1 = 16;
1927
+ case 48:
1928
+ case 49:
1929
+ case 50:
1930
+ case 51:
1931
+ case 52:
1932
+ case 53:
1933
+ case 54:
1934
+ case 55:
1935
+ case 56:
1936
+ case 57: return l += A$1(), u$1 = 11;
1937
+ default:
1938
+ for (; n < s$1 && I$1(c);) n++, c = e.charCodeAt(n);
1939
+ if (i !== n) {
1940
+ switch (l = e.substring(i, n), l) {
1941
+ case "true": return u$1 = 8;
1942
+ case "false": return u$1 = 9;
1943
+ case "null": return u$1 = 7;
1944
+ }
1945
+ return u$1 = 16;
1946
+ }
1947
+ return l += String.fromCharCode(c), n++, u$1 = 16;
1948
+ }
1949
+ }
1950
+ o(y, "scanNext");
1951
+ function I$1(c) {
1952
+ if (Q(c) || x(c)) return !1;
1953
+ switch (c) {
1954
+ case 125:
1955
+ case 93:
1956
+ case 123:
1957
+ case 91:
1958
+ case 34:
1959
+ case 58:
1960
+ case 44:
1961
+ case 47: return !1;
1962
+ }
1963
+ return !0;
1964
+ }
1965
+ o(I$1, "isUnknownContentCharacter");
1966
+ function L() {
1967
+ let c;
1968
+ do
1969
+ c = y();
1970
+ while (c >= 12 && c <= 15);
1971
+ return c;
1972
+ }
1973
+ return o(L, "scanNextNonTrivia"), {
1974
+ setPosition: d$1,
1975
+ getPosition: o(() => n, "getPosition"),
1976
+ scan: t ? L : y,
1977
+ getToken: o(() => u$1, "getToken"),
1978
+ getTokenValue: o(() => l, "getTokenValue"),
1979
+ getTokenOffset: o(() => i, "getTokenOffset"),
1980
+ getTokenLength: o(() => n - i, "getTokenLength"),
1981
+ getTokenStartLine: o(() => r, "getTokenStartLine"),
1982
+ getTokenStartCharacter: o(() => i - T$1, "getTokenStartCharacter"),
1983
+ getTokenError: o(() => b, "getTokenError")
1984
+ };
1985
+ }
1986
+ o(je, "createScanner");
1987
+ function Q(e) {
1988
+ return e === 32 || e === 9;
1989
+ }
1990
+ o(Q, "isWhiteSpace");
1991
+ function x(e) {
1992
+ return e === 10 || e === 13;
1993
+ }
1994
+ o(x, "isLineBreak");
1995
+ function U(e) {
1996
+ return e >= 48 && e <= 57;
1997
+ }
1998
+ o(U, "isDigit");
1999
+ var le;
2000
+ (function(e) {
2001
+ e[e.lineFeed = 10] = "lineFeed", e[e.carriageReturn = 13] = "carriageReturn", e[e.space = 32] = "space", e[e._0 = 48] = "_0", e[e._1 = 49] = "_1", e[e._2 = 50] = "_2", e[e._3 = 51] = "_3", e[e._4 = 52] = "_4", e[e._5 = 53] = "_5", e[e._6 = 54] = "_6", e[e._7 = 55] = "_7", e[e._8 = 56] = "_8", e[e._9 = 57] = "_9", e[e.a = 97] = "a", e[e.b = 98] = "b", e[e.c = 99] = "c", e[e.d = 100] = "d", e[e.e = 101] = "e", e[e.f = 102] = "f", e[e.g = 103] = "g", e[e.h = 104] = "h", e[e.i = 105] = "i", e[e.j = 106] = "j", e[e.k = 107] = "k", e[e.l = 108] = "l", e[e.m = 109] = "m", e[e.n = 110] = "n", e[e.o = 111] = "o", e[e.p = 112] = "p", e[e.q = 113] = "q", e[e.r = 114] = "r", e[e.s = 115] = "s", e[e.t = 116] = "t", e[e.u = 117] = "u", e[e.v = 118] = "v", e[e.w = 119] = "w", e[e.x = 120] = "x", e[e.y = 121] = "y", e[e.z = 122] = "z", e[e.A = 65] = "A", e[e.B = 66] = "B", e[e.C = 67] = "C", e[e.D = 68] = "D", e[e.E = 69] = "E", e[e.F = 70] = "F", e[e.G = 71] = "G", e[e.H = 72] = "H", e[e.I = 73] = "I", e[e.J = 74] = "J", e[e.K = 75] = "K", e[e.L = 76] = "L", e[e.M = 77] = "M", e[e.N = 78] = "N", e[e.O = 79] = "O", e[e.P = 80] = "P", e[e.Q = 81] = "Q", e[e.R = 82] = "R", e[e.S = 83] = "S", e[e.T = 84] = "T", e[e.U = 85] = "U", e[e.V = 86] = "V", e[e.W = 87] = "W", e[e.X = 88] = "X", e[e.Y = 89] = "Y", e[e.Z = 90] = "Z", e[e.asterisk = 42] = "asterisk", e[e.backslash = 92] = "backslash", e[e.closeBrace = 125] = "closeBrace", e[e.closeBracket = 93] = "closeBracket", e[e.colon = 58] = "colon", e[e.comma = 44] = "comma", e[e.dot = 46] = "dot", e[e.doubleQuote = 34] = "doubleQuote", e[e.minus = 45] = "minus", e[e.openBrace = 123] = "openBrace", e[e.openBracket = 91] = "openBracket", e[e.plus = 43] = "plus", e[e.slash = 47] = "slash", e[e.formFeed = 12] = "formFeed", e[e.tab = 9] = "tab";
2002
+ })(le || (le = {})), new Array(20).fill(0).map((e, t) => " ".repeat(t));
2003
+ const h = 200;
2004
+ new Array(h).fill(0).map((e, t) => `
2005
+ ` + " ".repeat(t)), new Array(h).fill(0).map((e, t) => "\r" + " ".repeat(t)), new Array(h).fill(0).map((e, t) => `\r
2006
+ ` + " ".repeat(t)), new Array(h).fill(0).map((e, t) => `
2007
+ ` + " ".repeat(t)), new Array(h).fill(0).map((e, t) => "\r" + " ".repeat(t)), new Array(h).fill(0).map((e, t) => `\r
2008
+ ` + " ".repeat(t));
2009
+ var R;
2010
+ (function(e) {
2011
+ e.DEFAULT = { allowTrailingComma: !1 };
2012
+ })(R || (R = {}));
2013
+ function ye(e, t = [], s$1 = R.DEFAULT) {
2014
+ let n = null, l = [];
2015
+ const i = [];
2016
+ function u$1(r) {
2017
+ Array.isArray(l) ? l.push(r) : n !== null && (l[n] = r);
2018
+ }
2019
+ return o(u$1, "onValue"), Fe(e, {
2020
+ onObjectBegin: o(() => {
2021
+ const r = {};
2022
+ u$1(r), i.push(l), l = r, n = null;
2023
+ }, "onObjectBegin"),
2024
+ onObjectProperty: o((r) => {
2025
+ n = r;
2026
+ }, "onObjectProperty"),
2027
+ onObjectEnd: o(() => {
2028
+ l = i.pop();
2029
+ }, "onObjectEnd"),
2030
+ onArrayBegin: o(() => {
2031
+ const r = [];
2032
+ u$1(r), i.push(l), l = r, n = null;
2033
+ }, "onArrayBegin"),
2034
+ onArrayEnd: o(() => {
2035
+ l = i.pop();
2036
+ }, "onArrayEnd"),
2037
+ onLiteralValue: u$1,
2038
+ onError: o((r, g, T$1) => {
2039
+ t.push({
2040
+ error: r,
2041
+ offset: g,
2042
+ length: T$1
2043
+ });
2044
+ }, "onError")
2045
+ }, s$1), l[0];
2046
+ }
2047
+ o(ye, "parse$1");
2048
+ function Fe(e, t, s$1 = R.DEFAULT) {
2049
+ const n = je(e, !1), l = [];
2050
+ function i(v$1) {
2051
+ return v$1 ? () => v$1(n.getTokenOffset(), n.getTokenLength(), n.getTokenStartLine(), n.getTokenStartCharacter()) : () => !0;
2052
+ }
2053
+ o(i, "toNoArgVisit");
2054
+ function u$1(v$1) {
2055
+ return v$1 ? () => v$1(n.getTokenOffset(), n.getTokenLength(), n.getTokenStartLine(), n.getTokenStartCharacter(), () => l.slice()) : () => !0;
2056
+ }
2057
+ o(u$1, "toNoArgVisitWithPath");
2058
+ function f$1(v$1) {
2059
+ return v$1 ? (D) => v$1(D, n.getTokenOffset(), n.getTokenLength(), n.getTokenStartLine(), n.getTokenStartCharacter()) : () => !0;
2060
+ }
2061
+ o(f$1, "toOneArgVisit");
2062
+ function r(v$1) {
2063
+ return v$1 ? (D) => v$1(D, n.getTokenOffset(), n.getTokenLength(), n.getTokenStartLine(), n.getTokenStartCharacter(), () => l.slice()) : () => !0;
2064
+ }
2065
+ o(r, "toOneArgVisitWithPath");
2066
+ const g = u$1(t.onObjectBegin), T$1 = r(t.onObjectProperty), b = i(t.onObjectEnd), _$1 = u$1(t.onArrayBegin), d$1 = i(t.onArrayEnd), A$1 = r(t.onLiteralValue), w$1 = f$1(t.onSeparator), y = i(t.onComment), I$1 = f$1(t.onError), L = s$1 && s$1.disallowComments, c = s$1 && s$1.allowTrailingComma;
2067
+ function k() {
2068
+ for (;;) {
2069
+ const v$1 = n.scan();
2070
+ switch (n.getTokenError()) {
2071
+ case 4:
2072
+ p$2(14);
2073
+ break;
2074
+ case 5:
2075
+ p$2(15);
2076
+ break;
2077
+ case 3:
2078
+ p$2(13);
2079
+ break;
2080
+ case 1:
2081
+ L || p$2(11);
2082
+ break;
2083
+ case 2:
2084
+ p$2(12);
2085
+ break;
2086
+ case 6:
2087
+ p$2(16);
2088
+ break;
2089
+ }
2090
+ switch (v$1) {
2091
+ case 12:
2092
+ case 13:
2093
+ L ? p$2(10) : y();
2094
+ break;
2095
+ case 16:
2096
+ p$2(1);
2097
+ break;
2098
+ case 15:
2099
+ case 14: break;
2100
+ default: return v$1;
2101
+ }
2102
+ }
2103
+ }
2104
+ o(k, "scanNext");
2105
+ function p$2(v$1, D = [], ne = []) {
2106
+ if (I$1(v$1), D.length + ne.length > 0) {
2107
+ let S = n.getToken();
2108
+ for (; S !== 17;) {
2109
+ if (D.indexOf(S) !== -1) {
2110
+ k();
2111
+ break;
2112
+ } else if (ne.indexOf(S) !== -1) break;
2113
+ S = k();
2114
+ }
2115
+ }
2116
+ }
2117
+ o(p$2, "handleError");
2118
+ function F(v$1) {
2119
+ const D = n.getTokenValue();
2120
+ return v$1 ? A$1(D) : (T$1(D), l.push(D)), k(), !0;
2121
+ }
2122
+ o(F, "parseString");
2123
+ function j() {
2124
+ switch (n.getToken()) {
2125
+ case 11:
2126
+ const v$1 = n.getTokenValue();
2127
+ let D = Number(v$1);
2128
+ isNaN(D) && (p$2(2), D = 0), A$1(D);
2129
+ break;
2130
+ case 7:
2131
+ A$1(null);
2132
+ break;
2133
+ case 8:
2134
+ A$1(!0);
2135
+ break;
2136
+ case 9:
2137
+ A$1(!1);
2138
+ break;
2139
+ default: return !1;
2140
+ }
2141
+ return k(), !0;
2142
+ }
2143
+ o(j, "parseLiteral");
2144
+ function a$1() {
2145
+ return n.getToken() !== 10 ? (p$2(3, [], [2, 5]), !1) : (F(!1), n.getToken() === 6 ? (w$1(":"), k(), J() || p$2(4, [], [2, 5])) : p$2(5, [], [2, 5]), l.pop(), !0);
2146
+ }
2147
+ o(a$1, "parseProperty");
2148
+ function N() {
2149
+ g(), k();
2150
+ let v$1 = !1;
2151
+ for (; n.getToken() !== 2 && n.getToken() !== 17;) {
2152
+ if (n.getToken() === 5) {
2153
+ if (v$1 || p$2(4, [], []), w$1(","), k(), n.getToken() === 2 && c) break;
2154
+ } else v$1 && p$2(6, [], []);
2155
+ a$1() || p$2(4, [], [2, 5]), v$1 = !0;
2156
+ }
2157
+ return b(), n.getToken() !== 2 ? p$2(7, [2], []) : k(), !0;
2158
+ }
2159
+ o(N, "parseObject");
2160
+ function be() {
2161
+ _$1(), k();
2162
+ let v$1 = !0, D = !1;
2163
+ for (; n.getToken() !== 4 && n.getToken() !== 17;) {
2164
+ if (n.getToken() === 5) {
2165
+ if (D || p$2(4, [], []), w$1(","), k(), n.getToken() === 4 && c) break;
2166
+ } else D && p$2(6, [], []);
2167
+ v$1 ? (l.push(0), v$1 = !1) : l[l.length - 1]++, J() || p$2(4, [], [4, 5]), D = !0;
2168
+ }
2169
+ return d$1(), v$1 || l.pop(), n.getToken() !== 4 ? p$2(8, [4], []) : k(), !0;
2170
+ }
2171
+ o(be, "parseArray");
2172
+ function J() {
2173
+ switch (n.getToken()) {
2174
+ case 3: return be();
2175
+ case 1: return N();
2176
+ case 10: return F(!0);
2177
+ default: return j();
2178
+ }
2179
+ }
2180
+ return o(J, "parseValue"), k(), n.getToken() === 17 ? s$1.allowEmptyContent ? !0 : (p$2(4, [], []), !1) : J() ? (n.getToken() !== 17 && p$2(9, [], []), !0) : (p$2(4, [], []), !1);
2181
+ }
2182
+ o(Fe, "visit");
2183
+ var ie;
2184
+ (function(e) {
2185
+ e[e.None = 0] = "None", e[e.UnexpectedEndOfComment = 1] = "UnexpectedEndOfComment", e[e.UnexpectedEndOfString = 2] = "UnexpectedEndOfString", e[e.UnexpectedEndOfNumber = 3] = "UnexpectedEndOfNumber", e[e.InvalidUnicode = 4] = "InvalidUnicode", e[e.InvalidEscapeCharacter = 5] = "InvalidEscapeCharacter", e[e.InvalidCharacter = 6] = "InvalidCharacter";
2186
+ })(ie || (ie = {}));
2187
+ var oe;
2188
+ (function(e) {
2189
+ e[e.OpenBraceToken = 1] = "OpenBraceToken", e[e.CloseBraceToken = 2] = "CloseBraceToken", e[e.OpenBracketToken = 3] = "OpenBracketToken", e[e.CloseBracketToken = 4] = "CloseBracketToken", e[e.CommaToken = 5] = "CommaToken", e[e.ColonToken = 6] = "ColonToken", e[e.NullKeyword = 7] = "NullKeyword", e[e.TrueKeyword = 8] = "TrueKeyword", e[e.FalseKeyword = 9] = "FalseKeyword", e[e.StringLiteral = 10] = "StringLiteral", e[e.NumericLiteral = 11] = "NumericLiteral", e[e.LineCommentTrivia = 12] = "LineCommentTrivia", e[e.BlockCommentTrivia = 13] = "BlockCommentTrivia", e[e.LineBreakTrivia = 14] = "LineBreakTrivia", e[e.Trivia = 15] = "Trivia", e[e.Unknown = 16] = "Unknown", e[e.EOF = 17] = "EOF";
2190
+ })(oe || (oe = {}));
2191
+ const De = ye;
2192
+ var ue;
2193
+ (function(e) {
2194
+ e[e.InvalidSymbol = 1] = "InvalidSymbol", e[e.InvalidNumberFormat = 2] = "InvalidNumberFormat", e[e.PropertyNameExpected = 3] = "PropertyNameExpected", e[e.ValueExpected = 4] = "ValueExpected", e[e.ColonExpected = 5] = "ColonExpected", e[e.CommaExpected = 6] = "CommaExpected", e[e.CloseBraceExpected = 7] = "CloseBraceExpected", e[e.CloseBracketExpected = 8] = "CloseBracketExpected", e[e.EndOfFileExpected = 9] = "EndOfFileExpected", e[e.InvalidCommentToken = 10] = "InvalidCommentToken", e[e.UnexpectedEndOfComment = 11] = "UnexpectedEndOfComment", e[e.UnexpectedEndOfString = 12] = "UnexpectedEndOfString", e[e.UnexpectedEndOfNumber = 13] = "UnexpectedEndOfNumber", e[e.InvalidUnicode = 14] = "InvalidUnicode", e[e.InvalidEscapeCharacter = 15] = "InvalidEscapeCharacter", e[e.InvalidCharacter = 16] = "InvalidCharacter";
2195
+ })(ue || (ue = {}));
2196
+ const re = o((e, t) => De(_e(t, e, "utf8")), "readJsonc"), H = Symbol("implicitBaseUrl"), $ = "${configDir}", Ee = o(() => {
2197
+ const { findPnpApi: e } = ve;
2198
+ return e && e(process.cwd());
2199
+ }, "getPnpApi"), X = o((e, t, s$1, n) => {
2200
+ const l = `resolveFromPackageJsonPath:${e}:${t}:${s$1}`;
2201
+ if (n != null && n.has(l)) return n.get(l);
2202
+ const i = re(e, n);
2203
+ if (!i) return;
2204
+ let u$1 = t || "tsconfig.json";
2205
+ if (!s$1 && i.exports) try {
2206
+ const [f$1] = v(i.exports, t, ["require", "types"]);
2207
+ u$1 = f$1;
2208
+ } catch {
2209
+ return !1;
2210
+ }
2211
+ else !t && i.tsconfig && (u$1 = i.tsconfig);
2212
+ return u$1 = path.join(e, "..", u$1), n?.set(l, u$1), u$1;
2213
+ }, "resolveFromPackageJsonPath"), Y = "package.json", Z = "tsconfig.json", Be = o((e, t, s$1) => {
2214
+ let n = e;
2215
+ if (e === ".." && (n = path.join(n, Z)), e[0] === "." && (n = path.resolve(t, n)), path.isAbsolute(n)) {
2216
+ if (B(s$1, n)) {
2217
+ if (P(s$1, n).isFile()) return n;
2218
+ } else if (!n.endsWith(".json")) {
2219
+ const d$1 = `${n}.json`;
2220
+ if (B(s$1, d$1)) return d$1;
2221
+ }
2222
+ return;
2223
+ }
2224
+ const [l, ...i] = e.split("/"), u$1 = l[0] === "@" ? `${l}/${i.shift()}` : l, f$1 = i.join("/"), r = Ee();
2225
+ if (r) {
2226
+ const { resolveRequest: d$1 } = r;
2227
+ try {
2228
+ if (u$1 === e) {
2229
+ const A$1 = d$1(path.join(u$1, Y), t);
2230
+ if (A$1) {
2231
+ const w$1 = X(A$1, f$1, !1, s$1);
2232
+ if (w$1 && B(s$1, w$1)) return w$1;
2233
+ }
2234
+ } else {
2235
+ let A$1;
2236
+ try {
2237
+ A$1 = d$1(e, t, { extensions: [".json"] });
2238
+ } catch {
2239
+ A$1 = d$1(path.join(e, Z), t);
2240
+ }
2241
+ if (A$1) return A$1;
2242
+ }
2243
+ } catch {}
2244
+ }
2245
+ const g = se(path.resolve(t), path.join("node_modules", u$1), s$1);
2246
+ if (!g || !P(s$1, g).isDirectory()) return;
2247
+ const T$1 = path.join(g, Y);
2248
+ if (B(s$1, T$1)) {
2249
+ const d$1 = X(T$1, f$1, !1, s$1);
2250
+ if (d$1 === !1) return;
2251
+ if (d$1 && B(s$1, d$1) && P(s$1, d$1).isFile()) return d$1;
2252
+ }
2253
+ const b = path.join(g, f$1), _$1 = b.endsWith(".json");
2254
+ if (!_$1) {
2255
+ const d$1 = `${b}.json`;
2256
+ if (B(s$1, d$1)) return d$1;
2257
+ }
2258
+ if (B(s$1, b)) {
2259
+ if (P(s$1, b).isDirectory()) {
2260
+ const d$1 = path.join(b, Y);
2261
+ if (B(s$1, d$1)) {
2262
+ const w$1 = X(d$1, "", !0, s$1);
2263
+ if (w$1 && B(s$1, w$1)) return w$1;
2264
+ }
2265
+ const A$1 = path.join(b, Z);
2266
+ if (B(s$1, A$1)) return A$1;
2267
+ } else if (_$1) return b;
2268
+ }
2269
+ }, "resolveExtendsPath"), q = o((e, t) => G(path.relative(e, t)), "pathRelative"), fe = [
2270
+ "files",
2271
+ "include",
2272
+ "exclude"
2273
+ ], Ie = o((e, t, s$1, n) => {
2274
+ const l = Be(e, t, n);
2275
+ if (!l) throw new Error(`File '${e}' not found.`);
2276
+ if (s$1.has(l)) throw new Error(`Circularity detected while resolving configuration: ${l}`);
2277
+ s$1.add(l);
2278
+ const i = path.dirname(l), u$1 = ce(l, n, s$1);
2279
+ delete u$1.references;
2280
+ const { compilerOptions: f$1 } = u$1;
2281
+ if (f$1) {
2282
+ const { baseUrl: r } = f$1;
2283
+ r && !r.startsWith($) && (f$1.baseUrl = E(path.relative(t, path.join(i, r))) || "./");
2284
+ let { outDir: g } = f$1;
2285
+ g && (g.startsWith($) || (g = path.relative(t, path.join(i, g))), f$1.outDir = E(g) || "./");
2286
+ }
2287
+ for (const r of fe) {
2288
+ const g = u$1[r];
2289
+ g && (u$1[r] = g.map((T$1) => T$1.startsWith($) ? T$1 : E(path.relative(t, path.join(i, T$1)))));
2290
+ }
2291
+ return u$1;
2292
+ }, "resolveExtends"), Le = ["outDir", "declarationDir"], ce = o((e, t, s$1 = /* @__PURE__ */ new Set()) => {
2293
+ let n;
2294
+ try {
2295
+ n = re(e, t) || {};
2296
+ } catch {
2297
+ throw new Error(`Cannot resolve tsconfig at path: ${e}`);
2298
+ }
2299
+ if (typeof n != "object") throw new SyntaxError(`Failed to parse tsconfig at: ${e}`);
2300
+ const l = path.dirname(e);
2301
+ if (n.compilerOptions) {
2302
+ const { compilerOptions: i } = n;
2303
+ i.paths && !i.baseUrl && (i[H] = l);
2304
+ }
2305
+ if (n.extends) {
2306
+ const i = Array.isArray(n.extends) ? n.extends : [n.extends];
2307
+ delete n.extends;
2308
+ for (const u$1 of i.reverse()) {
2309
+ const f$1 = Ie(u$1, l, new Set(s$1), t), r = {
2310
+ ...f$1,
2311
+ ...n,
2312
+ compilerOptions: {
2313
+ ...f$1.compilerOptions,
2314
+ ...n.compilerOptions
2315
+ }
2316
+ };
2317
+ f$1.watchOptions && (r.watchOptions = {
2318
+ ...f$1.watchOptions,
2319
+ ...n.watchOptions
2320
+ }), n = r;
2321
+ }
2322
+ }
2323
+ if (n.compilerOptions) {
2324
+ const { compilerOptions: i } = n;
2325
+ for (const f$1 of ["baseUrl", "rootDir"]) {
2326
+ const r = i[f$1];
2327
+ if (r && !r.startsWith($)) {
2328
+ const g = path.resolve(l, r);
2329
+ i[f$1] = q(l, g);
2330
+ }
2331
+ }
2332
+ for (const f$1 of Le) {
2333
+ let r = i[f$1];
2334
+ r && (Array.isArray(n.exclude) || (n.exclude = []), n.exclude.includes(r) || n.exclude.push(r), r.startsWith($) || (r = G(r)), i[f$1] = r);
2335
+ }
2336
+ } else n.compilerOptions = {};
2337
+ if (n.include ? (n.include = n.include.map(E), n.files && delete n.files) : n.files && (n.files = n.files.map((i) => i.startsWith($) ? i : G(i))), n.watchOptions) {
2338
+ const { watchOptions: i } = n;
2339
+ i.excludeDirectories && (i.excludeDirectories = i.excludeDirectories.map((u$1) => E(path.resolve(l, u$1))));
2340
+ }
2341
+ return n;
2342
+ }, "_parseTsconfig"), W = o((e, t) => {
2343
+ if (e.startsWith($)) return E(path.join(t, e.slice(12)));
2344
+ }, "interpolateConfigDir"), $e = [
2345
+ "outDir",
2346
+ "declarationDir",
2347
+ "outFile",
2348
+ "rootDir",
2349
+ "baseUrl",
2350
+ "tsBuildInfoFile"
2351
+ ], Ue = o((e) => {
2352
+ if (e.strict) for (const N of [
2353
+ "noImplicitAny",
2354
+ "noImplicitThis",
2355
+ "strictNullChecks",
2356
+ "strictFunctionTypes",
2357
+ "strictBindCallApply",
2358
+ "strictPropertyInitialization",
2359
+ "strictBuiltinIteratorReturn",
2360
+ "alwaysStrict",
2361
+ "useUnknownInCatchVariables"
2362
+ ]) e[N] === void 0 && (e[N] = !0);
2363
+ if (e.target) {
2364
+ let a$1 = e.target.toLowerCase();
2365
+ a$1 === "es2015" && (a$1 = "es6"), e.target = a$1, a$1 === "esnext" && (e.module ??= "es6", e.useDefineForClassFields ??= !0), (a$1 === "es6" || a$1 === "es2016" || a$1 === "es2017" || a$1 === "es2018" || a$1 === "es2019" || a$1 === "es2020" || a$1 === "es2021" || a$1 === "es2022" || a$1 === "es2023" || a$1 === "es2024") && (e.module ??= "es6"), (a$1 === "es2022" || a$1 === "es2023" || a$1 === "es2024") && (e.useDefineForClassFields ??= !0);
2366
+ }
2367
+ if (e.module) {
2368
+ let a$1 = e.module.toLowerCase();
2369
+ a$1 === "es2015" && (a$1 = "es6"), e.module = a$1, (a$1 === "es6" || a$1 === "es2020" || a$1 === "es2022" || a$1 === "esnext" || a$1 === "none" || a$1 === "system" || a$1 === "umd" || a$1 === "amd") && (e.moduleResolution ??= "classic"), a$1 === "system" && (e.allowSyntheticDefaultImports ??= !0), (a$1 === "node16" || a$1 === "nodenext" || a$1 === "preserve") && (e.esModuleInterop ??= !0, e.allowSyntheticDefaultImports ??= !0), (a$1 === "node16" || a$1 === "nodenext") && (e.moduleDetection ??= "force", e.useDefineForClassFields ??= !0), a$1 === "node16" && (e.target ??= "es2022", e.moduleResolution ??= "node16"), a$1 === "nodenext" && (e.target ??= "esnext", e.moduleResolution ??= "nodenext"), a$1 === "preserve" && (e.moduleResolution ??= "bundler");
2370
+ }
2371
+ if (e.moduleResolution) {
2372
+ let a$1 = e.moduleResolution.toLowerCase();
2373
+ a$1 === "node" && (a$1 = "node10"), e.moduleResolution = a$1, (a$1 === "node16" || a$1 === "nodenext" || a$1 === "bundler") && (e.resolvePackageJsonExports ??= !0, e.resolvePackageJsonImports ??= !0), a$1 === "bundler" && (e.allowSyntheticDefaultImports ??= !0, e.resolveJsonModule ??= !0);
2374
+ }
2375
+ e.esModuleInterop && (e.allowSyntheticDefaultImports ??= !0), e.verbatimModuleSyntax && (e.isolatedModules ??= !0, e.preserveConstEnums ??= !0), e.isolatedModules && (e.preserveConstEnums ??= !0);
2376
+ }, "normalizeCompilerOptions"), ae = o((e, t = /* @__PURE__ */ new Map()) => {
2377
+ const s$1 = path.resolve(e), n = ce(s$1, t), l = path.dirname(s$1), { compilerOptions: i } = n;
2378
+ if (i) {
2379
+ for (const f$1 of $e) {
2380
+ const r = i[f$1];
2381
+ if (r) {
2382
+ const g = W(r, l);
2383
+ i[f$1] = g ? q(l, g) : r;
2384
+ }
2385
+ }
2386
+ for (const f$1 of ["rootDirs", "typeRoots"]) {
2387
+ const r = i[f$1];
2388
+ r && (i[f$1] = r.map((g) => {
2389
+ const T$1 = W(g, l);
2390
+ return T$1 ? q(l, T$1) : g;
2391
+ }));
2392
+ }
2393
+ const { paths: u$1 } = i;
2394
+ if (u$1) for (const f$1 of Object.keys(u$1)) u$1[f$1] = u$1[f$1].map((r) => {
2395
+ var g;
2396
+ return (g = W(r, l)) != null ? g : r;
2397
+ });
2398
+ Ue(i);
2399
+ }
2400
+ for (const u$1 of fe) {
2401
+ const f$1 = n[u$1];
2402
+ f$1 && (n[u$1] = f$1.map((r) => {
2403
+ var g;
2404
+ return (g = W(r, l)) != null ? g : r;
2405
+ }));
2406
+ }
2407
+ return n;
2408
+ }, "parseTsconfig"), he = o((e = process.cwd(), t = "tsconfig.json", s$1 = /* @__PURE__ */ new Map()) => {
2409
+ const n = se(E(e), t, s$1);
2410
+ if (!n) return null;
2411
+ const l = ae(n, s$1);
2412
+ return {
2413
+ path: n,
2414
+ config: l
2415
+ };
2416
+ }, "getTsconfig"), xe = /\*/g, ge = o((e, t) => {
2417
+ const s$1 = e.match(xe);
2418
+ if (s$1 && s$1.length > 1) throw new Error(t);
2419
+ }, "assertStarCount"), Ne = o((e) => {
2420
+ if (e.includes("*")) {
2421
+ const [t, s$1] = e.split("*");
2422
+ return {
2423
+ prefix: t,
2424
+ suffix: s$1
2425
+ };
2426
+ }
2427
+ return e;
2428
+ }, "parsePattern"), Se = o(({ prefix: e, suffix: t }, s$1) => s$1.startsWith(e) && s$1.endsWith(t), "isPatternMatch"), Pe = o((e, t, s$1) => Object.entries(e).map(([n, l]) => (ge(n, `Pattern '${n}' can have at most one '*' character.`), {
2429
+ pattern: Ne(n),
2430
+ substitutions: l.map((i) => {
2431
+ if (ge(i, `Substitution '${i}' in pattern '${n}' can have at most one '*' character.`), !t && !z.test(i)) throw new Error("Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?");
2432
+ return path.resolve(s$1, i);
2433
+ })
2434
+ })), "parsePaths");
2435
+ o((e) => {
2436
+ const { compilerOptions: t } = e.config;
2437
+ if (!t) return null;
2438
+ const { baseUrl: s$1, paths: n } = t;
2439
+ if (!s$1 && !n) return null;
2440
+ const l = H in t && t[H], i = path.resolve(path.dirname(e.path), s$1 || l || "."), u$1 = n ? Pe(n, s$1, i) : [];
2441
+ return (f$1) => {
2442
+ if (z.test(f$1)) return [];
2443
+ const r = [];
2444
+ for (const _$1 of u$1) {
2445
+ if (_$1.pattern === f$1) return _$1.substitutions.map(E);
2446
+ typeof _$1.pattern != "string" && r.push(_$1);
2447
+ }
2448
+ let g, T$1 = -1;
2449
+ for (const _$1 of r) Se(_$1.pattern, f$1) && _$1.pattern.prefix.length > T$1 && (T$1 = _$1.pattern.prefix.length, g = _$1);
2450
+ if (!g) return s$1 ? [E(path.join(i, f$1))] : [];
2451
+ const b = f$1.slice(g.pattern.prefix.length, f$1.length - g.pattern.suffix.length);
2452
+ return g.substitutions.map((_$1) => E(_$1.replace("*", b)));
2453
+ };
2454
+ }, "createPathsMatcher");
2455
+ const pe = o((e) => {
2456
+ let t = "";
2457
+ for (let s$1 = 0; s$1 < e.length; s$1 += 1) {
2458
+ const n = e[s$1], l = n.toUpperCase();
2459
+ t += n === l ? n.toLowerCase() : l;
2460
+ }
2461
+ return t;
2462
+ }, "s"), We = 65, Me = 97, Ve = o(() => Math.floor(Math.random() * 26), "m"), Je = o((e) => Array.from({ length: e }, () => String.fromCodePoint(Ve() + (Math.random() > .5 ? We : Me))).join(""), "S"), Oe = o((e = Ae) => {
2463
+ const t = process.execPath;
2464
+ if (e.existsSync(t)) return !e.existsSync(pe(t));
2465
+ const s$1 = `/${Je(10)}`;
2466
+ e.writeFileSync(s$1, "");
2467
+ const n = !e.existsSync(pe(s$1));
2468
+ return e.unlinkSync(s$1), n;
2469
+ }, "l"), { join: M } = path.posix, K = {
2470
+ ts: [
2471
+ ".ts",
2472
+ ".tsx",
2473
+ ".d.ts"
2474
+ ],
2475
+ cts: [".cts", ".d.cts"],
2476
+ mts: [".mts", ".d.mts"]
2477
+ }, ze = o((e) => {
2478
+ const t = [...K.ts], s$1 = [...K.cts], n = [...K.mts];
2479
+ return e != null && e.allowJs && (t.push(".js", ".jsx"), s$1.push(".cjs"), n.push(".mjs")), [
2480
+ ...t,
2481
+ ...s$1,
2482
+ ...n
2483
+ ];
2484
+ }, "getSupportedExtensions"), Ge = o((e) => {
2485
+ const t = [];
2486
+ if (!e) return t;
2487
+ const { outDir: s$1, declarationDir: n } = e;
2488
+ return s$1 && t.push(s$1), n && t.push(n), t;
2489
+ }, "getDefaultExcludeSpec"), me = o((e) => e.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`), "escapeForRegexp"), Qe = [
2490
+ "node_modules",
2491
+ "bower_components",
2492
+ "jspm_packages"
2493
+ ], C = `(?!(${Qe.join("|")})(/|$))`, He = /(?:^|\/)[^.*?]+$/, ke = "**/*", V = "[^/]", ee = "[^./]", we = process.platform === "win32";
2494
+ o(({ config: e, path: t }, s$1 = Oe()) => {
2495
+ if ("extends" in e) throw new Error("tsconfig#extends must be resolved. Use getTsconfig or parseTsconfig to resolve it.");
2496
+ if (!path.isAbsolute(t)) throw new Error("The tsconfig path must be absolute");
2497
+ we && (t = E(t));
2498
+ const n = path.dirname(t), { files: l, include: i, exclude: u$1, compilerOptions: f$1 } = e, r = l == null ? void 0 : l.map((w$1) => M(n, w$1)), g = ze(f$1), T$1 = s$1 ? "" : "i", _$1 = (u$1 || Ge(f$1)).map((w$1) => {
2499
+ const y = M(n, w$1), I$1 = me(y).replaceAll(String.raw`\*\*/`, "(.+/)?").replaceAll(String.raw`\*`, `${V}*`).replaceAll(String.raw`\?`, V);
2500
+ return new RegExp(`^${I$1}($|/)`, T$1);
2501
+ }), d$1 = l || i ? i : [ke], A$1 = d$1 ? d$1.map((w$1) => {
2502
+ let y = M(n, w$1);
2503
+ He.test(y) && (y = M(y, ke));
2504
+ const I$1 = me(y).replaceAll(String.raw`/\*\*`, `(/${C}${ee}${V}*)*?`).replaceAll(/(\/)?\\\*/g, (L, c) => {
2505
+ const k = `(${ee}|(\\.(?!min\\.js$))?)*`;
2506
+ return c ? `/${C}${ee}${k}` : k;
2507
+ }).replaceAll(/(\/)?\\\?/g, (L, c) => {
2508
+ const k = V;
2509
+ return c ? `/${C}${k}` : k;
2510
+ });
2511
+ return new RegExp(`^${I$1}$`, T$1);
2512
+ }) : void 0;
2513
+ return (w$1) => {
2514
+ if (!path.isAbsolute(w$1)) throw new Error("filePath must be absolute");
2515
+ if (we && (w$1 = E(w$1)), r != null && r.includes(w$1)) return e;
2516
+ if (!(!g.some((y) => w$1.endsWith(y)) || _$1.some((y) => y.test(w$1))) && A$1 && A$1.some((y) => y.test(w$1))) return e;
2517
+ };
2518
+ }, "createFilesMatcher");
2519
+ var import_picocolors = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
2520
+ let p = process || {}, argv = p.argv || [], env = p.env || {};
2521
+ let isColorSupported = !(!!env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || (p.stdout || {}).isTTY && env.TERM !== "dumb" || !!env.CI);
2522
+ let formatter = (open, close, replace = open) => (input) => {
2523
+ let string$1 = "" + input, index = string$1.indexOf(close, open.length);
2524
+ return ~index ? open + replaceClose(string$1, close, replace, index) + close : open + string$1 + close;
2525
+ };
2526
+ let replaceClose = (string$1, close, replace, index) => {
2527
+ let result = "", cursor = 0;
2528
+ do {
2529
+ result += string$1.substring(cursor, index) + replace;
2530
+ cursor = index + close.length;
2531
+ index = string$1.indexOf(close, cursor);
2532
+ } while (~index);
2533
+ return result + string$1.substring(cursor);
2534
+ };
2535
+ let createColors = (enabled = isColorSupported) => {
2536
+ let f$1 = enabled ? formatter : () => String;
2537
+ return {
2538
+ isColorSupported: enabled,
2539
+ reset: f$1("\x1B[0m", "\x1B[0m"),
2540
+ bold: f$1("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m"),
2541
+ dim: f$1("\x1B[2m", "\x1B[22m", "\x1B[22m\x1B[2m"),
2542
+ italic: f$1("\x1B[3m", "\x1B[23m"),
2543
+ underline: f$1("\x1B[4m", "\x1B[24m"),
2544
+ inverse: f$1("\x1B[7m", "\x1B[27m"),
2545
+ hidden: f$1("\x1B[8m", "\x1B[28m"),
2546
+ strikethrough: f$1("\x1B[9m", "\x1B[29m"),
2547
+ black: f$1("\x1B[30m", "\x1B[39m"),
2548
+ red: f$1("\x1B[31m", "\x1B[39m"),
2549
+ green: f$1("\x1B[32m", "\x1B[39m"),
2550
+ yellow: f$1("\x1B[33m", "\x1B[39m"),
2551
+ blue: f$1("\x1B[34m", "\x1B[39m"),
2552
+ magenta: f$1("\x1B[35m", "\x1B[39m"),
2553
+ cyan: f$1("\x1B[36m", "\x1B[39m"),
2554
+ white: f$1("\x1B[37m", "\x1B[39m"),
2555
+ gray: f$1("\x1B[90m", "\x1B[39m"),
2556
+ bgBlack: f$1("\x1B[40m", "\x1B[49m"),
2557
+ bgRed: f$1("\x1B[41m", "\x1B[49m"),
2558
+ bgGreen: f$1("\x1B[42m", "\x1B[49m"),
2559
+ bgYellow: f$1("\x1B[43m", "\x1B[49m"),
2560
+ bgBlue: f$1("\x1B[44m", "\x1B[49m"),
2561
+ bgMagenta: f$1("\x1B[45m", "\x1B[49m"),
2562
+ bgCyan: f$1("\x1B[46m", "\x1B[49m"),
2563
+ bgWhite: f$1("\x1B[47m", "\x1B[49m"),
2564
+ blackBright: f$1("\x1B[90m", "\x1B[39m"),
2565
+ redBright: f$1("\x1B[91m", "\x1B[39m"),
2566
+ greenBright: f$1("\x1B[92m", "\x1B[39m"),
2567
+ yellowBright: f$1("\x1B[93m", "\x1B[39m"),
2568
+ blueBright: f$1("\x1B[94m", "\x1B[39m"),
2569
+ magentaBright: f$1("\x1B[95m", "\x1B[39m"),
2570
+ cyanBright: f$1("\x1B[96m", "\x1B[39m"),
2571
+ whiteBright: f$1("\x1B[97m", "\x1B[39m"),
2572
+ bgBlackBright: f$1("\x1B[100m", "\x1B[49m"),
2573
+ bgRedBright: f$1("\x1B[101m", "\x1B[49m"),
2574
+ bgGreenBright: f$1("\x1B[102m", "\x1B[49m"),
2575
+ bgYellowBright: f$1("\x1B[103m", "\x1B[49m"),
2576
+ bgBlueBright: f$1("\x1B[104m", "\x1B[49m"),
2577
+ bgMagentaBright: f$1("\x1B[105m", "\x1B[49m"),
2578
+ bgCyanBright: f$1("\x1B[106m", "\x1B[49m"),
2579
+ bgWhiteBright: f$1("\x1B[107m", "\x1B[49m")
2580
+ };
2581
+ };
2582
+ module.exports = createColors();
2583
+ module.exports.createColors = createColors;
2584
+ })))(), 1);
2585
+ function isErr(result) {
2586
+ return result instanceof CtxError;
2587
+ }
2588
+ function attempt(fn) {
2589
+ const convertUnknownErrorToCtxError = (error) => {
2590
+ const newError = error instanceof Error ? error : new Error(String(error));
2591
+ return new CtxError("", {}, newError);
2592
+ };
2593
+ try {
2594
+ const result = fn();
2595
+ return isPromise(result) ? result.then((value) => value).catch((error) => convertUnknownErrorToCtxError(error)) : result;
2596
+ } catch (error) {
2597
+ return convertUnknownErrorToCtxError(error);
2598
+ }
2599
+ }
2600
+ function err(message$1, cause) {
2601
+ return cause ? new CtxError(message$1, { cause }) : new CtxError(message$1);
2602
+ }
2603
+ var CtxError = class CtxError$1 extends Error {
2604
+ context;
2605
+ cause;
2606
+ constructor(message$1, options, errorToConvert) {
2607
+ super();
2608
+ Object.setPrototypeOf(this, new.target.prototype);
2609
+ if (errorToConvert) {
2610
+ this.name = errorToConvert.name;
2611
+ this.message = errorToConvert.message;
2612
+ if (errorToConvert.cause instanceof Error) this.cause = errorToConvert.cause;
2613
+ if (errorToConvert.stack) this.stack = errorToConvert.stack;
2614
+ } else {
2615
+ this.name = "CtxError";
2616
+ this.message = message$1;
2617
+ if (options?.cause) this.cause = options.cause;
2618
+ }
2619
+ }
2620
+ get messageChain() {
2621
+ const messages = [this.message];
2622
+ let currentCause = this.cause;
2623
+ while (currentCause) {
2624
+ const causeMessage = this.#prependErrorNameToMessage(currentCause);
2625
+ messages.push(causeMessage);
2626
+ currentCause = currentCause.cause instanceof Error ? currentCause.cause : void 0;
2627
+ }
2628
+ const filteredMessages = messages.map((msg) => msg.trim()).filter(Boolean);
2629
+ return filteredMessages.length > 0 ? filteredMessages.join(" -> ") : "Unknown error";
2630
+ }
2631
+ #prependErrorNameToMessage(error) {
2632
+ return `${error.name !== "Error" && error.name !== "CtxError" ? `${error.name}: ` : ""}${error.message}`;
2633
+ }
2634
+ get rootStack() {
2635
+ const cleanStack = (stack) => {
2636
+ const stackLines = stack.trim().split("\n");
2637
+ const excludes = [
2638
+ "at new CtxError",
2639
+ "at err",
2640
+ "at attempt"
2641
+ ];
2642
+ return stackLines.map((line) => line.trim()).filter((line) => !excludes.some((exclude) => line.startsWith(exclude))).join("\n ");
2643
+ };
2644
+ const stacks = [this.stack];
2645
+ let currentCause = this.cause;
2646
+ while (currentCause) {
2647
+ stacks.push(currentCause.stack);
2648
+ currentCause = currentCause.cause instanceof Error ? currentCause.cause : void 0;
2649
+ }
2650
+ const rootStack = stacks.map((stack) => stack ? stack.trim() : "").filter(Boolean).at(-1);
2651
+ return rootStack ? cleanStack(rootStack) : "<no stack>";
2652
+ }
2653
+ ctx(context) {
2654
+ this.context = {
2655
+ ...this.context,
2656
+ ...context
2657
+ };
2658
+ return this;
2659
+ }
2660
+ get(key) {
2661
+ if (this.cause instanceof CtxError$1) {
2662
+ const deepestValue = this.cause.get(key);
2663
+ if (deepestValue !== void 0) return deepestValue;
2664
+ }
2665
+ if (this.context && Object.hasOwn(this.context, key)) return this.context[key];
2666
+ }
2667
+ getAll(key) {
2668
+ const values$1 = [];
2669
+ if (this.context && Object.hasOwn(this.context, key)) values$1.push(this.context[key]);
2670
+ if (this.cause instanceof CtxError$1) values$1.push(...this.cause.getAll(key));
2671
+ return values$1;
2672
+ }
2673
+ };
2674
+ function isPromise(value) {
2675
+ return value ? typeof value.then === "function" : false;
2676
+ }
2677
+ const IMPORT_PATTERN = /(?:import|from)\s+['"]([^'"]+)['"]$/gm;
2678
+ const FILES_GLOB = "**/*.{ts,tsx,js,jsx,astro}";
2679
+ const TRANSFORM_ERRORS = [];
2680
+ async function cli() {
2681
+ const options = object({
2682
+ write: option("-w", "--write", { description: message`Write changes to files` }),
2683
+ ignorePatterns: multiple(option("-i", "--ignore", string({ metavar: "PATTERN" }), { description: message`Additional glob patterns for files to ignore` }))
2684
+ });
2685
+ const { write, ignorePatterns } = run(options, {
2686
+ programName: "ts-import-fix",
2687
+ help: "option",
2688
+ showDefault: { prefix: " [default: " }
2689
+ });
2690
+ const exclude = [
2691
+ "node_modules/",
2692
+ "dist/",
2693
+ ...ignorePatterns
2694
+ ];
2695
+ return {
2696
+ filePaths: await Array.fromAsync(fs.glob(FILES_GLOB, { exclude })),
2697
+ write
2698
+ };
2699
+ }
2700
+ function getPathsMap() {
2701
+ const tsconfig = he();
2702
+ if (!tsconfig) return err("failed to load tsconfig", void 0);
2703
+ const pathsMap = {};
2704
+ for (let [alias, [aliasDir]] of Object.entries(tsconfig.config.compilerOptions?.paths ?? {})) {
2705
+ if (!alias.endsWith("/*")) continue;
2706
+ if (!aliasDir?.endsWith("/*")) continue;
2707
+ aliasDir = aliasDir.slice(0, -2);
2708
+ alias = alias.slice(0, -2);
2709
+ pathsMap[alias] = aliasDir;
2710
+ }
2711
+ return pathsMap;
2712
+ }
2713
+ function changeExtension(parsedPath, newExtension) {
2714
+ return {
2715
+ ...parsedPath,
2716
+ ext: newExtension,
2717
+ base: ""
2718
+ };
2719
+ }
2720
+ function transformExtension(filePath) {
2721
+ const pathParts = path.parse(filePath);
2722
+ if (!(pathParts.ext === ".js" || pathParts.ext === "")) return filePath;
2723
+ return path.format(changeExtension(pathParts, ".ts"));
2724
+ }
2725
+ function transformRelativeImport(filePath, importPath, pathsMap) {
2726
+ const currentDir = path.dirname(filePath);
2727
+ const absoluteImportPath = path.resolve(currentDir, importPath);
2728
+ if (!fss.existsSync(absoluteImportPath)) {
2729
+ TRANSFORM_ERRORS.push(`❌ (${filePath}) skipped transform of '${importPath}': target file does not exist`);
2730
+ return importPath;
2731
+ }
2732
+ for (const [alias, aliasDir] of Object.entries(pathsMap)) {
2733
+ const relativeToAliasDir = path.relative(aliasDir, absoluteImportPath);
2734
+ if (relativeToAliasDir.startsWith("..")) continue;
2735
+ return `${alias}/${relativeToAliasDir}`;
2736
+ }
2737
+ TRANSFORM_ERRORS.push(`❌ (${filePath}) could not find alias for '${importPath}'`);
2738
+ }
2739
+ async function tsImportFix() {
2740
+ const { filePaths, write } = await cli();
2741
+ const pathsMap = getPathsMap();
2742
+ if (isErr(pathsMap)) return pathsMap;
2743
+ const importFixResult = await attempt(() => {
2744
+ const filePromises = filePaths.map(async (filePath) => {
2745
+ const content = await fs.readFile(filePath, "utf8");
2746
+ const transformedContent = content.replace(IMPORT_PATTERN, (match, importPath) => {
2747
+ const isRelativeImport = importPath.startsWith("./") || importPath.startsWith("../");
2748
+ const isAliasImport = Object.keys(pathsMap).some((alias) => importPath.startsWith(alias));
2749
+ if (!(isRelativeImport || isAliasImport)) return match;
2750
+ let newImportPath = transformExtension(importPath);
2751
+ if (isRelativeImport) newImportPath = transformRelativeImport(filePath, newImportPath, pathsMap) ?? newImportPath;
2752
+ if (newImportPath === importPath) return match;
2753
+ const { ext: originalExt } = path.parse(importPath);
2754
+ const newPathParts = path.parse(newImportPath);
2755
+ const { ext: newExt } = newPathParts;
2756
+ let newImportPathString = newImportPath;
2757
+ if (newExt !== originalExt) newImportPathString = `${path.format(changeExtension(newPathParts, ""))}${import_picocolors.default.greenBright(newExt)}`;
2758
+ console.log(`✅ (${filePath}) '${importPath}' -> ${newImportPathString}`);
2759
+ return match.replace(importPath, newImportPath);
2760
+ });
2761
+ if (transformedContent === content) return;
2762
+ if (write) await fs.writeFile(filePath, transformedContent);
2763
+ });
2764
+ return Promise.all(filePromises);
2765
+ });
2766
+ let exitCode = 0;
2767
+ if (TRANSFORM_ERRORS.length > 0) {
2768
+ console.error(TRANSFORM_ERRORS.join("\n"));
2769
+ exitCode = 1;
2770
+ }
2771
+ if (isErr(importFixResult)) return err("something went wrong when transforming imports", importFixResult);
2772
+ return exitCode;
2773
+ }
2774
+ async function main() {
2775
+ const result = await tsImportFix();
2776
+ if (isErr(result)) {
2777
+ console.error(import_picocolors.default.redBright(`ts-import-fix: ${result.messageChain}`));
2778
+ return 1;
2779
+ }
2780
+ return result;
2781
+ }
2782
+ if (import.meta.main) process$1.exitCode = await main();
2783
+ export {};