The best way to control Claude Code, Codex and more from any computer or phone

main
ts 828 lines 23.7 KB
Raw
1 // oxlint-disable unicorn/prefer-string-starts-ends-with no-control-regex
2
3 // Alchemy modifications are licensed under Apache-2.0.
4 // This file includes third-party code; see /THIRD_PARTY_LICENSES.md.
5 //
6 // TypeScript port of `ignore` (https://github.com/kaelzhang/node-ignore) v7.0.5.
7 // Copyright (c) 2013 Kael Zhang <i@kael.me>, contributors. MIT License.
8
9 function makeArray<T>(subject: T | readonly T[]): T[] {
10 return Array.isArray(subject) ? [...subject] : [subject as T];
11 }
12
13 const UNDEFINED = undefined;
14 const EMPTY = "";
15 const SPACE = " ";
16 const ESCAPE = "\\";
17 const REGEX_TEST_BLANK_LINE = /^\s+$/;
18 const REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\]|^)\\$/;
19 const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
20 const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
21 const REGEX_SPLITALL_CRLF = /\r?\n/g;
22
23 // Invalid:
24 // - /foo,
25 // - ./foo,
26 // - ../foo,
27 // - .
28 // - ..
29 // Valid:
30 // - .foo
31 const REGEX_TEST_INVALID_PATH = /^\.{0,2}\/|^\.{1,2}$/;
32
33 const REGEX_TEST_TRAILING_SLASH = /\/$/;
34
35 const SLASH = "/";
36
37 // Do not use ternary expression here, since "istanbul ignore next" is buggy
38 let TMP_KEY_IGNORE: string | symbol = "node-ignore";
39 /* istanbul ignore else */
40 if (typeof Symbol !== "undefined") {
41 TMP_KEY_IGNORE = Symbol.for("node-ignore");
42 }
43 const KEY_IGNORE = TMP_KEY_IGNORE;
44
45 const define = <T>(object: object, key: PropertyKey, value: T): T => {
46 Object.defineProperty(object, key, { value });
47 return value;
48 };
49
50 const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
51
52 const RETURN_FALSE = () => false;
53
54 // Sanitize the range of a regular expression
55 // The cases are complicated, see test cases for details
56 const sanitizeRange = (range: string): string =>
57 range.replace(REGEX_REGEXP_RANGE, (match, from, to) =>
58 from.charCodeAt(0) <= to.charCodeAt(0)
59 ? match
60 : // Invalid range (out of order) which is ok for gitignore rules but
61 // fatal for JavaScript regular expression, so eliminate it.
62 EMPTY,
63 );
64
65 // > An optional `!` or `^` at the start of a class negates it, so that it
66 // > matches any character not in the set. (gitignore(5), fnmatch(3))
67 // The leading `^` has already been escaped to `\^` by the metacharacter
68 // escaper, so we strip the literal `!` or escaped `^` and emit a single
69 // regex `^` which is the JavaScript negation token.
70 const negateRange = (range: string): string =>
71 range.startsWith("!") || range.startsWith("\\^")
72 ? `^${range.slice(range[0] === "!" ? 1 : 2)}`
73 : range;
74
75 // See fixtures #59
76 const cleanRangeBackSlash = (slashes: string): string => {
77 const { length } = slashes;
78 return slashes.slice(0, length - (length % 2));
79 };
80
81 // > If the pattern ends with a slash,
82 // > it is removed for the purpose of the following description,
83 // > but it would only find a match with a directory.
84 // > In other words, foo/ will match a directory foo and paths underneath it,
85 // > but will not match a regular file or a symbolic link foo
86 // > (this is consistent with the way how pathspec works in general in Git).
87 // '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'
88 // -> ignore-rules will not deal with it, because it costs extra `fs.stat` call
89 // you could use option `mark: true` with `glob`
90
91 // '`foo/`' should not continue with the '`..`'
92 type Replacer = (this: string, ...args: any[]) => string;
93
94 const REPLACERS: Array<readonly [RegExp, Replacer]> = [
95 [
96 // Remove BOM
97 // TODO:
98 // Other similar zero-width characters?
99 /^\uFEFF/,
100 () => EMPTY,
101 ],
102
103 // > Trailing spaces are ignored unless they are quoted with backslash ("\")
104 [
105 // (a\ ) -> (a )
106 // (a ) -> (a)
107 // (a ) -> (a)
108 // (a \ ) -> (a )
109 /((?:\\\\)*?)(\\?\s+)$/,
110 (_, m1, m2) => m1 + (m2.indexOf("\\") === 0 ? SPACE : EMPTY),
111 ],
112
113 // Replace (\ ) with ' '
114 // (\ ) -> ' '
115 // (\\ ) -> '\\ '
116 // (\\\ ) -> '\\ '
117 [
118 /(\\+?)\s/g,
119 (_, m1) => {
120 const { length } = m1;
121 return m1.slice(0, length - (length % 2)) + SPACE;
122 },
123 ],
124
125 // Escape metacharacters
126 // which is written down by users but means special for regular expressions.
127
128 // > There are 12 characters with special meanings:
129 // > - the backslash \,
130 // > - the caret ^,
131 // > - the dollar sign $,
132 // > - the period or dot .,
133 // > - the vertical bar or pipe symbol |,
134 // > - the question mark ?,
135 // > - the asterisk or star *,
136 // > - the plus sign +,
137 // > - the opening parenthesis (,
138 // > - the closing parenthesis ),
139 // > - and the opening square bracket [,
140 // > - the opening curly brace {,
141 // > These special characters are often called "metacharacters".
142 [/[\\$.|*+(){^]/g, (match) => `\\${match}`],
143
144 [
145 // > a question mark (?) matches a single character
146 /(?!\\)\?/g,
147 () => "[^/]",
148 ],
149
150 // leading slash
151 [
152 // > A leading slash matches the beginning of the pathname.
153 // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
154 // A leading slash matches the beginning of the pathname
155 /^\//,
156 () => "^",
157 ],
158
159 // replace special metacharacter slash after the leading slash
160 [/\//g, () => "\\/"],
161
162 [
163 // > A leading "**" followed by a slash means match in all directories.
164 // > For example, "**/foo" matches file or directory "foo" anywhere,
165 // > the same as pattern "foo".
166 // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
167 // > under directory "foo".
168 // Notice that the '*'s have been replaced as '\\*'
169 /^\^*(?:\\\*\\\*\\\/)+/,
170
171 // '**/foo' <-> 'foo'
172 () => "^(?:.*\\/)?",
173 ],
174
175 // starting
176 [
177 // there will be no leading '/'
178 // (which has been replaced by section "leading slash")
179 // If starts with '**', adding a '^' to the regular expression also works
180 /^(?=[^^])/,
181 function startingReplacer(this: string) {
182 // If has a slash `/` at the beginning or middle
183 return !/\/(?!$)/.test(this)
184 ? // > Prior to 2.22.1
185 // > If the pattern does not contain a slash /,
186 // > Git treats it as a shell glob pattern
187 // Actually, if there is only a trailing slash,
188 // git also treats it as a shell glob pattern
189
190 // After 2.22.1 (compatible but clearer)
191 // > If there is a separator at the beginning or middle (or both)
192 // > of the pattern, then the pattern is relative to the directory
193 // > level of the particular .gitignore file itself.
194 // > Otherwise the pattern may also match at any level below
195 // > the .gitignore level.
196 "(?:^|\\/)"
197 : // > Otherwise, Git treats the pattern as a shell glob suitable for
198 // > consumption by fnmatch(3)
199 "^";
200 },
201 ],
202
203 // two globstars
204 [
205 // Use lookahead assertions so that we could match more than one `'/**'`
206 /\\\/\\\*\\\*(?=\\\/|$)/g,
207
208 // Zero, one or several directories
209 // should not use '*', or it will be replaced by the next replacer
210
211 // Check if it is not the last `'/**'`
212 (_, index, str) =>
213 index + 6 < str.length
214 ? // case: /**/
215 // > A slash followed by two consecutive asterisks then a slash matches
216 // > zero or more directories.
217 // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.
218 // '/**/'
219 "(?:\\/[^\\/]+)*"
220 : // case: /**
221 // > A trailing `"/**"` matches everything inside.
222
223 // #21: everything inside but it should not include the current folder
224 "\\/.+",
225 ],
226
227 // normal intermediate wildcards
228 [
229 // Never replace escaped '*'
230 // ignore rule '\*' will match the path '*'
231
232 // 'abc.*/' -> go
233 // 'abc.*' -> skip this rule,
234 // coz trailing single wildcard will be handed by [trailing wildcard]
235 /(^|[^\\]+)(\\\*)+(?=.+)/g,
236
237 // '*.js' matches '.js'
238 // '*.js' doesn't match 'abc'
239 (_, p1, p2) => {
240 // 1.
241 // > An asterisk "*" matches anything except a slash.
242 // 2.
243 // > Other consecutive asterisks are considered regular asterisks
244 // > and will match according to the previous rules.
245 const unescaped = p2.replace(/\\\*/g, "[^\\/]*");
246 return p1 + unescaped;
247 },
248 ],
249
250 [
251 // unescape, revert step 3 except for back slash
252 // For example, if a user escape a '\\*',
253 // after step 3, the result will be '\\\\\\*'
254 /\\\\\\(?=[$.|*+(){^])/g,
255 () => ESCAPE,
256 ],
257
258 [
259 // '\\\\' -> '\\'
260 /\\\\/g,
261 () => ESCAPE,
262 ],
263
264 [
265 // > The range notation, e.g. [a-zA-Z],
266 // > can be used to match one of the characters in a range.
267
268 // `\` is escaped by step 3
269 /(\\)?\[([^\]/]*?)(\\*)($|\])/g,
270 (match, leadEscape, range, endEscape, close) =>
271 leadEscape === ESCAPE
272 ? // '\\[bar]' -> '\\\\[bar\\]'
273 `\\[${range}${cleanRangeBackSlash(endEscape)}${close}`
274 : close === "]"
275 ? endEscape.length % 2 === 0
276 ? // A normal case, and it is a range notation
277 // '[bar]'
278 // '[bar\\\\]'
279 `[${negateRange(sanitizeRange(range))}${endEscape}]`
280 : // Invalid range notaton
281 // '[bar\\]' -> '[bar\\\\]'
282 "[]"
283 : "[]",
284 ],
285
286 // ending
287 [
288 // 'js' will not match 'js.'
289 // 'ab' will not match 'abc'
290 /(?:[^*])$/,
291
292 // WTF!
293 // https://git-scm.com/docs/gitignore
294 // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
295 // which re-fixes #24, #38
296
297 // > If there is a separator at the end of the pattern then the pattern
298 // > will only match directories, otherwise the pattern can match both
299 // > files and directories.
300
301 // 'js*' will not match 'a.js'
302 // 'js/' will not match 'a.js'
303 // 'js' will match 'a.js' and 'a.js/'
304 (match) =>
305 /\/$/.test(match)
306 ? // foo/ will not match 'foo'
307 `${match}$`
308 : // foo matches 'foo' and 'foo/'
309 `${match}(?=$|\\/$)`,
310 ],
311 ];
312
313 const REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\/)?\\\*$/;
314 const MODE_IGNORE = "regex";
315 const MODE_CHECK_IGNORE = "checkRegex";
316
317 type MatcherMode = typeof MODE_IGNORE | typeof MODE_CHECK_IGNORE;
318
319 const TRAILING_WILD_CARD_REPLACERS: Record<MatcherMode, Replacer> = {
320 [MODE_IGNORE](_, p1: string | undefined) {
321 const prefix = p1
322 ? // '\^':
323 // '/*' does not match EMPTY
324 // '/*' does not match everything
325
326 // '\\\/':
327 // 'abc/*' does not match 'abc/'
328 `${p1}[^/]+`
329 : // 'a*' matches 'a'
330 // 'a*' matches 'aa'
331 "[^/]*";
332
333 return `${prefix}(?=$|\\/$)`;
334 },
335
336 [MODE_CHECK_IGNORE](_, p1: string | undefined) {
337 // When doing `git check-ignore`
338 const prefix = p1
339 ? // '\\\/':
340 // 'abc/*' DOES match 'abc/' !
341 `${p1}[^/]*`
342 : // 'a*' matches 'a'
343 // 'a*' matches 'aa'
344 "[^/]*";
345
346 return `${prefix}(?=$|\\/$)`;
347 },
348 };
349
350 // @param {pattern}
351 const makeRegexPrefix = (pattern: string): string =>
352 REPLACERS.reduce(
353 (prev, [matcher, replacer]) => prev.replace(matcher, replacer.bind(pattern)),
354 pattern,
355 );
356
357 const isString = (subject: unknown): subject is string => typeof subject === "string";
358
359 // > A blank line matches no files, so it can serve as a separator for readability.
360 const checkPattern = (pattern: string): boolean =>
361 Boolean(
362 pattern &&
363 !REGEX_TEST_BLANK_LINE.test(pattern) &&
364 !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern) &&
365 // > A line starting with # serves as a comment.
366 pattern.indexOf("#") !== 0,
367 );
368
369 const splitPattern = (pattern: string): string[] =>
370 pattern.split(REGEX_SPLITALL_CRLF).filter(Boolean);
371
372 class IgnoreRule {
373 readonly pattern: string;
374 readonly mark: string | undefined;
375 readonly negative: boolean;
376 readonly body!: string;
377 readonly ignoreCase!: boolean;
378 readonly regexPrefix!: string;
379 private _regex?: RegExp;
380 private _checkRegex?: RegExp;
381
382 constructor(
383 pattern: string,
384 mark: string | undefined,
385 body: string,
386 ignoreCase: boolean,
387 negative: boolean,
388 prefix: string,
389 ) {
390 this.pattern = pattern;
391 this.mark = mark;
392 this.negative = negative;
393
394 define(this, "body", body);
395 define(this, "ignoreCase", ignoreCase);
396 define(this, "regexPrefix", prefix);
397 }
398
399 get regex() {
400 const key = `_${MODE_IGNORE}` as const;
401
402 if (this[key]) {
403 return this[key];
404 }
405
406 return this._make(MODE_IGNORE, key);
407 }
408
409 get checkRegex() {
410 const key = `_${MODE_CHECK_IGNORE}` as const;
411
412 if (this[key]) {
413 return this[key];
414 }
415
416 return this._make(MODE_CHECK_IGNORE, key);
417 }
418
419 _make(mode: MatcherMode, key: "_regex" | "_checkRegex"): RegExp {
420 const str = this.regexPrefix.replace(
421 REGEX_REPLACE_TRAILING_WILDCARD,
422
423 // It does not need to bind pattern
424 TRAILING_WILD_CARD_REPLACERS[mode],
425 );
426
427 const regex = this.ignoreCase ? new RegExp(str, "i") : new RegExp(str);
428
429 return define(this, key, regex);
430 }
431 }
432
433 const createRule = ({ pattern, mark }: PatternParams, ignoreCase: boolean): IgnoreRule => {
434 let negative = false;
435 let body = pattern;
436
437 // > An optional prefix "!" which negates the pattern;
438 if (body.indexOf("!") === 0) {
439 negative = true;
440 body = body.substr(1);
441 }
442
443 body = body
444 // > Put a backslash ("\") in front of the first "!" for patterns that
445 // > begin with a literal "!", for example, `"\!important!.txt"`.
446 .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!")
447 // > Put a backslash ("\") in front of the first hash for patterns that
448 // > begin with a hash.
449 .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
450
451 const regexPrefix = makeRegexPrefix(body);
452
453 return new IgnoreRule(pattern, mark, body, ignoreCase, negative, regexPrefix);
454 };
455
456 class RuleManager {
457 private readonly _ignoreCase: boolean;
458 _rules: IgnoreRule[] = [];
459 private _added = false;
460
461 constructor(ignoreCase: boolean) {
462 this._ignoreCase = ignoreCase;
463 }
464
465 _add(pattern: string | Ignore | PatternParams): void {
466 // #32
467 const ignorePattern = pattern as Ignore & Record<PropertyKey, unknown>;
468 if (pattern && ignorePattern[KEY_IGNORE]) {
469 this._rules = this._rules.concat(ignorePattern._rules._rules);
470 this._added = true;
471 return;
472 }
473
474 if (isString(pattern)) {
475 pattern = {
476 pattern,
477 };
478 }
479
480 const patternParams = pattern as PatternParams;
481 if (checkPattern(patternParams.pattern)) {
482 const rule = createRule(patternParams, this._ignoreCase);
483 this._added = true;
484 this._rules.push(rule);
485 }
486 }
487
488 // @param {Array<string> | string | Ignore} pattern
489 add(pattern: string | Ignore | PatternParams | readonly (string | Ignore)[]): boolean {
490 this._added = false;
491
492 const patterns: readonly (string | Ignore | PatternParams)[] = isString(pattern)
493 ? splitPattern(pattern)
494 : Array.isArray(pattern)
495 ? pattern
496 : [pattern as Ignore | PatternParams];
497 patterns.forEach((p) => this._add(p));
498
499 return this._added;
500 }
501
502 // Test one single path without recursively checking parent directories
503 //
504 // - checkUnignored `boolean` whether should check if the path is unignored,
505 // setting `checkUnignored` to `false` could reduce additional
506 // path matching.
507 // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`
508
509 // @returns {TestResult} true if a file is ignored
510 test(path: string, checkUnignored: boolean, mode: MatcherMode): IgnoreTestResult {
511 let ignored = false;
512 let unignored = false;
513 let matchedRule: IgnoreRule | undefined;
514
515 this._rules.forEach((rule) => {
516 const { negative } = rule;
517
518 // | ignored : unignored
519 // -------- | ---------------------------------------
520 // negative | 0:0 | 0:1 | 1:0 | 1:1
521 // -------- | ------- | ------- | ------- | --------
522 // 0 | TEST | TEST | SKIP | X
523 // 1 | TESTIF | SKIP | TEST | X
524
525 // - SKIP: always skip
526 // - TEST: always test
527 // - TESTIF: only test if checkUnignored
528 // - X: that never happen
529 if (
530 (unignored === negative && ignored !== unignored) ||
531 (negative && !ignored && !unignored && !checkUnignored)
532 ) {
533 return;
534 }
535
536 const matched = rule[mode].test(path);
537
538 if (!matched) {
539 return;
540 }
541
542 ignored = !negative;
543 unignored = negative;
544
545 matchedRule = negative ? UNDEFINED : rule;
546 });
547
548 const ret: IgnoreTestResult = {
549 ignored,
550 unignored,
551 };
552
553 if (matchedRule) {
554 ret.rule = matchedRule;
555 }
556
557 return ret;
558 }
559 }
560
561 type ErrorConstructor = new (message: string) => Error;
562 type InvalidPathHandler = (message: string, constructor: ErrorConstructor) => boolean;
563
564 const throwError: InvalidPathHandler = (message, Ctor) => {
565 throw new Ctor(message);
566 };
567
568 interface CheckPath {
569 (path: unknown, originalPath: string, doThrow: InvalidPathHandler): boolean;
570 isNotRelative: (path: string) => boolean;
571 convert: (path: string) => string;
572 }
573
574 const checkPath: CheckPath = (path, originalPath, doThrow) => {
575 if (!isString(path)) {
576 return doThrow(`path must be a string, but got \`${originalPath}\``, TypeError);
577 }
578
579 // We don't know if we should ignore EMPTY, so throw
580 if (!path) {
581 return doThrow(`path must not be empty`, TypeError);
582 }
583
584 // Check if it is a relative path
585 if (checkPath.isNotRelative(path)) {
586 const r = "`path.relative()`d";
587 return doThrow(`path should be a ${r} string, but got "${originalPath}"`, RangeError);
588 }
589
590 return true;
591 };
592
593 const isNotRelative = (path: string): boolean => REGEX_TEST_INVALID_PATH.test(path);
594
595 checkPath.isNotRelative = isNotRelative;
596
597 // On windows, the following function will be replaced
598 /* istanbul ignore next */
599 checkPath.convert = (path) => path;
600
601 class Ignore {
602 readonly [KEY_IGNORE]?: true;
603 readonly _rules: RuleManager;
604 private readonly _strictPathCheck: boolean;
605 private _ignoreCache!: Record<string, IgnoreTestResult>;
606 private _testCache!: Record<string, IgnoreTestResult>;
607
608 constructor({
609 ignorecase = true,
610 ignoreCase = ignorecase,
611 allowRelativePaths = false,
612 }: IgnoreOptions = {}) {
613 define(this, KEY_IGNORE, true);
614
615 this._rules = new RuleManager(ignoreCase);
616 this._strictPathCheck = !allowRelativePaths;
617 this._initCache();
618 }
619
620 _initCache(): void {
621 // A cache for the result of `.ignores()`
622 this._ignoreCache = Object.create(null);
623
624 // A cache for the result of `.test()`
625 this._testCache = Object.create(null);
626 }
627
628 add(pattern: string | Ignore | readonly (string | Ignore)[] | PatternParams): this {
629 if (this._rules.add(pattern)) {
630 // Some rules have just added to the ignore,
631 // making the behavior changed,
632 // so we need to re-initialize the result cache
633 this._initCache();
634 }
635
636 return this;
637 }
638
639 // legacy
640 addPattern(pattern: string | readonly string[]): this {
641 return this.add(pattern);
642 }
643
644 // @returns {TestResult}
645 _test(
646 originalPath: string,
647 cache: Record<string, IgnoreTestResult>,
648 checkUnignored: boolean,
649 slices?: string[],
650 ): IgnoreTestResult {
651 const path =
652 originalPath &&
653 // Supports nullable path
654 checkPath.convert(originalPath);
655
656 checkPath(path, originalPath, this._strictPathCheck ? throwError : RETURN_FALSE);
657
658 return this._t(path, cache, checkUnignored, slices);
659 }
660
661 checkIgnore(path: string): IgnoreTestResult {
662 // If the path doest not end with a slash, `.ignores()` is much equivalent
663 // to `git check-ignore`
664 if (!REGEX_TEST_TRAILING_SLASH.test(path)) {
665 return this.test(path);
666 }
667
668 const slices = path.split(SLASH).filter(Boolean);
669 slices.pop();
670
671 if (slices.length) {
672 const parent = this._t(slices.join(SLASH) + SLASH, this._testCache, true, slices);
673
674 if (parent.ignored) {
675 return parent;
676 }
677 }
678
679 return this._rules.test(path, false, MODE_CHECK_IGNORE);
680 }
681
682 _t(
683 // The path to be tested
684 path: string,
685
686 // The cache for the result of a certain checking
687 cache: Record<string, IgnoreTestResult>,
688
689 // Whether should check if the path is unignored
690 checkUnignored: boolean,
691
692 // The path slices
693 slices?: string[],
694 ): IgnoreTestResult {
695 if (path in cache) {
696 return cache[path];
697 }
698
699 if (!slices) {
700 // path/to/a.js
701 // ['path', 'to', 'a.js']
702 slices = path.split(SLASH).filter(Boolean);
703 }
704
705 slices.pop();
706
707 // If the path has no parent directory, just test it
708 if (!slices.length) {
709 return (cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE));
710 }
711
712 const parent = this._t(slices.join(SLASH) + SLASH, cache, checkUnignored, slices);
713
714 // If the path contains a parent directory, check the parent first
715 return (cache[path] = parent.ignored
716 ? // > It is not possible to re-include a file if a parent directory of
717 // > that file is excluded.
718 parent
719 : this._rules.test(path, checkUnignored, MODE_IGNORE));
720 }
721
722 ignores(path: string): boolean {
723 return this._test(path, this._ignoreCache, false).ignored;
724 }
725
726 // Alchemy addition: match one path against the rules without checking its
727 // parent directories, so callers can start the parent walk below a
728 // boundary (e.g. a working directory inside an ignored folder).
729 matches(path: string): IgnoreTestResult {
730 return this._rules.test(checkPath.convert(path), true, MODE_IGNORE);
731 }
732
733 createFilter(): (path: string) => boolean {
734 return (path: string) => !this.ignores(path);
735 }
736
737 filter(paths: readonly string[]): string[] {
738 return makeArray(paths).filter(this.createFilter());
739 }
740
741 // @returns {TestResult}
742 test(path: string): IgnoreTestResult {
743 return this._test(path, this._testCache, true);
744 }
745 }
746
747 const factory = (options?: IgnoreOptions): Ignore => new Ignore(options);
748
749 const isPathValid = (path: string): boolean =>
750 checkPath(path && checkPath.convert(path), path, RETURN_FALSE);
751
752 const setupWindows = () => {
753 const makePosix = (str: string): string =>
754 /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/");
755
756 checkPath.convert = makePosix;
757
758 // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/'
759 // 'd:\\foo'
760 const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
761 checkPath.isNotRelative = (path: string) =>
762 REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path);
763 };
764
765 // Windows
766 // --------------------------------------------------------------
767 /* istanbul ignore next */
768 if (
769 // Detect `process` so that it can run in browsers.
770 typeof process !== "undefined" &&
771 process.platform === "win32"
772 ) {
773 setupWindows();
774 }
775
776 // ES module exports (upstream uses `module.exports`). Upstream also exposes
777 // `setupWindows` via `Symbol.for("setupWindows")` for its own test suite; we
778 // drop that hook since it's unused.
779
780 export default factory as unknown as (options?: IgnoreOptions) => IgnoreInstance;
781 export { Ignore, isPathValid };
782
783 // --- Type declarations -----------------------------------------------------
784 // (not part of the verbatim upstream source; mirrors upstream `index.d.ts`)
785
786 type Pathname = string;
787
788 interface PatternParams {
789 pattern: string;
790 mark?: string;
791 }
792
793 interface IgnoreTestResult {
794 ignored: boolean;
795 unignored: boolean;
796 rule?: IgnoreRule;
797 }
798
799 export interface IgnoreOptions {
800 ignorecase?: boolean;
801 /** For compatibility. */
802 ignoreCase?: boolean;
803 allowRelativePaths?: boolean;
804 }
805
806 export interface IgnoreInstance {
807 add(
808 patterns: string | IgnoreInstance | readonly (string | IgnoreInstance)[] | PatternParams,
809 ): this;
810 filter(pathnames: readonly Pathname[]): Pathname[];
811 createFilter(): (pathname: Pathname) => boolean;
812 ignores(pathname: Pathname): boolean;
813 /** Alchemy addition: match one path without checking parent directories. */
814 matches(pathname: Pathname): {
815 ignored: boolean;
816 unignored: boolean;
817 };
818 test(pathname: Pathname): {
819 ignored: boolean;
820 unignored: boolean;
821 rule?: { pattern: string; mark?: string; negative: boolean };
822 };
823 checkIgnore(pathname: Pathname): {
824 ignored: boolean;
825 unignored: boolean;
826 rule?: { pattern: string; mark?: string; negative: boolean };
827 };
828 }