@mtnts/contract-client 0.0.6 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs ADDED
@@ -0,0 +1,2210 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __typeError = (msg) => {
10
+ throw TypeError(msg);
11
+ };
12
+ var __commonJS = (cb, mod) => function __require() {
13
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
14
+ };
15
+ var __export = (target, all) => {
16
+ for (var name in all)
17
+ __defProp(target, name, { get: all[name], enumerable: true });
18
+ };
19
+ var __copyProps = (to, from, except, desc) => {
20
+ if (from && typeof from === "object" || typeof from === "function") {
21
+ for (let key of __getOwnPropNames(from))
22
+ if (!__hasOwnProp.call(to, key) && key !== except)
23
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
24
+ }
25
+ return to;
26
+ };
27
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
28
+ // If the importer is in node compatibility mode or this is not an ESM
29
+ // file that has been converted to a CommonJS file using a Babel-
30
+ // compatible transform (i.e. "__esModule" has not been set), then set
31
+ // "default" to the CommonJS "module.exports" for node compatibility.
32
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
33
+ mod
34
+ ));
35
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
36
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
37
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
38
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
39
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
40
+
41
+ // node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js
42
+ var require_ignore = __commonJS({
43
+ "node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js"(exports2, module2) {
44
+ "use strict";
45
+ function makeArray(subject) {
46
+ return Array.isArray(subject) ? subject : [subject];
47
+ }
48
+ var UNDEFINED = void 0;
49
+ var EMPTY = "";
50
+ var SPACE = " ";
51
+ var ESCAPE = "\\";
52
+ var REGEX_TEST_BLANK_LINE = /^\s+$/;
53
+ var REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
54
+ var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
55
+ var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
56
+ var REGEX_SPLITALL_CRLF = /\r?\n/g;
57
+ var REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
58
+ var REGEX_TEST_TRAILING_SLASH = /\/$/;
59
+ var SLASH = "/";
60
+ var TMP_KEY_IGNORE = "node-ignore";
61
+ if (typeof Symbol !== "undefined") {
62
+ TMP_KEY_IGNORE = /* @__PURE__ */ Symbol.for("node-ignore");
63
+ }
64
+ var KEY_IGNORE = TMP_KEY_IGNORE;
65
+ var define = (object, key, value) => {
66
+ Object.defineProperty(object, key, { value });
67
+ return value;
68
+ };
69
+ var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
70
+ var RETURN_FALSE = () => false;
71
+ var sanitizeRange = (range) => range.replace(
72
+ REGEX_REGEXP_RANGE,
73
+ (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match : EMPTY
74
+ );
75
+ var cleanRangeBackSlash = (slashes) => {
76
+ const { length } = slashes;
77
+ return slashes.slice(0, length - length % 2);
78
+ };
79
+ var REPLACERS = [
80
+ [
81
+ // Remove BOM
82
+ // TODO:
83
+ // Other similar zero-width characters?
84
+ /^\uFEFF/,
85
+ () => EMPTY
86
+ ],
87
+ // > Trailing spaces are ignored unless they are quoted with backslash ("\")
88
+ [
89
+ // (a\ ) -> (a )
90
+ // (a ) -> (a)
91
+ // (a ) -> (a)
92
+ // (a \ ) -> (a )
93
+ /((?:\\\\)*?)(\\?\s+)$/,
94
+ (_, m1, m2) => m1 + (m2.indexOf("\\") === 0 ? SPACE : EMPTY)
95
+ ],
96
+ // Replace (\ ) with ' '
97
+ // (\ ) -> ' '
98
+ // (\\ ) -> '\\ '
99
+ // (\\\ ) -> '\\ '
100
+ [
101
+ /(\\+?)\s/g,
102
+ (_, m1) => {
103
+ const { length } = m1;
104
+ return m1.slice(0, length - length % 2) + SPACE;
105
+ }
106
+ ],
107
+ // Escape metacharacters
108
+ // which is written down by users but means special for regular expressions.
109
+ // > There are 12 characters with special meanings:
110
+ // > - the backslash \,
111
+ // > - the caret ^,
112
+ // > - the dollar sign $,
113
+ // > - the period or dot .,
114
+ // > - the vertical bar or pipe symbol |,
115
+ // > - the question mark ?,
116
+ // > - the asterisk or star *,
117
+ // > - the plus sign +,
118
+ // > - the opening parenthesis (,
119
+ // > - the closing parenthesis ),
120
+ // > - and the opening square bracket [,
121
+ // > - the opening curly brace {,
122
+ // > These special characters are often called "metacharacters".
123
+ [
124
+ /[\\$.|*+(){^]/g,
125
+ (match) => `\\${match}`
126
+ ],
127
+ [
128
+ // > a question mark (?) matches a single character
129
+ /(?!\\)\?/g,
130
+ () => "[^/]"
131
+ ],
132
+ // leading slash
133
+ [
134
+ // > A leading slash matches the beginning of the pathname.
135
+ // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
136
+ // A leading slash matches the beginning of the pathname
137
+ /^\//,
138
+ () => "^"
139
+ ],
140
+ // replace special metacharacter slash after the leading slash
141
+ [
142
+ /\//g,
143
+ () => "\\/"
144
+ ],
145
+ [
146
+ // > A leading "**" followed by a slash means match in all directories.
147
+ // > For example, "**/foo" matches file or directory "foo" anywhere,
148
+ // > the same as pattern "foo".
149
+ // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
150
+ // > under directory "foo".
151
+ // Notice that the '*'s have been replaced as '\\*'
152
+ /^\^*\\\*\\\*\\\//,
153
+ // '**/foo' <-> 'foo'
154
+ () => "^(?:.*\\/)?"
155
+ ],
156
+ // starting
157
+ [
158
+ // there will be no leading '/'
159
+ // (which has been replaced by section "leading slash")
160
+ // If starts with '**', adding a '^' to the regular expression also works
161
+ /^(?=[^^])/,
162
+ function startingReplacer() {
163
+ return !/\/(?!$)/.test(this) ? "(?:^|\\/)" : "^";
164
+ }
165
+ ],
166
+ // two globstars
167
+ [
168
+ // Use lookahead assertions so that we could match more than one `'/**'`
169
+ /\\\/\\\*\\\*(?=\\\/|$)/g,
170
+ // Zero, one or several directories
171
+ // should not use '*', or it will be replaced by the next replacer
172
+ // Check if it is not the last `'/**'`
173
+ (_, index, str) => index + 6 < str.length ? "(?:\\/[^\\/]+)*" : "\\/.+"
174
+ ],
175
+ // normal intermediate wildcards
176
+ [
177
+ // Never replace escaped '*'
178
+ // ignore rule '\*' will match the path '*'
179
+ // 'abc.*/' -> go
180
+ // 'abc.*' -> skip this rule,
181
+ // coz trailing single wildcard will be handed by [trailing wildcard]
182
+ /(^|[^\\]+)(\\\*)+(?=.+)/g,
183
+ // '*.js' matches '.js'
184
+ // '*.js' doesn't match 'abc'
185
+ (_, p1, p2) => {
186
+ const unescaped = p2.replace(/\\\*/g, "[^\\/]*");
187
+ return p1 + unescaped;
188
+ }
189
+ ],
190
+ [
191
+ // unescape, revert step 3 except for back slash
192
+ // For example, if a user escape a '\\*',
193
+ // after step 3, the result will be '\\\\\\*'
194
+ /\\\\\\(?=[$.|*+(){^])/g,
195
+ () => ESCAPE
196
+ ],
197
+ [
198
+ // '\\\\' -> '\\'
199
+ /\\\\/g,
200
+ () => ESCAPE
201
+ ],
202
+ [
203
+ // > The range notation, e.g. [a-zA-Z],
204
+ // > can be used to match one of the characters in a range.
205
+ // `\` is escaped by step 3
206
+ /(\\)?\[([^\]/]*?)(\\*)($|\])/g,
207
+ (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === "]" ? endEscape.length % 2 === 0 ? `[${sanitizeRange(range)}${endEscape}]` : "[]" : "[]"
208
+ ],
209
+ // ending
210
+ [
211
+ // 'js' will not match 'js.'
212
+ // 'ab' will not match 'abc'
213
+ /(?:[^*])$/,
214
+ // WTF!
215
+ // https://git-scm.com/docs/gitignore
216
+ // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
217
+ // which re-fixes #24, #38
218
+ // > If there is a separator at the end of the pattern then the pattern
219
+ // > will only match directories, otherwise the pattern can match both
220
+ // > files and directories.
221
+ // 'js*' will not match 'a.js'
222
+ // 'js/' will not match 'a.js'
223
+ // 'js' will match 'a.js' and 'a.js/'
224
+ (match) => /\/$/.test(match) ? `${match}$` : `${match}(?=$|\\/$)`
225
+ ]
226
+ ];
227
+ var REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\/)?\\\*$/;
228
+ var MODE_IGNORE = "regex";
229
+ var MODE_CHECK_IGNORE = "checkRegex";
230
+ var UNDERSCORE = "_";
231
+ var TRAILING_WILD_CARD_REPLACERS = {
232
+ [MODE_IGNORE](_, p1) {
233
+ const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
234
+ return `${prefix}(?=$|\\/$)`;
235
+ },
236
+ [MODE_CHECK_IGNORE](_, p1) {
237
+ const prefix = p1 ? `${p1}[^/]*` : "[^/]*";
238
+ return `${prefix}(?=$|\\/$)`;
239
+ }
240
+ };
241
+ var makeRegexPrefix = (pattern) => REPLACERS.reduce(
242
+ (prev, [matcher, replacer]) => prev.replace(matcher, replacer.bind(pattern)),
243
+ pattern
244
+ );
245
+ var isString = (subject) => typeof subject === "string";
246
+ var checkPattern = (pattern) => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) && pattern.indexOf("#") !== 0;
247
+ var splitPattern = (pattern) => pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean);
248
+ var IgnoreRule = class {
249
+ constructor(pattern, mark, body, ignoreCase, negative, prefix) {
250
+ this.pattern = pattern;
251
+ this.mark = mark;
252
+ this.negative = negative;
253
+ define(this, "body", body);
254
+ define(this, "ignoreCase", ignoreCase);
255
+ define(this, "regexPrefix", prefix);
256
+ }
257
+ get regex() {
258
+ const key = UNDERSCORE + MODE_IGNORE;
259
+ if (this[key]) {
260
+ return this[key];
261
+ }
262
+ return this._make(MODE_IGNORE, key);
263
+ }
264
+ get checkRegex() {
265
+ const key = UNDERSCORE + MODE_CHECK_IGNORE;
266
+ if (this[key]) {
267
+ return this[key];
268
+ }
269
+ return this._make(MODE_CHECK_IGNORE, key);
270
+ }
271
+ _make(mode, key) {
272
+ const str = this.regexPrefix.replace(
273
+ REGEX_REPLACE_TRAILING_WILDCARD,
274
+ // It does not need to bind pattern
275
+ TRAILING_WILD_CARD_REPLACERS[mode]
276
+ );
277
+ const regex = this.ignoreCase ? new RegExp(str, "i") : new RegExp(str);
278
+ return define(this, key, regex);
279
+ }
280
+ };
281
+ var createRule = ({
282
+ pattern,
283
+ mark
284
+ }, ignoreCase) => {
285
+ let negative = false;
286
+ let body = pattern;
287
+ if (body.indexOf("!") === 0) {
288
+ negative = true;
289
+ body = body.substr(1);
290
+ }
291
+ body = body.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
292
+ const regexPrefix = makeRegexPrefix(body);
293
+ return new IgnoreRule(
294
+ pattern,
295
+ mark,
296
+ body,
297
+ ignoreCase,
298
+ negative,
299
+ regexPrefix
300
+ );
301
+ };
302
+ var RuleManager = class {
303
+ constructor(ignoreCase) {
304
+ this._ignoreCase = ignoreCase;
305
+ this._rules = [];
306
+ }
307
+ _add(pattern) {
308
+ if (pattern && pattern[KEY_IGNORE]) {
309
+ this._rules = this._rules.concat(pattern._rules._rules);
310
+ this._added = true;
311
+ return;
312
+ }
313
+ if (isString(pattern)) {
314
+ pattern = {
315
+ pattern
316
+ };
317
+ }
318
+ if (checkPattern(pattern.pattern)) {
319
+ const rule = createRule(pattern, this._ignoreCase);
320
+ this._added = true;
321
+ this._rules.push(rule);
322
+ }
323
+ }
324
+ // @param {Array<string> | string | Ignore} pattern
325
+ add(pattern) {
326
+ this._added = false;
327
+ makeArray(
328
+ isString(pattern) ? splitPattern(pattern) : pattern
329
+ ).forEach(this._add, this);
330
+ return this._added;
331
+ }
332
+ // Test one single path without recursively checking parent directories
333
+ //
334
+ // - checkUnignored `boolean` whether should check if the path is unignored,
335
+ // setting `checkUnignored` to `false` could reduce additional
336
+ // path matching.
337
+ // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`
338
+ // @returns {TestResult} true if a file is ignored
339
+ test(path7, checkUnignored, mode) {
340
+ let ignored = false;
341
+ let unignored = false;
342
+ let matchedRule;
343
+ this._rules.forEach((rule) => {
344
+ const { negative } = rule;
345
+ if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
346
+ return;
347
+ }
348
+ const matched = rule[mode].test(path7);
349
+ if (!matched) {
350
+ return;
351
+ }
352
+ ignored = !negative;
353
+ unignored = negative;
354
+ matchedRule = negative ? UNDEFINED : rule;
355
+ });
356
+ const ret = {
357
+ ignored,
358
+ unignored
359
+ };
360
+ if (matchedRule) {
361
+ ret.rule = matchedRule;
362
+ }
363
+ return ret;
364
+ }
365
+ };
366
+ var throwError = (message, Ctor) => {
367
+ throw new Ctor(message);
368
+ };
369
+ var checkPath = (path7, originalPath, doThrow) => {
370
+ if (!isString(path7)) {
371
+ return doThrow(
372
+ `path must be a string, but got \`${originalPath}\``,
373
+ TypeError
374
+ );
375
+ }
376
+ if (!path7) {
377
+ return doThrow(`path must not be empty`, TypeError);
378
+ }
379
+ if (checkPath.isNotRelative(path7)) {
380
+ const r = "`path.relative()`d";
381
+ return doThrow(
382
+ `path should be a ${r} string, but got "${originalPath}"`,
383
+ RangeError
384
+ );
385
+ }
386
+ return true;
387
+ };
388
+ var isNotRelative = (path7) => REGEX_TEST_INVALID_PATH.test(path7);
389
+ checkPath.isNotRelative = isNotRelative;
390
+ checkPath.convert = (p) => p;
391
+ var Ignore = class {
392
+ constructor({
393
+ ignorecase = true,
394
+ ignoreCase = ignorecase,
395
+ allowRelativePaths = false
396
+ } = {}) {
397
+ define(this, KEY_IGNORE, true);
398
+ this._rules = new RuleManager(ignoreCase);
399
+ this._strictPathCheck = !allowRelativePaths;
400
+ this._initCache();
401
+ }
402
+ _initCache() {
403
+ this._ignoreCache = /* @__PURE__ */ Object.create(null);
404
+ this._testCache = /* @__PURE__ */ Object.create(null);
405
+ }
406
+ add(pattern) {
407
+ if (this._rules.add(pattern)) {
408
+ this._initCache();
409
+ }
410
+ return this;
411
+ }
412
+ // legacy
413
+ addPattern(pattern) {
414
+ return this.add(pattern);
415
+ }
416
+ // @returns {TestResult}
417
+ _test(originalPath, cache, checkUnignored, slices) {
418
+ const path7 = originalPath && checkPath.convert(originalPath);
419
+ checkPath(
420
+ path7,
421
+ originalPath,
422
+ this._strictPathCheck ? throwError : RETURN_FALSE
423
+ );
424
+ return this._t(path7, cache, checkUnignored, slices);
425
+ }
426
+ checkIgnore(path7) {
427
+ if (!REGEX_TEST_TRAILING_SLASH.test(path7)) {
428
+ return this.test(path7);
429
+ }
430
+ const slices = path7.split(SLASH).filter(Boolean);
431
+ slices.pop();
432
+ if (slices.length) {
433
+ const parent = this._t(
434
+ slices.join(SLASH) + SLASH,
435
+ this._testCache,
436
+ true,
437
+ slices
438
+ );
439
+ if (parent.ignored) {
440
+ return parent;
441
+ }
442
+ }
443
+ return this._rules.test(path7, false, MODE_CHECK_IGNORE);
444
+ }
445
+ _t(path7, cache, checkUnignored, slices) {
446
+ if (path7 in cache) {
447
+ return cache[path7];
448
+ }
449
+ if (!slices) {
450
+ slices = path7.split(SLASH).filter(Boolean);
451
+ }
452
+ slices.pop();
453
+ if (!slices.length) {
454
+ return cache[path7] = this._rules.test(path7, checkUnignored, MODE_IGNORE);
455
+ }
456
+ const parent = this._t(
457
+ slices.join(SLASH) + SLASH,
458
+ cache,
459
+ checkUnignored,
460
+ slices
461
+ );
462
+ return cache[path7] = parent.ignored ? parent : this._rules.test(path7, checkUnignored, MODE_IGNORE);
463
+ }
464
+ ignores(path7) {
465
+ return this._test(path7, this._ignoreCache, false).ignored;
466
+ }
467
+ createFilter() {
468
+ return (path7) => !this.ignores(path7);
469
+ }
470
+ filter(paths) {
471
+ return makeArray(paths).filter(this.createFilter());
472
+ }
473
+ // @returns {TestResult}
474
+ test(path7) {
475
+ return this._test(path7, this._testCache, true);
476
+ }
477
+ };
478
+ var factory = (options) => new Ignore(options);
479
+ var isPathValid = (path7) => checkPath(path7 && checkPath.convert(path7), path7, RETURN_FALSE);
480
+ var setupWindows = () => {
481
+ const makePosix = (str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
482
+ checkPath.convert = makePosix;
483
+ const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
484
+ checkPath.isNotRelative = (path7) => REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path7) || isNotRelative(path7);
485
+ };
486
+ if (
487
+ // Detect `process` so that it can run in browsers.
488
+ typeof process !== "undefined" && process.platform === "win32"
489
+ ) {
490
+ setupWindows();
491
+ }
492
+ module2.exports = factory;
493
+ factory.default = factory;
494
+ module2.exports.isPathValid = isPathValid;
495
+ define(module2.exports, /* @__PURE__ */ Symbol.for("setupWindows"), setupWindows);
496
+ }
497
+ });
498
+
499
+ // src/cli/index.ts
500
+ var cli_exports = {};
501
+ __export(cli_exports, {
502
+ generateBlockchainTypes: () => generateBlockchainTypes
503
+ });
504
+ module.exports = __toCommonJS(cli_exports);
505
+
506
+ // node_modules/.pnpm/globby@16.2.0/node_modules/globby/index.js
507
+ var import_node_process2 = __toESM(require("process"), 1);
508
+ var import_node_fs3 = __toESM(require("fs"), 1);
509
+ var import_node_path5 = __toESM(require("path"), 1);
510
+ var import_node_stream2 = require("stream");
511
+
512
+ // node_modules/.pnpm/@sindresorhus+merge-streams@4.0.0/node_modules/@sindresorhus/merge-streams/index.js
513
+ var import_node_events = require("events");
514
+ var import_node_stream = require("stream");
515
+ var import_promises = require("stream/promises");
516
+ function mergeStreams(streams) {
517
+ if (!Array.isArray(streams)) {
518
+ throw new TypeError(`Expected an array, got \`${typeof streams}\`.`);
519
+ }
520
+ for (const stream of streams) {
521
+ validateStream(stream);
522
+ }
523
+ const objectMode = streams.some(({ readableObjectMode }) => readableObjectMode);
524
+ const highWaterMark = getHighWaterMark(streams, objectMode);
525
+ const passThroughStream = new MergedStream({
526
+ objectMode,
527
+ writableHighWaterMark: highWaterMark,
528
+ readableHighWaterMark: highWaterMark
529
+ });
530
+ for (const stream of streams) {
531
+ passThroughStream.add(stream);
532
+ }
533
+ return passThroughStream;
534
+ }
535
+ var getHighWaterMark = (streams, objectMode) => {
536
+ if (streams.length === 0) {
537
+ return (0, import_node_stream.getDefaultHighWaterMark)(objectMode);
538
+ }
539
+ const highWaterMarks = streams.filter(({ readableObjectMode }) => readableObjectMode === objectMode).map(({ readableHighWaterMark }) => readableHighWaterMark);
540
+ return Math.max(...highWaterMarks);
541
+ };
542
+ var _streams, _ended, _aborted, _onFinished, _unpipeEvent, _streamPromises;
543
+ var MergedStream = class extends import_node_stream.PassThrough {
544
+ constructor() {
545
+ super(...arguments);
546
+ __privateAdd(this, _streams, /* @__PURE__ */ new Set([]));
547
+ __privateAdd(this, _ended, /* @__PURE__ */ new Set([]));
548
+ __privateAdd(this, _aborted, /* @__PURE__ */ new Set([]));
549
+ __privateAdd(this, _onFinished);
550
+ __privateAdd(this, _unpipeEvent, /* @__PURE__ */ Symbol("unpipe"));
551
+ __privateAdd(this, _streamPromises, /* @__PURE__ */ new WeakMap());
552
+ }
553
+ add(stream) {
554
+ validateStream(stream);
555
+ if (__privateGet(this, _streams).has(stream)) {
556
+ return;
557
+ }
558
+ __privateGet(this, _streams).add(stream);
559
+ __privateGet(this, _onFinished) ?? __privateSet(this, _onFinished, onMergedStreamFinished(this, __privateGet(this, _streams), __privateGet(this, _unpipeEvent)));
560
+ const streamPromise = endWhenStreamsDone({
561
+ passThroughStream: this,
562
+ stream,
563
+ streams: __privateGet(this, _streams),
564
+ ended: __privateGet(this, _ended),
565
+ aborted: __privateGet(this, _aborted),
566
+ onFinished: __privateGet(this, _onFinished),
567
+ unpipeEvent: __privateGet(this, _unpipeEvent)
568
+ });
569
+ __privateGet(this, _streamPromises).set(stream, streamPromise);
570
+ stream.pipe(this, { end: false });
571
+ }
572
+ async remove(stream) {
573
+ validateStream(stream);
574
+ if (!__privateGet(this, _streams).has(stream)) {
575
+ return false;
576
+ }
577
+ const streamPromise = __privateGet(this, _streamPromises).get(stream);
578
+ if (streamPromise === void 0) {
579
+ return false;
580
+ }
581
+ __privateGet(this, _streamPromises).delete(stream);
582
+ stream.unpipe(this);
583
+ await streamPromise;
584
+ return true;
585
+ }
586
+ };
587
+ _streams = new WeakMap();
588
+ _ended = new WeakMap();
589
+ _aborted = new WeakMap();
590
+ _onFinished = new WeakMap();
591
+ _unpipeEvent = new WeakMap();
592
+ _streamPromises = new WeakMap();
593
+ var onMergedStreamFinished = async (passThroughStream, streams, unpipeEvent) => {
594
+ updateMaxListeners(passThroughStream, PASSTHROUGH_LISTENERS_COUNT);
595
+ const controller = new AbortController();
596
+ try {
597
+ await Promise.race([
598
+ onMergedStreamEnd(passThroughStream, controller),
599
+ onInputStreamsUnpipe(passThroughStream, streams, unpipeEvent, controller)
600
+ ]);
601
+ } finally {
602
+ controller.abort();
603
+ updateMaxListeners(passThroughStream, -PASSTHROUGH_LISTENERS_COUNT);
604
+ }
605
+ };
606
+ var onMergedStreamEnd = async (passThroughStream, { signal }) => {
607
+ try {
608
+ await (0, import_promises.finished)(passThroughStream, { signal, cleanup: true });
609
+ } catch (error) {
610
+ errorOrAbortStream(passThroughStream, error);
611
+ throw error;
612
+ }
613
+ };
614
+ var onInputStreamsUnpipe = async (passThroughStream, streams, unpipeEvent, { signal }) => {
615
+ for await (const [unpipedStream] of (0, import_node_events.on)(passThroughStream, "unpipe", { signal })) {
616
+ if (streams.has(unpipedStream)) {
617
+ unpipedStream.emit(unpipeEvent);
618
+ }
619
+ }
620
+ };
621
+ var validateStream = (stream) => {
622
+ if (typeof stream?.pipe !== "function") {
623
+ throw new TypeError(`Expected a readable stream, got: \`${typeof stream}\`.`);
624
+ }
625
+ };
626
+ var endWhenStreamsDone = async ({ passThroughStream, stream, streams, ended, aborted, onFinished, unpipeEvent }) => {
627
+ updateMaxListeners(passThroughStream, PASSTHROUGH_LISTENERS_PER_STREAM);
628
+ const controller = new AbortController();
629
+ try {
630
+ await Promise.race([
631
+ afterMergedStreamFinished(onFinished, stream, controller),
632
+ onInputStreamEnd({
633
+ passThroughStream,
634
+ stream,
635
+ streams,
636
+ ended,
637
+ aborted,
638
+ controller
639
+ }),
640
+ onInputStreamUnpipe({
641
+ stream,
642
+ streams,
643
+ ended,
644
+ aborted,
645
+ unpipeEvent,
646
+ controller
647
+ })
648
+ ]);
649
+ } finally {
650
+ controller.abort();
651
+ updateMaxListeners(passThroughStream, -PASSTHROUGH_LISTENERS_PER_STREAM);
652
+ }
653
+ if (streams.size > 0 && streams.size === ended.size + aborted.size) {
654
+ if (ended.size === 0 && aborted.size > 0) {
655
+ abortStream(passThroughStream);
656
+ } else {
657
+ endStream(passThroughStream);
658
+ }
659
+ }
660
+ };
661
+ var afterMergedStreamFinished = async (onFinished, stream, { signal }) => {
662
+ try {
663
+ await onFinished;
664
+ if (!signal.aborted) {
665
+ abortStream(stream);
666
+ }
667
+ } catch (error) {
668
+ if (!signal.aborted) {
669
+ errorOrAbortStream(stream, error);
670
+ }
671
+ }
672
+ };
673
+ var onInputStreamEnd = async ({ passThroughStream, stream, streams, ended, aborted, controller: { signal } }) => {
674
+ try {
675
+ await (0, import_promises.finished)(stream, {
676
+ signal,
677
+ cleanup: true,
678
+ readable: true,
679
+ writable: false
680
+ });
681
+ if (streams.has(stream)) {
682
+ ended.add(stream);
683
+ }
684
+ } catch (error) {
685
+ if (signal.aborted || !streams.has(stream)) {
686
+ return;
687
+ }
688
+ if (isAbortError(error)) {
689
+ aborted.add(stream);
690
+ } else {
691
+ errorStream(passThroughStream, error);
692
+ }
693
+ }
694
+ };
695
+ var onInputStreamUnpipe = async ({ stream, streams, ended, aborted, unpipeEvent, controller: { signal } }) => {
696
+ await (0, import_node_events.once)(stream, unpipeEvent, { signal });
697
+ if (!stream.readable) {
698
+ return (0, import_node_events.once)(signal, "abort", { signal });
699
+ }
700
+ streams.delete(stream);
701
+ ended.delete(stream);
702
+ aborted.delete(stream);
703
+ };
704
+ var endStream = (stream) => {
705
+ if (stream.writable) {
706
+ stream.end();
707
+ }
708
+ };
709
+ var errorOrAbortStream = (stream, error) => {
710
+ if (isAbortError(error)) {
711
+ abortStream(stream);
712
+ } else {
713
+ errorStream(stream, error);
714
+ }
715
+ };
716
+ var isAbortError = (error) => error?.code === "ERR_STREAM_PREMATURE_CLOSE";
717
+ var abortStream = (stream) => {
718
+ if (stream.readable || stream.writable) {
719
+ stream.destroy();
720
+ }
721
+ };
722
+ var errorStream = (stream, error) => {
723
+ if (!stream.destroyed) {
724
+ stream.once("error", noop);
725
+ stream.destroy(error);
726
+ }
727
+ };
728
+ var noop = () => {
729
+ };
730
+ var updateMaxListeners = (passThroughStream, increment) => {
731
+ const maxListeners = passThroughStream.getMaxListeners();
732
+ if (maxListeners !== 0 && maxListeners !== Number.POSITIVE_INFINITY) {
733
+ passThroughStream.setMaxListeners(maxListeners + increment);
734
+ }
735
+ };
736
+ var PASSTHROUGH_LISTENERS_COUNT = 2;
737
+ var PASSTHROUGH_LISTENERS_PER_STREAM = 1;
738
+
739
+ // node_modules/.pnpm/globby@16.2.0/node_modules/globby/index.js
740
+ var import_fast_glob3 = __toESM(require("fast-glob"), 1);
741
+
742
+ // node_modules/.pnpm/unicorn-magic@0.4.0/node_modules/unicorn-magic/node.js
743
+ var import_node_util = require("util");
744
+ var import_node_child_process = require("child_process");
745
+ var import_node_path = __toESM(require("path"), 1);
746
+ var import_node_url = require("url");
747
+ var execFileOriginal = (0, import_node_util.promisify)(import_node_child_process.execFile);
748
+ function toPath(urlOrPath) {
749
+ return urlOrPath instanceof URL ? (0, import_node_url.fileURLToPath)(urlOrPath) : urlOrPath;
750
+ }
751
+ var TEN_MEGABYTES_IN_BYTES = 10 * 1024 * 1024;
752
+
753
+ // node_modules/.pnpm/globby@16.2.0/node_modules/globby/ignore.js
754
+ var import_node_process = __toESM(require("process"), 1);
755
+ var import_node_fs2 = __toESM(require("fs"), 1);
756
+ var import_promises2 = __toESM(require("fs/promises"), 1);
757
+ var import_node_path4 = __toESM(require("path"), 1);
758
+ var import_node_os = __toESM(require("os"), 1);
759
+ var import_fast_glob2 = __toESM(require("fast-glob"), 1);
760
+ var import_ignore = __toESM(require_ignore(), 1);
761
+
762
+ // node_modules/.pnpm/is-path-inside@4.0.0/node_modules/is-path-inside/index.js
763
+ var import_node_path2 = __toESM(require("path"), 1);
764
+ function isPathInside(childPath, parentPath) {
765
+ const relation = import_node_path2.default.relative(parentPath, childPath);
766
+ return Boolean(
767
+ relation && relation !== ".." && !relation.startsWith(`..${import_node_path2.default.sep}`) && relation !== import_node_path2.default.resolve(childPath)
768
+ );
769
+ }
770
+
771
+ // node_modules/.pnpm/slash@5.1.0/node_modules/slash/index.js
772
+ function slash(path7) {
773
+ const isExtendedLengthPath = path7.startsWith("\\\\?\\");
774
+ if (isExtendedLengthPath) {
775
+ return path7;
776
+ }
777
+ return path7.replace(/\\/g, "/");
778
+ }
779
+
780
+ // node_modules/.pnpm/globby@16.2.0/node_modules/globby/utilities.js
781
+ var import_node_fs = __toESM(require("fs"), 1);
782
+ var import_node_path3 = __toESM(require("path"), 1);
783
+ var import_node_util2 = require("util");
784
+ var import_fast_glob = __toESM(require("fast-glob"), 1);
785
+ var isNegativePattern = (pattern) => pattern[0] === "!";
786
+ var normalizeAbsolutePatternToRelative = (pattern) => {
787
+ if (!pattern.startsWith("/")) {
788
+ return pattern;
789
+ }
790
+ const inner = pattern.slice(1);
791
+ const firstSlashIndex = inner.indexOf("/");
792
+ const firstSegment = firstSlashIndex > 0 ? inner.slice(0, firstSlashIndex) : inner;
793
+ if (firstSlashIndex > 0 && !import_fast_glob.default.isDynamicPattern(firstSegment)) {
794
+ return pattern;
795
+ }
796
+ return inner;
797
+ };
798
+ var absolutePrefixesMatch = (positivePrefix, negativePrefix) => negativePrefix === positivePrefix;
799
+ var getStaticAbsolutePathPrefix = (pattern) => {
800
+ if (!import_node_path3.default.isAbsolute(pattern)) {
801
+ return void 0;
802
+ }
803
+ const staticSegments = [];
804
+ for (const segment of pattern.split("/")) {
805
+ if (!segment) {
806
+ continue;
807
+ }
808
+ if (import_fast_glob.default.isDynamicPattern(segment)) {
809
+ break;
810
+ }
811
+ staticSegments.push(segment);
812
+ }
813
+ return staticSegments.length === 0 ? void 0 : `/${staticSegments.join("/")}`;
814
+ };
815
+ var normalizeNegativePattern = (pattern, positiveAbsolutePathPrefixes = [], hasRelativePositivePattern = false) => {
816
+ if (!pattern.startsWith("/")) {
817
+ return pattern;
818
+ }
819
+ const normalizedPattern = normalizeAbsolutePatternToRelative(pattern);
820
+ if (normalizedPattern !== pattern) {
821
+ return normalizedPattern;
822
+ }
823
+ if (hasRelativePositivePattern) {
824
+ return pattern.slice(1);
825
+ }
826
+ const negativeAbsolutePathPrefix = getStaticAbsolutePathPrefix(pattern);
827
+ const preserveAsAbsolutePattern = negativeAbsolutePathPrefix !== void 0 && positiveAbsolutePathPrefixes.some((positiveAbsolutePathPrefix) => absolutePrefixesMatch(positiveAbsolutePathPrefix, negativeAbsolutePathPrefix));
828
+ return preserveAsAbsolutePattern ? pattern : pattern.slice(1);
829
+ };
830
+ var bindFsMethod = (object, methodName) => {
831
+ const method = object?.[methodName];
832
+ return typeof method === "function" ? method.bind(object) : void 0;
833
+ };
834
+ var promisifyFsMethod = (object, methodName) => {
835
+ const method = object?.[methodName];
836
+ if (typeof method !== "function") {
837
+ return void 0;
838
+ }
839
+ return (0, import_node_util2.promisify)(method.bind(object));
840
+ };
841
+ var normalizeDirectoryPatternForFastGlob = (pattern) => {
842
+ if (!pattern.endsWith("/")) {
843
+ return pattern;
844
+ }
845
+ const trimmedPattern = pattern.replace(/\/+$/u, "");
846
+ if (!trimmedPattern) {
847
+ return "/**";
848
+ }
849
+ if (trimmedPattern === "**") {
850
+ return "**/**";
851
+ }
852
+ const hasLeadingSlash = trimmedPattern.startsWith("/");
853
+ const patternBody = hasLeadingSlash ? trimmedPattern.slice(1) : trimmedPattern;
854
+ const hasInnerSlash = patternBody.includes("/");
855
+ const needsRecursivePrefix = !hasLeadingSlash && !hasInnerSlash && !trimmedPattern.startsWith("**/");
856
+ const recursivePrefix = needsRecursivePrefix ? "**/" : "";
857
+ return `${recursivePrefix}${trimmedPattern}/**`;
858
+ };
859
+ var getParentDirectoryPrefix = (pattern) => {
860
+ const normalizedPattern = isNegativePattern(pattern) ? pattern.slice(1) : pattern;
861
+ const match = normalizedPattern.match(/^(\.\.\/)+/);
862
+ return match ? match[0] : "";
863
+ };
864
+ var adjustIgnorePatternsForParentDirectories = (patterns, ignorePatterns) => {
865
+ if (patterns.length === 0 || ignorePatterns.length === 0) {
866
+ return ignorePatterns;
867
+ }
868
+ const parentPrefixes = patterns.map((pattern) => getParentDirectoryPrefix(pattern));
869
+ const firstPrefix = parentPrefixes[0];
870
+ if (!firstPrefix) {
871
+ return ignorePatterns;
872
+ }
873
+ const allSamePrefix = parentPrefixes.every((prefix) => prefix === firstPrefix);
874
+ if (!allSamePrefix) {
875
+ return ignorePatterns;
876
+ }
877
+ return ignorePatterns.map((pattern) => {
878
+ if (pattern.startsWith("**/") && !pattern.startsWith("../")) {
879
+ return firstPrefix + pattern;
880
+ }
881
+ return pattern;
882
+ });
883
+ };
884
+ var getAsyncStatMethod = (fsImplementation) => bindFsMethod(fsImplementation?.promises, "stat") ?? bindFsMethod(import_node_fs.default.promises, "stat");
885
+ var getStatSyncMethod = (fsImplementation) => {
886
+ if (fsImplementation) {
887
+ return bindFsMethod(fsImplementation, "statSync");
888
+ }
889
+ return bindFsMethod(import_node_fs.default, "statSync");
890
+ };
891
+ var pathHasGitDirectory = (stats) => Boolean(stats?.isDirectory?.() || stats?.isFile?.());
892
+ var buildPathChain = (startPath, rootPath) => {
893
+ const chain = [];
894
+ let currentPath = startPath;
895
+ chain.push(currentPath);
896
+ while (currentPath !== rootPath) {
897
+ const parentPath = import_node_path3.default.dirname(currentPath);
898
+ if (parentPath === currentPath) {
899
+ break;
900
+ }
901
+ currentPath = parentPath;
902
+ chain.push(currentPath);
903
+ }
904
+ return chain;
905
+ };
906
+ var findGitRootInChain = async (paths, statMethod) => {
907
+ for (const directory of paths) {
908
+ const gitPath = import_node_path3.default.join(directory, ".git");
909
+ try {
910
+ const stats = await statMethod(gitPath);
911
+ if (pathHasGitDirectory(stats)) {
912
+ return directory;
913
+ }
914
+ } catch {
915
+ }
916
+ }
917
+ return void 0;
918
+ };
919
+ var findGitRootSyncUncached = (cwd, fsImplementation) => {
920
+ const statSyncMethod = getStatSyncMethod(fsImplementation);
921
+ if (!statSyncMethod) {
922
+ return void 0;
923
+ }
924
+ const currentPath = import_node_path3.default.resolve(cwd);
925
+ const { root } = import_node_path3.default.parse(currentPath);
926
+ const chain = buildPathChain(currentPath, root);
927
+ for (const directory of chain) {
928
+ const gitPath = import_node_path3.default.join(directory, ".git");
929
+ try {
930
+ const stats = statSyncMethod(gitPath);
931
+ if (pathHasGitDirectory(stats)) {
932
+ return directory;
933
+ }
934
+ } catch {
935
+ }
936
+ }
937
+ return void 0;
938
+ };
939
+ var findGitRootSync = (cwd, fsImplementation) => {
940
+ if (typeof cwd !== "string") {
941
+ throw new TypeError("cwd must be a string");
942
+ }
943
+ return findGitRootSyncUncached(cwd, fsImplementation);
944
+ };
945
+ var findGitRootAsyncUncached = async (cwd, fsImplementation) => {
946
+ const statMethod = getAsyncStatMethod(fsImplementation);
947
+ if (!statMethod) {
948
+ return findGitRootSync(cwd, fsImplementation);
949
+ }
950
+ const currentPath = import_node_path3.default.resolve(cwd);
951
+ const { root } = import_node_path3.default.parse(currentPath);
952
+ const chain = buildPathChain(currentPath, root);
953
+ return findGitRootInChain(chain, statMethod);
954
+ };
955
+ var findGitRoot = async (cwd, fsImplementation) => {
956
+ if (typeof cwd !== "string") {
957
+ throw new TypeError("cwd must be a string");
958
+ }
959
+ return findGitRootAsyncUncached(cwd, fsImplementation);
960
+ };
961
+ var isWithinGitRoot = (gitRoot, cwd) => {
962
+ const resolvedGitRoot = import_node_path3.default.resolve(gitRoot);
963
+ const resolvedCwd = import_node_path3.default.resolve(cwd);
964
+ return resolvedCwd === resolvedGitRoot || isPathInside(resolvedCwd, resolvedGitRoot);
965
+ };
966
+ var getParentGitignorePaths = (gitRoot, cwd) => {
967
+ if (gitRoot && typeof gitRoot !== "string") {
968
+ throw new TypeError("gitRoot must be a string or undefined");
969
+ }
970
+ if (typeof cwd !== "string") {
971
+ throw new TypeError("cwd must be a string");
972
+ }
973
+ if (!gitRoot) {
974
+ return [];
975
+ }
976
+ if (!isWithinGitRoot(gitRoot, cwd)) {
977
+ return [];
978
+ }
979
+ const chain = buildPathChain(import_node_path3.default.resolve(cwd), import_node_path3.default.resolve(gitRoot));
980
+ return [...chain].reverse().map((directory) => import_node_path3.default.join(directory, ".gitignore"));
981
+ };
982
+ var convertPatternsForFastGlob = (patterns, usingGitRoot, normalizeDirectoryPatternForFastGlob2) => {
983
+ if (usingGitRoot) {
984
+ return [];
985
+ }
986
+ const result = [];
987
+ let hasNegations = false;
988
+ for (const pattern of patterns) {
989
+ if (isNegativePattern(pattern)) {
990
+ hasNegations = true;
991
+ break;
992
+ }
993
+ result.push(normalizeDirectoryPatternForFastGlob2(pattern));
994
+ }
995
+ return hasNegations ? [] : result;
996
+ };
997
+
998
+ // node_modules/.pnpm/globby@16.2.0/node_modules/globby/ignore.js
999
+ var defaultIgnoredDirectories = [
1000
+ "**/node_modules",
1001
+ "**/flow-typed",
1002
+ "**/coverage",
1003
+ "**/.git"
1004
+ ];
1005
+ var ignoreFilesGlobOptions = {
1006
+ absolute: true,
1007
+ dot: true
1008
+ };
1009
+ var GITIGNORE_FILES_PATTERN = "**/.gitignore";
1010
+ var MAX_INCLUDE_DEPTH = 10;
1011
+ var getReadFileMethod = (fsImplementation) => bindFsMethod(fsImplementation?.promises, "readFile") ?? bindFsMethod(import_promises2.default, "readFile") ?? promisifyFsMethod(fsImplementation, "readFile");
1012
+ var getReadFileSyncMethod = (fsImplementation) => bindFsMethod(fsImplementation, "readFileSync") ?? bindFsMethod(import_node_fs2.default, "readFileSync");
1013
+ var shouldSkipIgnoreFileError = (error, suppressErrors) => {
1014
+ if (!error) {
1015
+ return Boolean(suppressErrors);
1016
+ }
1017
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") {
1018
+ return true;
1019
+ }
1020
+ return Boolean(suppressErrors);
1021
+ };
1022
+ var createReadError = (kind, filePath, error) => {
1023
+ const prefix = `Failed to read ${kind} at ${filePath}`;
1024
+ if (error instanceof Error) {
1025
+ return new Error(`${prefix}: ${error.message}`, { cause: error });
1026
+ }
1027
+ return new Error(`${prefix}: ${String(error)}`);
1028
+ };
1029
+ var createIgnoreFileReadError = (filePath, error) => createReadError("ignore file", filePath, error);
1030
+ var createGitConfigReadError = (filePath, error) => createReadError("git config", filePath, error);
1031
+ var processIgnoreFileCore = (filePath, readMethod, suppressErrors) => {
1032
+ try {
1033
+ const content = readMethod(filePath, "utf8");
1034
+ return { filePath, content };
1035
+ } catch (error) {
1036
+ if (shouldSkipIgnoreFileError(error, suppressErrors)) {
1037
+ return void 0;
1038
+ }
1039
+ throw createIgnoreFileReadError(filePath, error);
1040
+ }
1041
+ };
1042
+ var readIgnoreFilesSafely = async (paths, readFileMethod, suppressErrors) => {
1043
+ const fileResults = await Promise.all(paths.map(async (filePath) => {
1044
+ try {
1045
+ const content = await readFileMethod(filePath, "utf8");
1046
+ return { filePath, content };
1047
+ } catch (error) {
1048
+ if (shouldSkipIgnoreFileError(error, suppressErrors)) {
1049
+ return void 0;
1050
+ }
1051
+ throw createIgnoreFileReadError(filePath, error);
1052
+ }
1053
+ }));
1054
+ return fileResults.filter(Boolean);
1055
+ };
1056
+ var readIgnoreFilesSafelySync = (paths, readFileSyncMethod, suppressErrors) => paths.map((filePath) => processIgnoreFileCore(filePath, readFileSyncMethod, suppressErrors)).filter(Boolean);
1057
+ var dedupePaths = (paths) => {
1058
+ const seen = /* @__PURE__ */ new Set();
1059
+ return paths.filter((filePath) => {
1060
+ if (seen.has(filePath)) {
1061
+ return false;
1062
+ }
1063
+ seen.add(filePath);
1064
+ return true;
1065
+ });
1066
+ };
1067
+ var globIgnoreFiles = (globFunction, patterns, normalizedOptions) => globFunction(patterns, {
1068
+ ...normalizedOptions,
1069
+ ...ignoreFilesGlobOptions
1070
+ // Must be last to ensure absolute/dot flags stick
1071
+ });
1072
+ var getParentIgnorePaths = (gitRoot, normalizedOptions) => gitRoot ? getParentGitignorePaths(gitRoot, normalizedOptions.cwd) : [];
1073
+ var combineIgnoreFilePaths = (gitRoot, normalizedOptions, childPaths) => dedupePaths([
1074
+ ...getParentIgnorePaths(gitRoot, normalizedOptions),
1075
+ ...childPaths
1076
+ ]);
1077
+ var buildIgnoreResult = (files, normalizedOptions, gitRoot) => {
1078
+ const baseDir = gitRoot || normalizedOptions.cwd;
1079
+ const patterns = getPatternsFromIgnoreFiles(files, baseDir);
1080
+ const matcher = createIgnoreMatcher(patterns, normalizedOptions.cwd, baseDir);
1081
+ return {
1082
+ patterns,
1083
+ matcher,
1084
+ predicate: (fileOrDirectory) => matcher(fileOrDirectory).ignored,
1085
+ usingGitRoot: Boolean(gitRoot && gitRoot !== normalizedOptions.cwd)
1086
+ };
1087
+ };
1088
+ var applyBaseToPattern = (pattern, base) => {
1089
+ if (!base) {
1090
+ return pattern;
1091
+ }
1092
+ const isNegative = isNegativePattern(pattern);
1093
+ const cleanPattern = isNegative ? pattern.slice(1) : pattern;
1094
+ const slashIndex = cleanPattern.indexOf("/");
1095
+ const hasNonTrailingSlash = slashIndex !== -1 && slashIndex !== cleanPattern.length - 1;
1096
+ let result;
1097
+ if (!hasNonTrailingSlash) {
1098
+ result = import_node_path4.default.posix.join(base, "**", cleanPattern);
1099
+ } else if (cleanPattern.startsWith("/")) {
1100
+ result = import_node_path4.default.posix.join(base, cleanPattern.slice(1));
1101
+ } else {
1102
+ result = import_node_path4.default.posix.join(base, cleanPattern);
1103
+ }
1104
+ return isNegative ? "!" + result : result;
1105
+ };
1106
+ var parseIgnoreFile = (file, cwd) => {
1107
+ const base = slash(import_node_path4.default.relative(cwd, import_node_path4.default.dirname(file.filePath)));
1108
+ return file.content.split(/\r?\n/).filter((line) => line && !line.startsWith("#")).map((pattern) => applyBaseToPattern(pattern, base));
1109
+ };
1110
+ var toRelativePath = (fileOrDirectory, cwd) => {
1111
+ if (import_node_path4.default.isAbsolute(fileOrDirectory)) {
1112
+ const relativePath = import_node_path4.default.relative(cwd, fileOrDirectory);
1113
+ if (relativePath && !isPathInside(fileOrDirectory, cwd)) {
1114
+ return void 0;
1115
+ }
1116
+ return relativePath;
1117
+ }
1118
+ if (fileOrDirectory.startsWith("./")) {
1119
+ return fileOrDirectory.slice(2);
1120
+ }
1121
+ if (fileOrDirectory.startsWith("../")) {
1122
+ return void 0;
1123
+ }
1124
+ return fileOrDirectory;
1125
+ };
1126
+ var notIgnored = { ignored: false, unignored: false };
1127
+ var createIgnoreMatcher = (patterns, cwd, baseDir) => {
1128
+ const ignores = (0, import_ignore.default)().add(patterns);
1129
+ const resolvedCwd = import_node_path4.default.normalize(import_node_path4.default.resolve(cwd));
1130
+ const resolvedBaseDir = import_node_path4.default.normalize(import_node_path4.default.resolve(baseDir));
1131
+ return (fileOrDirectory) => {
1132
+ fileOrDirectory = toPath(fileOrDirectory);
1133
+ const hasTrailingSeparator = /[/\\]$/.test(fileOrDirectory);
1134
+ const normalizedPath = import_node_path4.default.normalize(import_node_path4.default.resolve(fileOrDirectory));
1135
+ if (normalizedPath === resolvedCwd) {
1136
+ return notIgnored;
1137
+ }
1138
+ let relativePath = toRelativePath(fileOrDirectory, resolvedBaseDir);
1139
+ if (relativePath === void 0) {
1140
+ return notIgnored;
1141
+ }
1142
+ if (!relativePath) {
1143
+ return notIgnored;
1144
+ }
1145
+ if (hasTrailingSeparator && !relativePath.endsWith(import_node_path4.default.sep)) {
1146
+ relativePath += import_node_path4.default.sep;
1147
+ }
1148
+ return ignores.test(slash(relativePath));
1149
+ };
1150
+ };
1151
+ var normalizeOptions = (options = {}) => {
1152
+ const ignoreOption = options.ignore ? Array.isArray(options.ignore) ? options.ignore : [options.ignore] : [];
1153
+ const cwd = toPath(options.cwd) ?? import_node_process.default.cwd();
1154
+ const deep = typeof options.deep === "number" ? Math.max(0, options.deep) + 1 : Number.POSITIVE_INFINITY;
1155
+ return {
1156
+ cwd,
1157
+ suppressErrors: options.suppressErrors ?? false,
1158
+ deep,
1159
+ ignore: [...ignoreOption, ...defaultIgnoredDirectories],
1160
+ followSymbolicLinks: options.followSymbolicLinks ?? true,
1161
+ concurrency: options.concurrency,
1162
+ throwErrorOnBrokenSymbolicLink: options.throwErrorOnBrokenSymbolicLink ?? false,
1163
+ fs: options.fs
1164
+ };
1165
+ };
1166
+ var unescapeGitQuotedValue = (value) => value.replaceAll(/\\(["\\abfnrtv])/g, (_match, escapedCharacter) => {
1167
+ switch (escapedCharacter) {
1168
+ case "a": {
1169
+ return "\x07";
1170
+ }
1171
+ case "b": {
1172
+ return "\b";
1173
+ }
1174
+ case "f": {
1175
+ return "\f";
1176
+ }
1177
+ case "n": {
1178
+ return "\n";
1179
+ }
1180
+ case "r": {
1181
+ return "\r";
1182
+ }
1183
+ case "t": {
1184
+ return " ";
1185
+ }
1186
+ case "v": {
1187
+ return "\v";
1188
+ }
1189
+ default: {
1190
+ return escapedCharacter;
1191
+ }
1192
+ }
1193
+ });
1194
+ var parseGitConfigValue = (value) => {
1195
+ const trimmedValue = value.trim();
1196
+ const quotedMatch = trimmedValue.match(/^"((?:[^"\\]|\\.)*)"\s*(?:[#;].*)?$/);
1197
+ if (quotedMatch) {
1198
+ return unescapeGitQuotedValue(quotedMatch[1]);
1199
+ }
1200
+ return trimmedValue.replace(/\s[#;].*$/, "").trim();
1201
+ };
1202
+ var resolveConfigPath = (filePath, configPath) => {
1203
+ if (configPath.startsWith("~/")) {
1204
+ const homeDirectory = import_node_os.default.homedir();
1205
+ const resolved = import_node_path4.default.join(homeDirectory, configPath.slice(2));
1206
+ if (!isPathInside(resolved, homeDirectory)) {
1207
+ return import_node_path4.default.join(homeDirectory, ".globby-invalid-path-traversal");
1208
+ }
1209
+ return resolved;
1210
+ }
1211
+ if (import_node_path4.default.isAbsolute(configPath)) {
1212
+ return configPath;
1213
+ }
1214
+ return import_node_path4.default.resolve(import_node_path4.default.dirname(filePath), configPath);
1215
+ };
1216
+ var parseGitConfigSection = (line) => {
1217
+ if (!line.startsWith("[")) {
1218
+ return void 0;
1219
+ }
1220
+ let inQuotes = false;
1221
+ let isEscaped = false;
1222
+ for (let index = 1; index < line.length; index++) {
1223
+ const character = line[index];
1224
+ if (isEscaped) {
1225
+ isEscaped = false;
1226
+ continue;
1227
+ }
1228
+ if (character === "\\") {
1229
+ isEscaped = true;
1230
+ continue;
1231
+ }
1232
+ if (character === '"') {
1233
+ inQuotes = !inQuotes;
1234
+ continue;
1235
+ }
1236
+ if (character === "]" && !inQuotes) {
1237
+ const remainder = line.slice(index + 1).trimStart();
1238
+ if (remainder && !remainder.startsWith("#") && !remainder.startsWith(";")) {
1239
+ return void 0;
1240
+ }
1241
+ return line.slice(1, index).trim();
1242
+ }
1243
+ }
1244
+ return void 0;
1245
+ };
1246
+ var parseGitConfigEntry = (line) => {
1247
+ const match = line.match(/^([A-Za-z\d-.]+)\s*=\s*(.*)$/);
1248
+ if (!match) {
1249
+ return void 0;
1250
+ }
1251
+ return {
1252
+ key: match[1].toLowerCase(),
1253
+ value: parseGitConfigValue(match[2])
1254
+ };
1255
+ };
1256
+ var parseIncludeIfCondition = (section) => {
1257
+ if (!section) {
1258
+ return void 0;
1259
+ }
1260
+ const match = section.match(/^includeif\s+"([^"]+)"$/i);
1261
+ return match ? match[1] : void 0;
1262
+ };
1263
+ var normalizeGitConfigConditionPattern = (pattern, configFilePath) => {
1264
+ if (pattern.startsWith("~/")) {
1265
+ pattern = import_node_path4.default.join(import_node_os.default.homedir(), pattern.slice(2));
1266
+ } else if (pattern.startsWith("./")) {
1267
+ pattern = import_node_path4.default.resolve(import_node_path4.default.dirname(configFilePath), pattern.slice(2));
1268
+ } else if (!import_node_path4.default.isAbsolute(pattern)) {
1269
+ pattern = `**/${pattern}`;
1270
+ }
1271
+ if (pattern.endsWith("/")) {
1272
+ pattern += "**";
1273
+ }
1274
+ return slash(pattern);
1275
+ };
1276
+ var gitConfigGlobToRegex = (pattern, flags) => {
1277
+ let regex = "";
1278
+ for (let index = 0; index < pattern.length; index++) {
1279
+ const character = pattern[index];
1280
+ const nextCharacter = pattern[index + 1];
1281
+ const nextNextCharacter = pattern[index + 2];
1282
+ if (character === "*" && nextCharacter === "*" && nextNextCharacter === "/") {
1283
+ regex += "(?:.*/)?";
1284
+ index += 2;
1285
+ continue;
1286
+ }
1287
+ if (character === "*" && nextCharacter === "*") {
1288
+ regex += ".*";
1289
+ index += 1;
1290
+ continue;
1291
+ }
1292
+ if (character === "*") {
1293
+ regex += "[^/]*";
1294
+ continue;
1295
+ }
1296
+ if (character === "?") {
1297
+ regex += "[^/]";
1298
+ continue;
1299
+ }
1300
+ if (character === "[") {
1301
+ const closingBracketIndex = pattern.indexOf("]", index + 1);
1302
+ if (closingBracketIndex !== -1) {
1303
+ const bracketContent = pattern.slice(index + 1, closingBracketIndex);
1304
+ if (bracketContent) {
1305
+ const negatedBracketContent = bracketContent[0] === "!" ? `^${bracketContent.slice(1)}` : bracketContent;
1306
+ regex += `[${negatedBracketContent}]`;
1307
+ index = closingBracketIndex;
1308
+ continue;
1309
+ }
1310
+ }
1311
+ }
1312
+ regex += /[|\\{}()[\]^$+?.]/.test(character) ? `\\${character}` : character;
1313
+ }
1314
+ try {
1315
+ return new RegExp(`^${regex}$`, flags);
1316
+ } catch {
1317
+ return /(?!)/;
1318
+ }
1319
+ };
1320
+ var matchesIncludeIfCondition = (condition, gitDirectory, configFilePath) => {
1321
+ if (!gitDirectory) {
1322
+ return false;
1323
+ }
1324
+ const match = condition.match(/^(gitdir|gitdir\/i):(.*)$/i);
1325
+ if (!match) {
1326
+ return false;
1327
+ }
1328
+ const [, keyword, rawPattern] = match;
1329
+ const pattern = normalizeGitConfigConditionPattern(rawPattern.trim(), configFilePath);
1330
+ const isCaseInsensitive = keyword.toLowerCase() === "gitdir/i";
1331
+ const regularExpression = gitConfigGlobToRegex(pattern, isCaseInsensitive ? "i" : void 0);
1332
+ const normalizedGitDirectory = slash(import_node_path4.default.resolve(gitDirectory));
1333
+ return regularExpression.test(normalizedGitDirectory);
1334
+ };
1335
+ var shouldIncludeConfigSection = (section, gitDirectory, configFilePath) => {
1336
+ if (section?.toLowerCase() === "include") {
1337
+ return true;
1338
+ }
1339
+ const condition = parseIncludeIfCondition(section);
1340
+ return condition ? matchesIncludeIfCondition(condition, gitDirectory, configFilePath) : false;
1341
+ };
1342
+ var createExcludesFileValue = (value, declaringFilePath) => ({
1343
+ value,
1344
+ declaringFilePath
1345
+ });
1346
+ var parseGitConfigForExcludesFile = (content, normalizedPath, gitDirectory) => {
1347
+ let currentSection;
1348
+ let excludesFile;
1349
+ const includePaths = [];
1350
+ for (const line of content.split(/\r?\n/)) {
1351
+ const trimmed = line.trim();
1352
+ if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith(";")) {
1353
+ continue;
1354
+ }
1355
+ if (trimmed.startsWith("[")) {
1356
+ currentSection = parseGitConfigSection(trimmed);
1357
+ continue;
1358
+ }
1359
+ const entry = parseGitConfigEntry(trimmed);
1360
+ if (!entry) {
1361
+ continue;
1362
+ }
1363
+ if (currentSection?.toLowerCase() === "core" && entry.key === "excludesfile") {
1364
+ excludesFile = createExcludesFileValue(entry.value, normalizedPath);
1365
+ continue;
1366
+ }
1367
+ if (shouldIncludeConfigSection(currentSection, gitDirectory, normalizedPath) && entry.key === "path" && entry.value) {
1368
+ includePaths.push(resolveConfigPath(normalizedPath, entry.value));
1369
+ }
1370
+ }
1371
+ return { excludesFile, includePaths };
1372
+ };
1373
+ var readGitConfigFile = (normalizedPath, readMethod, suppressErrors) => {
1374
+ try {
1375
+ return readMethod(normalizedPath, "utf8");
1376
+ } catch (error) {
1377
+ if (shouldSkipIgnoreFileError(error, suppressErrors)) {
1378
+ return void 0;
1379
+ }
1380
+ throw createGitConfigReadError(normalizedPath, error);
1381
+ }
1382
+ };
1383
+ var getExcludesFileFromGitConfigSync = (filePath, readFileSync, gitDirectory, options = {}) => {
1384
+ const { suppressErrors, includeStack = /* @__PURE__ */ new Set(), depth = 0 } = options;
1385
+ const normalizedPath = import_node_path4.default.resolve(filePath);
1386
+ if (includeStack.has(normalizedPath)) {
1387
+ return void 0;
1388
+ }
1389
+ if (depth >= MAX_INCLUDE_DEPTH) {
1390
+ return void 0;
1391
+ }
1392
+ includeStack.add(normalizedPath);
1393
+ const content = readGitConfigFile(normalizedPath, readFileSync, suppressErrors);
1394
+ if (content === void 0) {
1395
+ includeStack.delete(normalizedPath);
1396
+ return void 0;
1397
+ }
1398
+ let { excludesFile, includePaths } = parseGitConfigForExcludesFile(content, normalizedPath, gitDirectory);
1399
+ for (const includePath of includePaths) {
1400
+ const includedExcludesFile = getExcludesFileFromGitConfigSync(includePath, readFileSync, gitDirectory, { suppressErrors, includeStack, depth: depth + 1 });
1401
+ if (includedExcludesFile !== void 0) {
1402
+ excludesFile = includedExcludesFile;
1403
+ }
1404
+ }
1405
+ includeStack.delete(normalizedPath);
1406
+ return excludesFile;
1407
+ };
1408
+ var getExcludesFileFromGitConfigAsync = async (filePath, readFile, gitDirectory, options = {}) => {
1409
+ const { suppressErrors, includeStack = /* @__PURE__ */ new Set(), depth = 0 } = options;
1410
+ const normalizedPath = import_node_path4.default.resolve(filePath);
1411
+ if (includeStack.has(normalizedPath)) {
1412
+ return void 0;
1413
+ }
1414
+ if (depth >= MAX_INCLUDE_DEPTH) {
1415
+ return void 0;
1416
+ }
1417
+ includeStack.add(normalizedPath);
1418
+ let content;
1419
+ try {
1420
+ content = await readFile(normalizedPath, "utf8");
1421
+ } catch (error) {
1422
+ includeStack.delete(normalizedPath);
1423
+ if (shouldSkipIgnoreFileError(error, suppressErrors)) {
1424
+ return void 0;
1425
+ }
1426
+ throw createGitConfigReadError(normalizedPath, error);
1427
+ }
1428
+ let { excludesFile, includePaths } = parseGitConfigForExcludesFile(content, normalizedPath, gitDirectory);
1429
+ for (const includePath of includePaths) {
1430
+ const includedExcludesFile = await getExcludesFileFromGitConfigAsync(includePath, readFile, gitDirectory, { suppressErrors, includeStack, depth: depth + 1 });
1431
+ if (includedExcludesFile !== void 0) {
1432
+ excludesFile = includedExcludesFile;
1433
+ }
1434
+ }
1435
+ includeStack.delete(normalizedPath);
1436
+ return excludesFile;
1437
+ };
1438
+ var resolveGitDirectoryFromFile = (gitFilePath, content) => {
1439
+ const match = content.match(/^gitdir:\s*(.+?)\s*$/i);
1440
+ if (!match) {
1441
+ return gitFilePath;
1442
+ }
1443
+ return import_node_path4.default.resolve(import_node_path4.default.dirname(gitFilePath), match[1]);
1444
+ };
1445
+ var getGitDirectorySync = (gitRoot, readFileSync) => {
1446
+ if (!gitRoot) {
1447
+ return void 0;
1448
+ }
1449
+ const gitFilePath = import_node_path4.default.join(gitRoot, ".git");
1450
+ try {
1451
+ return resolveGitDirectoryFromFile(gitFilePath, readFileSync(gitFilePath, "utf8"));
1452
+ } catch {
1453
+ return gitFilePath;
1454
+ }
1455
+ };
1456
+ var getGitDirectoryAsync = async (gitRoot, readFile) => {
1457
+ if (!gitRoot) {
1458
+ return void 0;
1459
+ }
1460
+ const gitFilePath = import_node_path4.default.join(gitRoot, ".git");
1461
+ try {
1462
+ return resolveGitDirectoryFromFile(gitFilePath, await readFile(gitFilePath, "utf8"));
1463
+ } catch {
1464
+ return gitFilePath;
1465
+ }
1466
+ };
1467
+ var getXdgConfigHome = () => import_node_process.default.env.XDG_CONFIG_HOME || import_node_path4.default.join(import_node_os.default.homedir(), ".config");
1468
+ var getGitConfigPaths = () => {
1469
+ if ("GIT_CONFIG_GLOBAL" in import_node_process.default.env) {
1470
+ const value = import_node_process.default.env.GIT_CONFIG_GLOBAL;
1471
+ return value ? [value] : [];
1472
+ }
1473
+ return [
1474
+ import_node_path4.default.join(getXdgConfigHome(), "git", "config"),
1475
+ import_node_path4.default.join(import_node_os.default.homedir(), ".gitconfig")
1476
+ ];
1477
+ };
1478
+ var getDefaultGlobalGitignorePath = () => import_node_path4.default.join(getXdgConfigHome(), "git", "ignore");
1479
+ var resolveExcludesFilePath = (excludesFileConfig) => {
1480
+ if (excludesFileConfig?.value === "") {
1481
+ return void 0;
1482
+ }
1483
+ if (excludesFileConfig === void 0) {
1484
+ return getDefaultGlobalGitignorePath();
1485
+ }
1486
+ return resolveConfigPath(excludesFileConfig.declaringFilePath, excludesFileConfig.value);
1487
+ };
1488
+ var readGlobalGitignoreContent = (filePath, readMethod, suppressErrors) => {
1489
+ try {
1490
+ const content = readMethod(filePath, "utf8");
1491
+ return { filePath, content };
1492
+ } catch (error) {
1493
+ if (shouldSkipIgnoreFileError(error, suppressErrors)) {
1494
+ return void 0;
1495
+ }
1496
+ throw createIgnoreFileReadError(filePath, error);
1497
+ }
1498
+ };
1499
+ var getGlobalGitignoreFile = (options = {}) => {
1500
+ const cwd = toPath(options.cwd) ?? import_node_process.default.cwd();
1501
+ const readFileSync = getReadFileSyncMethod(options.fs);
1502
+ const gitRoot = findGitRootSync(cwd, options.fs);
1503
+ const gitDirectory = getGitDirectorySync(gitRoot, readFileSync);
1504
+ let excludesFileConfig;
1505
+ for (const gitConfigPath of getGitConfigPaths()) {
1506
+ const value = getExcludesFileFromGitConfigSync(gitConfigPath, readFileSync, gitDirectory, { suppressErrors: options.suppressErrors });
1507
+ if (value !== void 0) {
1508
+ excludesFileConfig = value;
1509
+ }
1510
+ }
1511
+ const filePath = resolveExcludesFilePath(excludesFileConfig);
1512
+ return filePath === void 0 ? void 0 : readGlobalGitignoreContent(filePath, readFileSync, options.suppressErrors);
1513
+ };
1514
+ var getGlobalGitignoreFileAsync = async (options = {}) => {
1515
+ const cwd = toPath(options.cwd) ?? import_node_process.default.cwd();
1516
+ const readFile = getReadFileMethod(options.fs);
1517
+ const gitRoot = await findGitRoot(cwd, options.fs);
1518
+ const gitDirectory = await getGitDirectoryAsync(gitRoot, readFile);
1519
+ const excludesFileValues = await Promise.all(getGitConfigPaths().map((gitConfigPath) => getExcludesFileFromGitConfigAsync(
1520
+ gitConfigPath,
1521
+ readFile,
1522
+ gitDirectory,
1523
+ { suppressErrors: options.suppressErrors }
1524
+ )));
1525
+ const excludesFileConfig = excludesFileValues.findLast((value) => value !== void 0);
1526
+ const filePath = resolveExcludesFilePath(excludesFileConfig);
1527
+ if (filePath === void 0) {
1528
+ return void 0;
1529
+ }
1530
+ try {
1531
+ const content = await readFile(filePath, "utf8");
1532
+ return { filePath, content };
1533
+ } catch (error) {
1534
+ if (shouldSkipIgnoreFileError(error, options.suppressErrors)) {
1535
+ return void 0;
1536
+ }
1537
+ throw createIgnoreFileReadError(filePath, error);
1538
+ }
1539
+ };
1540
+ var buildGlobalMatcher = (globalIgnoreFile, cwd, rootDirectory = cwd) => {
1541
+ const patterns = parseIgnoreFile(globalIgnoreFile, import_node_path4.default.dirname(globalIgnoreFile.filePath));
1542
+ return createIgnoreMatcher(patterns, cwd, rootDirectory);
1543
+ };
1544
+ var collectIgnoreFileArtifactsAsync = async (patterns, options, includeParentIgnoreFiles) => {
1545
+ const normalizedOptions = normalizeOptions(options);
1546
+ const childPaths = await globIgnoreFiles(import_fast_glob2.default, patterns, normalizedOptions);
1547
+ const gitRoot = includeParentIgnoreFiles ? await findGitRoot(normalizedOptions.cwd, normalizedOptions.fs) : void 0;
1548
+ const allPaths = combineIgnoreFilePaths(gitRoot, normalizedOptions, childPaths);
1549
+ const readFileMethod = getReadFileMethod(normalizedOptions.fs);
1550
+ const files = await readIgnoreFilesSafely(allPaths, readFileMethod, normalizedOptions.suppressErrors);
1551
+ return { files, normalizedOptions, gitRoot };
1552
+ };
1553
+ var collectIgnoreFileArtifactsSync = (patterns, options, includeParentIgnoreFiles) => {
1554
+ const normalizedOptions = normalizeOptions(options);
1555
+ const childPaths = globIgnoreFiles(import_fast_glob2.default.sync, patterns, normalizedOptions);
1556
+ const gitRoot = includeParentIgnoreFiles ? findGitRootSync(normalizedOptions.cwd, normalizedOptions.fs) : void 0;
1557
+ const allPaths = combineIgnoreFilePaths(gitRoot, normalizedOptions, childPaths);
1558
+ const readFileSyncMethod = getReadFileSyncMethod(normalizedOptions.fs);
1559
+ const files = readIgnoreFilesSafelySync(allPaths, readFileSyncMethod, normalizedOptions.suppressErrors);
1560
+ return { files, normalizedOptions, gitRoot };
1561
+ };
1562
+ var getPatternsFromIgnoreFiles = (files, baseDir) => files.flatMap((file) => parseIgnoreFile(file, baseDir));
1563
+ var getIgnorePatternsAndPredicate = async (patterns, options, includeParentIgnoreFiles = false) => {
1564
+ const { files, normalizedOptions, gitRoot } = await collectIgnoreFileArtifactsAsync(
1565
+ patterns,
1566
+ options,
1567
+ includeParentIgnoreFiles
1568
+ );
1569
+ return buildIgnoreResult(files, normalizedOptions, gitRoot);
1570
+ };
1571
+ var getIgnorePatternsAndPredicateSync = (patterns, options, includeParentIgnoreFiles = false) => {
1572
+ const { files, normalizedOptions, gitRoot } = collectIgnoreFileArtifactsSync(
1573
+ patterns,
1574
+ options,
1575
+ includeParentIgnoreFiles
1576
+ );
1577
+ return buildIgnoreResult(files, normalizedOptions, gitRoot);
1578
+ };
1579
+
1580
+ // node_modules/.pnpm/globby@16.2.0/node_modules/globby/index.js
1581
+ var assertPatternsInput = (patterns) => {
1582
+ if (patterns.some((pattern) => typeof pattern !== "string")) {
1583
+ throw new TypeError("Patterns must be a string or an array of strings");
1584
+ }
1585
+ };
1586
+ var getStatMethod = (fsImplementation) => {
1587
+ if (fsImplementation) {
1588
+ return bindFsMethod(fsImplementation.promises, "stat") ?? promisifyFsMethod(fsImplementation, "stat");
1589
+ }
1590
+ return bindFsMethod(import_node_fs3.default.promises, "stat");
1591
+ };
1592
+ var getStatSyncMethod2 = (fsImplementation) => bindFsMethod(fsImplementation, "statSync") ?? bindFsMethod(import_node_fs3.default, "statSync");
1593
+ var isDirectory = async (path7, fsImplementation) => {
1594
+ try {
1595
+ const stats = await getStatMethod(fsImplementation)(path7);
1596
+ return stats.isDirectory();
1597
+ } catch {
1598
+ return false;
1599
+ }
1600
+ };
1601
+ var isDirectorySync = (path7, fsImplementation) => {
1602
+ try {
1603
+ const stats = getStatSyncMethod2(fsImplementation)(path7);
1604
+ return stats.isDirectory();
1605
+ } catch {
1606
+ return false;
1607
+ }
1608
+ };
1609
+ var normalizePathForDirectoryGlob = (filePath, cwd) => {
1610
+ const path7 = isNegativePattern(filePath) ? filePath.slice(1) : filePath;
1611
+ return import_node_path5.default.isAbsolute(path7) ? path7 : import_node_path5.default.join(cwd, path7);
1612
+ };
1613
+ var shouldExpandGlobstarDirectory = (pattern) => {
1614
+ const match = pattern?.match(/\*\*\/([^/]+)$/);
1615
+ if (!match) {
1616
+ return false;
1617
+ }
1618
+ const dirname = match[1];
1619
+ const hasWildcards = /[*?[\]{}]/.test(dirname);
1620
+ const hasExtension = import_node_path5.default.extname(dirname) && !dirname.startsWith(".");
1621
+ return !hasWildcards && !hasExtension;
1622
+ };
1623
+ var getDirectoryGlob = ({ directoryPath, files, extensions }) => {
1624
+ const extensionGlob = extensions?.length > 0 ? `.${extensions.length > 1 ? `{${extensions.join(",")}}` : extensions[0]}` : "";
1625
+ return files ? files.map((file) => import_node_path5.default.posix.join(directoryPath, `**/${import_node_path5.default.extname(file) ? file : `${file}${extensionGlob}`}`)) : [import_node_path5.default.posix.join(directoryPath, `**${extensionGlob ? `/*${extensionGlob}` : ""}`)];
1626
+ };
1627
+ var directoryToGlob = async (directoryPaths, {
1628
+ cwd = import_node_process2.default.cwd(),
1629
+ files,
1630
+ extensions,
1631
+ fs: fsImplementation
1632
+ } = {}) => {
1633
+ const globs = await Promise.all(directoryPaths.map(async (directoryPath) => {
1634
+ const checkPattern = isNegativePattern(directoryPath) ? directoryPath.slice(1) : directoryPath;
1635
+ if (shouldExpandGlobstarDirectory(checkPattern)) {
1636
+ return getDirectoryGlob({ directoryPath, files, extensions });
1637
+ }
1638
+ const pathToCheck = normalizePathForDirectoryGlob(directoryPath, cwd);
1639
+ return await isDirectory(pathToCheck, fsImplementation) ? getDirectoryGlob({ directoryPath, files, extensions }) : directoryPath;
1640
+ }));
1641
+ return globs.flat();
1642
+ };
1643
+ var directoryToGlobSync = (directoryPaths, {
1644
+ cwd = import_node_process2.default.cwd(),
1645
+ files,
1646
+ extensions,
1647
+ fs: fsImplementation
1648
+ } = {}) => directoryPaths.flatMap((directoryPath) => {
1649
+ const checkPattern = isNegativePattern(directoryPath) ? directoryPath.slice(1) : directoryPath;
1650
+ if (shouldExpandGlobstarDirectory(checkPattern)) {
1651
+ return getDirectoryGlob({ directoryPath, files, extensions });
1652
+ }
1653
+ const pathToCheck = normalizePathForDirectoryGlob(directoryPath, cwd);
1654
+ return isDirectorySync(pathToCheck, fsImplementation) ? getDirectoryGlob({ directoryPath, files, extensions }) : directoryPath;
1655
+ });
1656
+ var toPatternsArray = (patterns) => {
1657
+ patterns = [...new Set([patterns].flat())];
1658
+ assertPatternsInput(patterns);
1659
+ return patterns;
1660
+ };
1661
+ var checkCwdOption = (cwd, fsImplementation = import_node_fs3.default) => {
1662
+ if (!cwd || !fsImplementation.statSync) {
1663
+ return;
1664
+ }
1665
+ let stats;
1666
+ try {
1667
+ stats = fsImplementation.statSync(cwd);
1668
+ } catch {
1669
+ return;
1670
+ }
1671
+ if (!stats.isDirectory()) {
1672
+ throw new Error(`The \`cwd\` option must be a path to a directory, got: ${cwd}`);
1673
+ }
1674
+ };
1675
+ var normalizeOptions2 = (options = {}) => {
1676
+ const ignore = options.ignore ? Array.isArray(options.ignore) ? options.ignore : [options.ignore] : [];
1677
+ options = {
1678
+ ...options,
1679
+ ignore,
1680
+ expandDirectories: options.expandDirectories ?? true,
1681
+ cwd: toPath(options.cwd)
1682
+ };
1683
+ checkCwdOption(options.cwd, options.fs);
1684
+ return options;
1685
+ };
1686
+ var normalizeArguments = (function_) => async (patterns, options) => function_(toPatternsArray(patterns), normalizeOptions2(options));
1687
+ var normalizeArgumentsSync = (function_) => (patterns, options) => function_(toPatternsArray(patterns), normalizeOptions2(options));
1688
+ var getIgnoreFilesPatterns = (options) => {
1689
+ const { ignoreFiles, gitignore } = options;
1690
+ const patterns = ignoreFiles ? toPatternsArray(ignoreFiles) : [];
1691
+ if (gitignore) {
1692
+ patterns.push(GITIGNORE_FILES_PATTERN);
1693
+ }
1694
+ return patterns;
1695
+ };
1696
+ var isPathIgnored = (matcher, globalMatcher, path7) => {
1697
+ const globalResult = globalMatcher ? globalMatcher(path7) : void 0;
1698
+ const result = matcher ? matcher(path7) : void 0;
1699
+ if (result?.unignored) {
1700
+ return false;
1701
+ }
1702
+ return Boolean(result?.ignored || globalResult?.ignored);
1703
+ };
1704
+ var hasIgnoredAncestorDirectory = (matcher, globalMatcher, file) => {
1705
+ let currentPath = file;
1706
+ while (true) {
1707
+ const parentDirectory = import_node_path5.default.dirname(currentPath);
1708
+ if (parentDirectory === currentPath) {
1709
+ return false;
1710
+ }
1711
+ if (isPathIgnored(matcher, globalMatcher, `${parentDirectory}${import_node_path5.default.sep}`)) {
1712
+ return true;
1713
+ }
1714
+ currentPath = parentDirectory;
1715
+ }
1716
+ };
1717
+ var combinePredicate = (matcher, globalMatcher) => {
1718
+ if (!matcher && !globalMatcher) {
1719
+ return false;
1720
+ }
1721
+ return (file) => {
1722
+ const result = matcher ? matcher(file) : void 0;
1723
+ if (result?.unignored) {
1724
+ const globalResult = globalMatcher ? globalMatcher(file) : void 0;
1725
+ return globalResult?.ignored && hasIgnoredAncestorDirectory(matcher, globalMatcher, file);
1726
+ }
1727
+ return isPathIgnored(matcher, globalMatcher, file);
1728
+ };
1729
+ };
1730
+ var buildIgnoreFilterResult = (options, cwd, { patterns, matcher, usingGitRoot }, globalMatcher, createFilter) => {
1731
+ const finalPredicate = combinePredicate(matcher, globalMatcher);
1732
+ const patternsForFastGlob = convertPatternsForFastGlob(patterns, usingGitRoot, normalizeDirectoryPatternForFastGlob);
1733
+ return {
1734
+ options: {
1735
+ ...options,
1736
+ ignore: [...options.ignore, ...patternsForFastGlob]
1737
+ },
1738
+ filter: createFilter(finalPredicate, cwd, options.fs)
1739
+ };
1740
+ };
1741
+ var applyIgnoreFilesAndGetFilter = async (options) => {
1742
+ const cwd = options.cwd ?? import_node_process2.default.cwd();
1743
+ const ignoreFilesPatterns = getIgnoreFilesPatterns(options);
1744
+ const globalIgnoreFile = options.globalGitignore ? await getGlobalGitignoreFileAsync(options) : void 0;
1745
+ if (ignoreFilesPatterns.length === 0 && !globalIgnoreFile) {
1746
+ return {
1747
+ options,
1748
+ filter: createFilterFunctionAsync(false, cwd, options.fs)
1749
+ };
1750
+ }
1751
+ const includeParentIgnoreFiles = options.gitignore === true;
1752
+ const ignoreResult = ignoreFilesPatterns.length > 0 ? await getIgnorePatternsAndPredicate(ignoreFilesPatterns, options, includeParentIgnoreFiles) : { patterns: [], matcher: false, usingGitRoot: false };
1753
+ const globalGitRoot = globalIgnoreFile ? await findGitRoot(cwd, options.fs) : void 0;
1754
+ const globalMatcher = globalIgnoreFile ? buildGlobalMatcher(globalIgnoreFile, cwd, globalGitRoot ?? cwd) : void 0;
1755
+ return buildIgnoreFilterResult(options, cwd, ignoreResult, globalMatcher, createFilterFunctionAsync);
1756
+ };
1757
+ var applyIgnoreFilesAndGetFilterSync = (options) => {
1758
+ const cwd = options.cwd ?? import_node_process2.default.cwd();
1759
+ const ignoreFilesPatterns = getIgnoreFilesPatterns(options);
1760
+ const globalIgnoreFile = options.globalGitignore ? getGlobalGitignoreFile(options) : void 0;
1761
+ if (ignoreFilesPatterns.length === 0 && !globalIgnoreFile) {
1762
+ return {
1763
+ options,
1764
+ filter: createFilterFunction(false, cwd, options.fs)
1765
+ };
1766
+ }
1767
+ const includeParentIgnoreFiles = options.gitignore === true;
1768
+ const ignoreResult = ignoreFilesPatterns.length > 0 ? getIgnorePatternsAndPredicateSync(ignoreFilesPatterns, options, includeParentIgnoreFiles) : { patterns: [], matcher: false, usingGitRoot: false };
1769
+ const globalGitRoot = globalIgnoreFile ? findGitRootSync(cwd, options.fs) : void 0;
1770
+ const globalMatcher = globalIgnoreFile ? buildGlobalMatcher(globalIgnoreFile, cwd, globalGitRoot ?? cwd) : void 0;
1771
+ return buildIgnoreFilterResult(options, cwd, ignoreResult, globalMatcher, createFilterFunction);
1772
+ };
1773
+ var assertGlobalGitignoreSyncSupport = (options) => {
1774
+ if (options.globalGitignore && options.fs && !options.fs.statSync) {
1775
+ throw new Error("The `globalGitignore` option in `globbySync()` requires `fs.statSync` when a custom `fs` is provided.");
1776
+ }
1777
+ };
1778
+ var globalGitignoreAsyncStatErrorMessage = "The `globalGitignore` option in `globby()` and `globbyStream()` requires `fs.promises.stat` or `fs.stat` when a custom `fs` is provided.";
1779
+ var assertGlobalGitignoreAsyncSupport = (options) => {
1780
+ if (!options.globalGitignore || !options.fs) {
1781
+ return;
1782
+ }
1783
+ if (!options.fs.promises?.stat && !options.fs.stat) {
1784
+ throw new Error(globalGitignoreAsyncStatErrorMessage);
1785
+ }
1786
+ };
1787
+ var createPathResolver = (cwd) => {
1788
+ const basePath = cwd || import_node_process2.default.cwd();
1789
+ const pathCache = /* @__PURE__ */ new Map();
1790
+ return (pathKey) => {
1791
+ let absolutePath = pathCache.get(pathKey);
1792
+ if (absolutePath === void 0) {
1793
+ if (pathCache.size > 1e4) {
1794
+ pathCache.clear();
1795
+ }
1796
+ absolutePath = import_node_path5.default.isAbsolute(pathKey) ? pathKey : import_node_path5.default.resolve(basePath, pathKey);
1797
+ pathCache.set(pathKey, absolutePath);
1798
+ }
1799
+ return absolutePath;
1800
+ };
1801
+ };
1802
+ var createAsyncDirectoryCheck = (fsMethod) => {
1803
+ const directoryCache = /* @__PURE__ */ new Map();
1804
+ return async (absolutePath) => {
1805
+ let isDirectory2 = directoryCache.get(absolutePath);
1806
+ if (isDirectory2 !== void 0) {
1807
+ return isDirectory2;
1808
+ }
1809
+ try {
1810
+ const stats = await fsMethod?.(absolutePath);
1811
+ isDirectory2 = Boolean(stats?.isDirectory());
1812
+ } catch {
1813
+ isDirectory2 = false;
1814
+ }
1815
+ if (directoryCache.size > 1e4) {
1816
+ directoryCache.clear();
1817
+ }
1818
+ directoryCache.set(absolutePath, isDirectory2);
1819
+ return isDirectory2;
1820
+ };
1821
+ };
1822
+ var createDirectoryCheck = (fsMethod) => {
1823
+ const directoryCache = /* @__PURE__ */ new Map();
1824
+ return (absolutePath) => {
1825
+ let isDirectory2 = directoryCache.get(absolutePath);
1826
+ if (isDirectory2 !== void 0) {
1827
+ return isDirectory2;
1828
+ }
1829
+ try {
1830
+ isDirectory2 = Boolean(fsMethod?.(absolutePath)?.isDirectory());
1831
+ } catch {
1832
+ isDirectory2 = false;
1833
+ }
1834
+ if (directoryCache.size > 1e4) {
1835
+ directoryCache.clear();
1836
+ }
1837
+ directoryCache.set(absolutePath, isDirectory2);
1838
+ return isDirectory2;
1839
+ };
1840
+ };
1841
+ var createFilterFunctionAsync = (isIgnored, cwd, fsImplementation) => {
1842
+ const resolveAbsolutePath = createPathResolver(cwd);
1843
+ const isDirectoryEntry = createAsyncDirectoryCheck(getStatMethod(fsImplementation));
1844
+ return async (fastGlobResult) => {
1845
+ if (!isIgnored) {
1846
+ return true;
1847
+ }
1848
+ const absolutePath = resolveAbsolutePath(import_node_path5.default.normalize(fastGlobResult.path ?? fastGlobResult));
1849
+ if (isIgnored(absolutePath)) {
1850
+ return false;
1851
+ }
1852
+ return !(await isDirectoryEntry(absolutePath) && isIgnored(`${absolutePath}${import_node_path5.default.sep}`));
1853
+ };
1854
+ };
1855
+ var createFilterFunction = (isIgnored, cwd, fsImplementation) => {
1856
+ const seen = /* @__PURE__ */ new Set();
1857
+ const resolveAbsolutePath = createPathResolver(cwd);
1858
+ const isDirectoryEntry = createDirectoryCheck(getStatSyncMethod2(fsImplementation));
1859
+ return (fastGlobResult) => {
1860
+ const pathKey = import_node_path5.default.normalize(fastGlobResult.path ?? fastGlobResult);
1861
+ if (seen.has(pathKey)) {
1862
+ return false;
1863
+ }
1864
+ if (isIgnored) {
1865
+ const absolutePath = resolveAbsolutePath(pathKey);
1866
+ if (isIgnored(absolutePath)) {
1867
+ return false;
1868
+ }
1869
+ if (isDirectoryEntry(absolutePath) && isIgnored(`${absolutePath}${import_node_path5.default.sep}`)) {
1870
+ return false;
1871
+ }
1872
+ }
1873
+ seen.add(pathKey);
1874
+ return true;
1875
+ };
1876
+ };
1877
+ var unionFastGlobResults = (results, filter) => results.flat().filter((fastGlobResult) => filter(fastGlobResult));
1878
+ var unionFastGlobResultsAsync = async (results, filter) => {
1879
+ results = results.flat();
1880
+ const matches = await Promise.all(results.map((fastGlobResult) => filter(fastGlobResult)));
1881
+ const seen = /* @__PURE__ */ new Set();
1882
+ return results.filter((fastGlobResult, index) => {
1883
+ if (!matches[index]) {
1884
+ return false;
1885
+ }
1886
+ const pathKey = import_node_path5.default.normalize(fastGlobResult.path ?? fastGlobResult);
1887
+ if (seen.has(pathKey)) {
1888
+ return false;
1889
+ }
1890
+ seen.add(pathKey);
1891
+ return true;
1892
+ });
1893
+ };
1894
+ var convertNegativePatterns = (patterns, options) => {
1895
+ if (patterns.length > 0 && patterns.every((pattern) => isNegativePattern(pattern))) {
1896
+ if (options.expandNegationOnlyPatterns === false) {
1897
+ return [];
1898
+ }
1899
+ patterns = ["**/*", ...patterns];
1900
+ }
1901
+ const positiveAbsolutePathPrefixes = [];
1902
+ let hasRelativePositivePattern = false;
1903
+ const normalizedPatterns = [];
1904
+ for (const pattern of patterns) {
1905
+ if (isNegativePattern(pattern)) {
1906
+ normalizedPatterns.push(`!${normalizeNegativePattern(pattern.slice(1), positiveAbsolutePathPrefixes, hasRelativePositivePattern)}`);
1907
+ continue;
1908
+ }
1909
+ normalizedPatterns.push(pattern);
1910
+ const staticAbsolutePathPrefix = getStaticAbsolutePathPrefix(pattern);
1911
+ if (staticAbsolutePathPrefix === void 0) {
1912
+ hasRelativePositivePattern = true;
1913
+ continue;
1914
+ }
1915
+ positiveAbsolutePathPrefixes.push(staticAbsolutePathPrefix);
1916
+ }
1917
+ patterns = normalizedPatterns;
1918
+ const tasks = [];
1919
+ while (patterns.length > 0) {
1920
+ const index = patterns.findIndex((pattern) => isNegativePattern(pattern));
1921
+ if (index === -1) {
1922
+ tasks.push({ patterns, options });
1923
+ break;
1924
+ }
1925
+ const ignorePattern = patterns[index].slice(1);
1926
+ for (const task of tasks) {
1927
+ task.options.ignore.push(ignorePattern);
1928
+ }
1929
+ if (index !== 0) {
1930
+ tasks.push({
1931
+ patterns: patterns.slice(0, index),
1932
+ options: {
1933
+ ...options,
1934
+ ignore: [
1935
+ ...options.ignore,
1936
+ ignorePattern
1937
+ ]
1938
+ }
1939
+ });
1940
+ }
1941
+ patterns = patterns.slice(index + 1);
1942
+ }
1943
+ return tasks;
1944
+ };
1945
+ var applyParentDirectoryIgnoreAdjustments = (tasks) => tasks.map((task) => ({
1946
+ patterns: task.patterns,
1947
+ options: {
1948
+ ...task.options,
1949
+ ignore: adjustIgnorePatternsForParentDirectories(task.patterns, task.options.ignore)
1950
+ }
1951
+ }));
1952
+ var normalizeExpandDirectoriesOption = (options, cwd) => ({
1953
+ ...cwd ? { cwd } : {},
1954
+ ...Array.isArray(options) ? { files: options } : options
1955
+ });
1956
+ var generateTasks = async (patterns, options) => {
1957
+ const globTasks = convertNegativePatterns(patterns, options);
1958
+ const { cwd, expandDirectories, fs: fsImplementation } = options;
1959
+ if (!expandDirectories) {
1960
+ return applyParentDirectoryIgnoreAdjustments(globTasks);
1961
+ }
1962
+ const directoryToGlobOptions = {
1963
+ ...normalizeExpandDirectoriesOption(expandDirectories, cwd),
1964
+ fs: fsImplementation
1965
+ };
1966
+ return Promise.all(globTasks.map(async (task) => {
1967
+ let { patterns: patterns2, options: options2 } = task;
1968
+ [
1969
+ patterns2,
1970
+ options2.ignore
1971
+ ] = await Promise.all([
1972
+ directoryToGlob(patterns2, directoryToGlobOptions),
1973
+ directoryToGlob(options2.ignore, { cwd, fs: fsImplementation })
1974
+ ]);
1975
+ options2.ignore = adjustIgnorePatternsForParentDirectories(patterns2, options2.ignore);
1976
+ return { patterns: patterns2, options: options2 };
1977
+ }));
1978
+ };
1979
+ var generateTasksSync = (patterns, options) => {
1980
+ const globTasks = convertNegativePatterns(patterns, options);
1981
+ const { cwd, expandDirectories, fs: fsImplementation } = options;
1982
+ if (!expandDirectories) {
1983
+ return applyParentDirectoryIgnoreAdjustments(globTasks);
1984
+ }
1985
+ const directoryToGlobSyncOptions = {
1986
+ ...normalizeExpandDirectoriesOption(expandDirectories, cwd),
1987
+ fs: fsImplementation
1988
+ };
1989
+ return globTasks.map((task) => {
1990
+ let { patterns: patterns2, options: options2 } = task;
1991
+ patterns2 = directoryToGlobSync(patterns2, directoryToGlobSyncOptions);
1992
+ options2.ignore = directoryToGlobSync(options2.ignore, { cwd, fs: fsImplementation });
1993
+ options2.ignore = adjustIgnorePatternsForParentDirectories(patterns2, options2.ignore);
1994
+ return { patterns: patterns2, options: options2 };
1995
+ });
1996
+ };
1997
+ var globby = normalizeArguments(async (patterns, options) => {
1998
+ assertGlobalGitignoreAsyncSupport(options);
1999
+ const { options: modifiedOptions, filter } = await applyIgnoreFilesAndGetFilter(options);
2000
+ const tasks = await generateTasks(patterns, modifiedOptions);
2001
+ const results = await Promise.all(tasks.map((task) => (0, import_fast_glob3.default)(task.patterns, task.options)));
2002
+ return unionFastGlobResultsAsync(results, filter);
2003
+ });
2004
+ var globbySync = normalizeArgumentsSync((patterns, options) => {
2005
+ assertGlobalGitignoreSyncSupport(options);
2006
+ const { options: modifiedOptions, filter } = applyIgnoreFilesAndGetFilterSync(options);
2007
+ const tasks = generateTasksSync(patterns, modifiedOptions);
2008
+ const results = tasks.map((task) => import_fast_glob3.default.sync(task.patterns, task.options));
2009
+ return unionFastGlobResults(results, filter);
2010
+ });
2011
+ var globbyStream = normalizeArgumentsSync((patterns, options) => {
2012
+ assertGlobalGitignoreAsyncSupport(options);
2013
+ const seen = /* @__PURE__ */ new Set();
2014
+ const stream = import_node_stream2.Readable.from((async function* () {
2015
+ const { options: modifiedOptions, filter } = await applyIgnoreFilesAndGetFilter(options);
2016
+ const tasks = await generateTasks(patterns, modifiedOptions);
2017
+ if (tasks.length === 0) {
2018
+ return;
2019
+ }
2020
+ const streams = tasks.map((task) => import_fast_glob3.default.stream(task.patterns, task.options));
2021
+ for await (const fastGlobResult of mergeStreams(streams)) {
2022
+ const pathKey = import_node_path5.default.normalize(fastGlobResult.path ?? fastGlobResult);
2023
+ if (!seen.has(pathKey) && await filter(fastGlobResult)) {
2024
+ seen.add(pathKey);
2025
+ yield fastGlobResult;
2026
+ }
2027
+ }
2028
+ })());
2029
+ return stream;
2030
+ });
2031
+ var isDynamicPattern = normalizeArgumentsSync((patterns, options) => patterns.some((pattern) => import_fast_glob3.default.isDynamicPattern(pattern, options)));
2032
+ var generateGlobTasks = normalizeArguments(generateTasks);
2033
+ var generateGlobTasksSync = normalizeArgumentsSync(generateTasksSync);
2034
+ var { convertPathToPattern } = import_fast_glob3.default;
2035
+
2036
+ // src/cli/index.ts
2037
+ var import_node_fs5 = __toESM(require("fs"), 1);
2038
+ var import_node_path7 = __toESM(require("path"), 1);
2039
+
2040
+ // src/cli/io-to-ts.ts
2041
+ var structs = /* @__PURE__ */ new Map();
2042
+ function solidityPrimitiveToTs(type) {
2043
+ if (["string", "address"].includes(type) || type.startsWith("byte")) return "string";
2044
+ if (type.startsWith("uint")) return "number";
2045
+ if (type === "bool") return "boolean";
2046
+ throw new Error(`[abiTypeToTsType] Not handle type: ${type}`);
2047
+ }
2048
+ function normalizeStructName(internalType) {
2049
+ if (!internalType) {
2050
+ return "UnknownStruct";
2051
+ }
2052
+ const rawName = internalType.split(" ")[1] ?? "UnknownStruct";
2053
+ return `BC${rawName.replace("[]", "").replaceAll(".", "")}`;
2054
+ }
2055
+ function buildTsObjectType(ios, ioType) {
2056
+ if (!ios?.length) {
2057
+ return ioType === "in" ? "null" : "void";
2058
+ }
2059
+ if (ios.length === 1 && ios[0].name === "" && ioType === "out") {
2060
+ return abiTypeToTsType(ios[0], ioType);
2061
+ }
2062
+ const fields = ios.map((item) => `${item.name || '""'}: ${abiTypeToTsType(item, ioType)}`).join("; ");
2063
+ return `{ ${fields} }`;
2064
+ }
2065
+ function getOrCreateStructType(item, ioType) {
2066
+ const structName = normalizeStructName(item.internalType);
2067
+ if (!structs.has(structName)) {
2068
+ const body = buildTsObjectType(item.components ?? [], ioType);
2069
+ structs.set(structName, `type ${structName} = ${body}`);
2070
+ }
2071
+ return structName;
2072
+ }
2073
+ function abiTypeToTsType(item, ioType) {
2074
+ const isArray = item.type.endsWith("[]");
2075
+ if (item.type.includes("tuple")) {
2076
+ const structName = getOrCreateStructType(item, ioType);
2077
+ return isArray ? `${structName}[]` : structName;
2078
+ }
2079
+ const baseType = isArray ? item.type.slice(0, -2) : item.type;
2080
+ const tsType = solidityPrimitiveToTs(baseType);
2081
+ return isArray ? `${tsType}[]` : tsType;
2082
+ }
2083
+ function abiToTs(ios, ioType) {
2084
+ return buildTsObjectType(ios, ioType);
2085
+ }
2086
+ function getStructString() {
2087
+ return [...structs.values()].join("\n");
2088
+ }
2089
+
2090
+ // src/cli/utils.ts
2091
+ var import_node_path6 = __toESM(require("path"), 1);
2092
+ var import_node_fs4 = __toESM(require("fs"), 1);
2093
+ var import_prettier = __toESM(require("prettier"), 1);
2094
+ var import_readline = __toESM(require("readline"), 1);
2095
+ function ask(label) {
2096
+ const rl = import_readline.default.createInterface({
2097
+ input: process.stdin,
2098
+ output: process.stdout
2099
+ });
2100
+ return new Promise((resolve) => {
2101
+ rl.question(label, (answer) => {
2102
+ rl.close();
2103
+ const rs = answer.trim();
2104
+ resolve(rs);
2105
+ });
2106
+ });
2107
+ }
2108
+ function capitalize(input) {
2109
+ return input.charAt(0).toUpperCase() + input.slice(1);
2110
+ }
2111
+ function createMethodsName(name) {
2112
+ return `${capitalize(name)}Mehods`;
2113
+ }
2114
+ function createEventsName(name) {
2115
+ return `${capitalize(name)}Events`;
2116
+ }
2117
+ function normalizePath(input) {
2118
+ return import_node_path6.default.basename(input, ".abi.json").split(/[-.]/g).join("");
2119
+ }
2120
+ async function writePrettyFile(fileName, content, outDir) {
2121
+ import_node_fs4.default.mkdirSync(outDir, {
2122
+ recursive: true
2123
+ });
2124
+ const outFile = import_node_path6.default.join(outDir, fileName);
2125
+ const config = await import_prettier.default.resolveConfig(outFile);
2126
+ const formatted = await import_prettier.default.format(content, {
2127
+ ...config,
2128
+ filepath: outFile
2129
+ });
2130
+ import_node_fs4.default.writeFileSync(outFile, formatted, "utf-8");
2131
+ }
2132
+ var contractsTemplate = ` type HandlerDefinition<Input = unknown, Output = unknown> = [Input, Output];
2133
+
2134
+ type RegistrySchema = Record<string, Record<string, HandlerDefinition<unknown, unknown>>>;
2135
+
2136
+ type RegistryHandlers<TSchema extends RegistrySchema, TOptions = unknown> = {
2137
+ [TGroup in keyof TSchema]: {
2138
+ [TKey in keyof TSchema[TGroup]]: (
2139
+ input: TSchema[TGroup][TKey][0],
2140
+ options?: TOptions,
2141
+ ) => Promise<TSchema[TGroup][TKey][1]>;
2142
+ };
2143
+ };
2144
+ type ContractOptions = {
2145
+ from?: string
2146
+ to?: string
2147
+ gas?: string | number
2148
+ }
2149
+ `;
2150
+
2151
+ // src/cli/index.ts
2152
+ function createGlobalDeclaration(content) {
2153
+ const finalContent = Array.isArray(content) ? content.join("\n") : content;
2154
+ return ` export {}
2155
+ declare global {
2156
+ ${finalContent}
2157
+ }`;
2158
+ }
2159
+ function defineMethods(abiName, items) {
2160
+ const content = items.map((item) => {
2161
+ const inputs = abiToTs(item.inputs, "in");
2162
+ const outputs = abiToTs(item.outputs, "out");
2163
+ return `
2164
+ ${item.name}: [${inputs},${outputs}]`;
2165
+ }).join("");
2166
+ return createGlobalDeclaration(`type ${createMethodsName(abiName)} = {${content}}`);
2167
+ }
2168
+ function defineEvents(abiName, items) {
2169
+ const content = items.map((item) => {
2170
+ return `
2171
+ ${item.name}: ${abiToTs(item.inputs, "out")}`;
2172
+ }).join("");
2173
+ return createGlobalDeclaration(`type ${createEventsName(abiName)} = {${content}}`);
2174
+ }
2175
+ function defineAllContracts(abis) {
2176
+ const content = abis.map(([name]) => {
2177
+ return `
2178
+ ${name}: ${createMethodsName(name)}`;
2179
+ });
2180
+ const allMehodsString = `type ContractMethods = RegistryHandlers<{${content}}, ContractOptions>`;
2181
+ return createGlobalDeclaration(contractsTemplate + allMehodsString);
2182
+ }
2183
+ async function generateBlockchainTypes() {
2184
+ const rootPath = process.cwd();
2185
+ const _input = await ask("type relative path: ");
2186
+ const input = _input ? _input + "/" : "";
2187
+ const outDir = import_node_path7.default.resolve(rootPath, `src/${input}@bc-types`);
2188
+ const filePaths = await globby(`src/${input}abis/*.abi.json`, {
2189
+ cwd: rootPath,
2190
+ absolute: true
2191
+ });
2192
+ const abis = filePaths.map((filePath) => [
2193
+ normalizePath(filePath),
2194
+ JSON.parse(import_node_fs5.default.readFileSync(filePath, "utf-8"))
2195
+ ]);
2196
+ abis.forEach(async ([name, abiArray]) => {
2197
+ const dir = import_node_path7.default.resolve(outDir, name);
2198
+ const methods = abiArray.filter((i) => i.type === "function");
2199
+ const events = abiArray.filter((i) => i.type === "event");
2200
+ writePrettyFile(`${name}.methods.d.ts`, defineMethods(name, methods), dir);
2201
+ writePrettyFile(`${name}.events.d.ts`, defineEvents(name, events), dir);
2202
+ });
2203
+ const structsString = createGlobalDeclaration(getStructString());
2204
+ writePrettyFile(`structs.d.ts`, structsString, outDir);
2205
+ writePrettyFile(`contracts.d.ts`, defineAllContracts(abis), outDir);
2206
+ }
2207
+ // Annotate the CommonJS export names for ESM import in node:
2208
+ 0 && (module.exports = {
2209
+ generateBlockchainTypes
2210
+ });