rollup 4.0.0-1 → 4.0.0-3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4611 @@
1
+ /*
2
+ @license
3
+ Rollup.js v4.0.0-3
4
+ Fri, 04 Aug 2023 08:16:31 GMT - commit d9deb724f026a6f3e429509fce2d920e75d6a1ae
5
+
6
+ https://github.com/rollup/rollup
7
+
8
+ Released under the MIT License.
9
+ */
10
+ 'use strict';
11
+
12
+ const rollup = require('./rollup.js');
13
+ const require$$0$1 = require('fs');
14
+ const require$$2 = require('util');
15
+ const require$$1 = require('stream');
16
+ const require$$0$2 = require('path');
17
+ const require$$2$1 = require('os');
18
+ const fseventsImporter = require('./fsevents-importer.js');
19
+ const require$$0$3 = require('events');
20
+
21
+ var chokidar = {};
22
+
23
+ const fs$3 = require$$0$1;
24
+ const { Readable } = require$$1;
25
+ const sysPath$3 = require$$0$2;
26
+ const { promisify: promisify$3 } = require$$2;
27
+ const picomatch$1 = rollup.picomatch;
28
+
29
+ const readdir$1 = promisify$3(fs$3.readdir);
30
+ const stat$3 = promisify$3(fs$3.stat);
31
+ const lstat$2 = promisify$3(fs$3.lstat);
32
+ const realpath$1 = promisify$3(fs$3.realpath);
33
+
34
+ /**
35
+ * @typedef {Object} EntryInfo
36
+ * @property {String} path
37
+ * @property {String} fullPath
38
+ * @property {fs.Stats=} stats
39
+ * @property {fs.Dirent=} dirent
40
+ * @property {String} basename
41
+ */
42
+
43
+ const BANG$2 = '!';
44
+ const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR';
45
+ const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]);
46
+ const FILE_TYPE = 'files';
47
+ const DIR_TYPE = 'directories';
48
+ const FILE_DIR_TYPE = 'files_directories';
49
+ const EVERYTHING_TYPE = 'all';
50
+ const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE];
51
+
52
+ const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code);
53
+ const [maj, min] = process.versions.node.split('.').slice(0, 2).map(n => Number.parseInt(n, 10));
54
+ const wantBigintFsStats = process.platform === 'win32' && (maj > 10 || (maj === 10 && min >= 5));
55
+
56
+ const normalizeFilter = filter => {
57
+ if (filter === undefined) return;
58
+ if (typeof filter === 'function') return filter;
59
+
60
+ if (typeof filter === 'string') {
61
+ const glob = picomatch$1(filter.trim());
62
+ return entry => glob(entry.basename);
63
+ }
64
+
65
+ if (Array.isArray(filter)) {
66
+ const positive = [];
67
+ const negative = [];
68
+ for (const item of filter) {
69
+ const trimmed = item.trim();
70
+ if (trimmed.charAt(0) === BANG$2) {
71
+ negative.push(picomatch$1(trimmed.slice(1)));
72
+ } else {
73
+ positive.push(picomatch$1(trimmed));
74
+ }
75
+ }
76
+
77
+ if (negative.length > 0) {
78
+ if (positive.length > 0) {
79
+ return entry =>
80
+ positive.some(f => f(entry.basename)) && !negative.some(f => f(entry.basename));
81
+ }
82
+ return entry => !negative.some(f => f(entry.basename));
83
+ }
84
+ return entry => positive.some(f => f(entry.basename));
85
+ }
86
+ };
87
+
88
+ class ReaddirpStream extends Readable {
89
+ static get defaultOptions() {
90
+ return {
91
+ root: '.',
92
+ /* eslint-disable no-unused-vars */
93
+ fileFilter: (path) => true,
94
+ directoryFilter: (path) => true,
95
+ /* eslint-enable no-unused-vars */
96
+ type: FILE_TYPE,
97
+ lstat: false,
98
+ depth: 2147483648,
99
+ alwaysStat: false
100
+ };
101
+ }
102
+
103
+ constructor(options = {}) {
104
+ super({
105
+ objectMode: true,
106
+ autoDestroy: true,
107
+ highWaterMark: options.highWaterMark || 4096
108
+ });
109
+ const opts = { ...ReaddirpStream.defaultOptions, ...options };
110
+ const { root, type } = opts;
111
+
112
+ this._fileFilter = normalizeFilter(opts.fileFilter);
113
+ this._directoryFilter = normalizeFilter(opts.directoryFilter);
114
+
115
+ const statMethod = opts.lstat ? lstat$2 : stat$3;
116
+ // Use bigint stats if it's windows and stat() supports options (node 10+).
117
+ if (wantBigintFsStats) {
118
+ this._stat = path => statMethod(path, { bigint: true });
119
+ } else {
120
+ this._stat = statMethod;
121
+ }
122
+
123
+ this._maxDepth = opts.depth;
124
+ this._wantsDir = [DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
125
+ this._wantsFile = [FILE_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE].includes(type);
126
+ this._wantsEverything = type === EVERYTHING_TYPE;
127
+ this._root = sysPath$3.resolve(root);
128
+ this._isDirent = ('Dirent' in fs$3) && !opts.alwaysStat;
129
+ this._statsProp = this._isDirent ? 'dirent' : 'stats';
130
+ this._rdOptions = { encoding: 'utf8', withFileTypes: this._isDirent };
131
+
132
+ // Launch stream with one parent, the root dir.
133
+ this.parents = [this._exploreDir(root, 1)];
134
+ this.reading = false;
135
+ this.parent = undefined;
136
+ }
137
+
138
+ async _read(batch) {
139
+ if (this.reading) return;
140
+ this.reading = true;
141
+
142
+ try {
143
+ while (!this.destroyed && batch > 0) {
144
+ const { path, depth, files = [] } = this.parent || {};
145
+
146
+ if (files.length > 0) {
147
+ const slice = files.splice(0, batch).map(dirent => this._formatEntry(dirent, path));
148
+ for (const entry of await Promise.all(slice)) {
149
+ if (this.destroyed) return;
150
+
151
+ const entryType = await this._getEntryType(entry);
152
+ if (entryType === 'directory' && this._directoryFilter(entry)) {
153
+ if (depth <= this._maxDepth) {
154
+ this.parents.push(this._exploreDir(entry.fullPath, depth + 1));
155
+ }
156
+
157
+ if (this._wantsDir) {
158
+ this.push(entry);
159
+ batch--;
160
+ }
161
+ } else if ((entryType === 'file' || this._includeAsFile(entry)) && this._fileFilter(entry)) {
162
+ if (this._wantsFile) {
163
+ this.push(entry);
164
+ batch--;
165
+ }
166
+ }
167
+ }
168
+ } else {
169
+ const parent = this.parents.pop();
170
+ if (!parent) {
171
+ this.push(null);
172
+ break;
173
+ }
174
+ this.parent = await parent;
175
+ if (this.destroyed) return;
176
+ }
177
+ }
178
+ } catch (error) {
179
+ this.destroy(error);
180
+ } finally {
181
+ this.reading = false;
182
+ }
183
+ }
184
+
185
+ async _exploreDir(path, depth) {
186
+ let files;
187
+ try {
188
+ files = await readdir$1(path, this._rdOptions);
189
+ } catch (error) {
190
+ this._onError(error);
191
+ }
192
+ return { files, depth, path };
193
+ }
194
+
195
+ async _formatEntry(dirent, path) {
196
+ let entry;
197
+ try {
198
+ const basename = this._isDirent ? dirent.name : dirent;
199
+ const fullPath = sysPath$3.resolve(sysPath$3.join(path, basename));
200
+ entry = { path: sysPath$3.relative(this._root, fullPath), fullPath, basename };
201
+ entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath);
202
+ } catch (err) {
203
+ this._onError(err);
204
+ }
205
+ return entry;
206
+ }
207
+
208
+ _onError(err) {
209
+ if (isNormalFlowError(err) && !this.destroyed) {
210
+ this.emit('warn', err);
211
+ } else {
212
+ this.destroy(err);
213
+ }
214
+ }
215
+
216
+ async _getEntryType(entry) {
217
+ // entry may be undefined, because a warning or an error were emitted
218
+ // and the statsProp is undefined
219
+ const stats = entry && entry[this._statsProp];
220
+ if (!stats) {
221
+ return;
222
+ }
223
+ if (stats.isFile()) {
224
+ return 'file';
225
+ }
226
+ if (stats.isDirectory()) {
227
+ return 'directory';
228
+ }
229
+ if (stats && stats.isSymbolicLink()) {
230
+ const full = entry.fullPath;
231
+ try {
232
+ const entryRealPath = await realpath$1(full);
233
+ const entryRealPathStats = await lstat$2(entryRealPath);
234
+ if (entryRealPathStats.isFile()) {
235
+ return 'file';
236
+ }
237
+ if (entryRealPathStats.isDirectory()) {
238
+ const len = entryRealPath.length;
239
+ if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath$3.sep) {
240
+ const recursiveError = new Error(
241
+ `Circular symlink detected: "${full}" points to "${entryRealPath}"`
242
+ );
243
+ recursiveError.code = RECURSIVE_ERROR_CODE;
244
+ return this._onError(recursiveError);
245
+ }
246
+ return 'directory';
247
+ }
248
+ } catch (error) {
249
+ this._onError(error);
250
+ }
251
+ }
252
+ }
253
+
254
+ _includeAsFile(entry) {
255
+ const stats = entry && entry[this._statsProp];
256
+
257
+ return stats && this._wantsEverything && !stats.isDirectory();
258
+ }
259
+ }
260
+
261
+ /**
262
+ * @typedef {Object} ReaddirpArguments
263
+ * @property {Function=} fileFilter
264
+ * @property {Function=} directoryFilter
265
+ * @property {String=} type
266
+ * @property {Number=} depth
267
+ * @property {String=} root
268
+ * @property {Boolean=} lstat
269
+ * @property {Boolean=} bigint
270
+ */
271
+
272
+ /**
273
+ * Main function which ends up calling readdirRec and reads all files and directories in given root recursively.
274
+ * @param {String} root Root directory
275
+ * @param {ReaddirpArguments=} options Options to specify root (start directory), filters and recursion depth
276
+ */
277
+ const readdirp$1 = (root, options = {}) => {
278
+ let type = options.entryType || options.type;
279
+ if (type === 'both') type = FILE_DIR_TYPE; // backwards-compatibility
280
+ if (type) options.type = type;
281
+ if (!root) {
282
+ throw new Error('readdirp: root argument is required. Usage: readdirp(root, options)');
283
+ } else if (typeof root !== 'string') {
284
+ throw new TypeError('readdirp: root argument must be a string. Usage: readdirp(root, options)');
285
+ } else if (type && !ALL_TYPES.includes(type)) {
286
+ throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(', ')}`);
287
+ }
288
+
289
+ options.root = root;
290
+ return new ReaddirpStream(options);
291
+ };
292
+
293
+ const readdirpPromise = (root, options = {}) => {
294
+ return new Promise((resolve, reject) => {
295
+ const files = [];
296
+ readdirp$1(root, options)
297
+ .on('data', entry => files.push(entry))
298
+ .on('end', () => resolve(files))
299
+ .on('error', error => reject(error));
300
+ });
301
+ };
302
+
303
+ readdirp$1.promise = readdirpPromise;
304
+ readdirp$1.ReaddirpStream = ReaddirpStream;
305
+ readdirp$1.default = readdirp$1;
306
+
307
+ var readdirp_1 = readdirp$1;
308
+
309
+ /*@__PURE__*/rollup.getDefaultExportFromCjs(readdirp_1);
310
+
311
+ var anymatch$2 = {exports: {}};
312
+
313
+ /*!
314
+ * normalize-path <https://github.com/jonschlinkert/normalize-path>
315
+ *
316
+ * Copyright (c) 2014-2018, Jon Schlinkert.
317
+ * Released under the MIT License.
318
+ */
319
+
320
+ var normalizePath$2 = function(path, stripTrailing) {
321
+ if (typeof path !== 'string') {
322
+ throw new TypeError('expected path to be a string');
323
+ }
324
+
325
+ if (path === '\\' || path === '/') return '/';
326
+
327
+ var len = path.length;
328
+ if (len <= 1) return path;
329
+
330
+ // ensure that win32 namespaces has two leading slashes, so that the path is
331
+ // handled properly by the win32 version of path.parse() after being normalized
332
+ // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces
333
+ var prefix = '';
334
+ if (len > 4 && path[3] === '\\') {
335
+ var ch = path[2];
336
+ if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') {
337
+ path = path.slice(2);
338
+ prefix = '//';
339
+ }
340
+ }
341
+
342
+ var segs = path.split(/[/\\]+/);
343
+ if (stripTrailing !== false && segs[segs.length - 1] === '') {
344
+ segs.pop();
345
+ }
346
+ return prefix + segs.join('/');
347
+ };
348
+
349
+ /*@__PURE__*/rollup.getDefaultExportFromCjs(normalizePath$2);
350
+
351
+ var anymatch_1 = anymatch$2.exports;
352
+
353
+ Object.defineProperty(anymatch_1, "__esModule", { value: true });
354
+
355
+ const picomatch = rollup.picomatch;
356
+ const normalizePath$1 = normalizePath$2;
357
+
358
+ /**
359
+ * @typedef {(testString: string) => boolean} AnymatchFn
360
+ * @typedef {string|RegExp|AnymatchFn} AnymatchPattern
361
+ * @typedef {AnymatchPattern|AnymatchPattern[]} AnymatchMatcher
362
+ */
363
+ const BANG$1 = '!';
364
+ const DEFAULT_OPTIONS = {returnIndex: false};
365
+ const arrify$1 = (item) => Array.isArray(item) ? item : [item];
366
+
367
+ /**
368
+ * @param {AnymatchPattern} matcher
369
+ * @param {object} options
370
+ * @returns {AnymatchFn}
371
+ */
372
+ const createPattern = (matcher, options) => {
373
+ if (typeof matcher === 'function') {
374
+ return matcher;
375
+ }
376
+ if (typeof matcher === 'string') {
377
+ const glob = picomatch(matcher, options);
378
+ return (string) => matcher === string || glob(string);
379
+ }
380
+ if (matcher instanceof RegExp) {
381
+ return (string) => matcher.test(string);
382
+ }
383
+ return (string) => false;
384
+ };
385
+
386
+ /**
387
+ * @param {Array<Function>} patterns
388
+ * @param {Array<Function>} negPatterns
389
+ * @param {String|Array} args
390
+ * @param {Boolean} returnIndex
391
+ * @returns {boolean|number}
392
+ */
393
+ const matchPatterns = (patterns, negPatterns, args, returnIndex) => {
394
+ const isList = Array.isArray(args);
395
+ const _path = isList ? args[0] : args;
396
+ if (!isList && typeof _path !== 'string') {
397
+ throw new TypeError('anymatch: second argument must be a string: got ' +
398
+ Object.prototype.toString.call(_path))
399
+ }
400
+ const path = normalizePath$1(_path, false);
401
+
402
+ for (let index = 0; index < negPatterns.length; index++) {
403
+ const nglob = negPatterns[index];
404
+ if (nglob(path)) {
405
+ return returnIndex ? -1 : false;
406
+ }
407
+ }
408
+
409
+ const applied = isList && [path].concat(args.slice(1));
410
+ for (let index = 0; index < patterns.length; index++) {
411
+ const pattern = patterns[index];
412
+ if (isList ? pattern(...applied) : pattern(path)) {
413
+ return returnIndex ? index : true;
414
+ }
415
+ }
416
+
417
+ return returnIndex ? -1 : false;
418
+ };
419
+
420
+ /**
421
+ * @param {AnymatchMatcher} matchers
422
+ * @param {Array|string} testString
423
+ * @param {object} options
424
+ * @returns {boolean|number|Function}
425
+ */
426
+ const anymatch$1 = (matchers, testString, options = DEFAULT_OPTIONS) => {
427
+ if (matchers == null) {
428
+ throw new TypeError('anymatch: specify first argument');
429
+ }
430
+ const opts = typeof options === 'boolean' ? {returnIndex: options} : options;
431
+ const returnIndex = opts.returnIndex || false;
432
+
433
+ // Early cache for matchers.
434
+ const mtchers = arrify$1(matchers);
435
+ const negatedGlobs = mtchers
436
+ .filter(item => typeof item === 'string' && item.charAt(0) === BANG$1)
437
+ .map(item => item.slice(1))
438
+ .map(item => picomatch(item, opts));
439
+ const patterns = mtchers
440
+ .filter(item => typeof item !== 'string' || (typeof item === 'string' && item.charAt(0) !== BANG$1))
441
+ .map(matcher => createPattern(matcher, opts));
442
+
443
+ if (testString == null) {
444
+ return (testString, ri = false) => {
445
+ const returnIndex = typeof ri === 'boolean' ? ri : false;
446
+ return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
447
+ }
448
+ }
449
+
450
+ return matchPatterns(patterns, negatedGlobs, testString, returnIndex);
451
+ };
452
+
453
+ anymatch$1.default = anymatch$1;
454
+ anymatch$2.exports = anymatch$1;
455
+
456
+ var anymatchExports = anymatch$2.exports;
457
+ /*@__PURE__*/rollup.getDefaultExportFromCjs(anymatchExports);
458
+
459
+ /*!
460
+ * is-extglob <https://github.com/jonschlinkert/is-extglob>
461
+ *
462
+ * Copyright (c) 2014-2016, Jon Schlinkert.
463
+ * Licensed under the MIT License.
464
+ */
465
+
466
+ var isExtglob$1 = function isExtglob(str) {
467
+ if (typeof str !== 'string' || str === '') {
468
+ return false;
469
+ }
470
+
471
+ var match;
472
+ while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) {
473
+ if (match[2]) return true;
474
+ str = str.slice(match.index + match[0].length);
475
+ }
476
+
477
+ return false;
478
+ };
479
+
480
+ /*@__PURE__*/rollup.getDefaultExportFromCjs(isExtglob$1);
481
+
482
+ /*!
483
+ * is-glob <https://github.com/jonschlinkert/is-glob>
484
+ *
485
+ * Copyright (c) 2014-2017, Jon Schlinkert.
486
+ * Released under the MIT License.
487
+ */
488
+
489
+ var isExtglob = isExtglob$1;
490
+ var chars = { '{': '}', '(': ')', '[': ']'};
491
+ var strictCheck = function(str) {
492
+ if (str[0] === '!') {
493
+ return true;
494
+ }
495
+ var index = 0;
496
+ var pipeIndex = -2;
497
+ var closeSquareIndex = -2;
498
+ var closeCurlyIndex = -2;
499
+ var closeParenIndex = -2;
500
+ var backSlashIndex = -2;
501
+ while (index < str.length) {
502
+ if (str[index] === '*') {
503
+ return true;
504
+ }
505
+
506
+ if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) {
507
+ return true;
508
+ }
509
+
510
+ if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') {
511
+ if (closeSquareIndex < index) {
512
+ closeSquareIndex = str.indexOf(']', index);
513
+ }
514
+ if (closeSquareIndex > index) {
515
+ if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
516
+ return true;
517
+ }
518
+ backSlashIndex = str.indexOf('\\', index);
519
+ if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
520
+ return true;
521
+ }
522
+ }
523
+ }
524
+
525
+ if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') {
526
+ closeCurlyIndex = str.indexOf('}', index);
527
+ if (closeCurlyIndex > index) {
528
+ backSlashIndex = str.indexOf('\\', index);
529
+ if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) {
530
+ return true;
531
+ }
532
+ }
533
+ }
534
+
535
+ if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') {
536
+ closeParenIndex = str.indexOf(')', index);
537
+ if (closeParenIndex > index) {
538
+ backSlashIndex = str.indexOf('\\', index);
539
+ if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
540
+ return true;
541
+ }
542
+ }
543
+ }
544
+
545
+ if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') {
546
+ if (pipeIndex < index) {
547
+ pipeIndex = str.indexOf('|', index);
548
+ }
549
+ if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') {
550
+ closeParenIndex = str.indexOf(')', pipeIndex);
551
+ if (closeParenIndex > pipeIndex) {
552
+ backSlashIndex = str.indexOf('\\', pipeIndex);
553
+ if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
554
+ return true;
555
+ }
556
+ }
557
+ }
558
+ }
559
+
560
+ if (str[index] === '\\') {
561
+ var open = str[index + 1];
562
+ index += 2;
563
+ var close = chars[open];
564
+
565
+ if (close) {
566
+ var n = str.indexOf(close, index);
567
+ if (n !== -1) {
568
+ index = n + 1;
569
+ }
570
+ }
571
+
572
+ if (str[index] === '!') {
573
+ return true;
574
+ }
575
+ } else {
576
+ index++;
577
+ }
578
+ }
579
+ return false;
580
+ };
581
+
582
+ var relaxedCheck = function(str) {
583
+ if (str[0] === '!') {
584
+ return true;
585
+ }
586
+ var index = 0;
587
+ while (index < str.length) {
588
+ if (/[*?{}()[\]]/.test(str[index])) {
589
+ return true;
590
+ }
591
+
592
+ if (str[index] === '\\') {
593
+ var open = str[index + 1];
594
+ index += 2;
595
+ var close = chars[open];
596
+
597
+ if (close) {
598
+ var n = str.indexOf(close, index);
599
+ if (n !== -1) {
600
+ index = n + 1;
601
+ }
602
+ }
603
+
604
+ if (str[index] === '!') {
605
+ return true;
606
+ }
607
+ } else {
608
+ index++;
609
+ }
610
+ }
611
+ return false;
612
+ };
613
+
614
+ var isGlob$2 = function isGlob(str, options) {
615
+ if (typeof str !== 'string' || str === '') {
616
+ return false;
617
+ }
618
+
619
+ if (isExtglob(str)) {
620
+ return true;
621
+ }
622
+
623
+ var check = strictCheck;
624
+
625
+ // optionally relax check
626
+ if (options && options.strict === false) {
627
+ check = relaxedCheck;
628
+ }
629
+
630
+ return check(str);
631
+ };
632
+
633
+ /*@__PURE__*/rollup.getDefaultExportFromCjs(isGlob$2);
634
+
635
+ var isGlob$1 = isGlob$2;
636
+ var pathPosixDirname = require$$0$2.posix.dirname;
637
+ var isWin32 = require$$2$1.platform() === 'win32';
638
+
639
+ var slash = '/';
640
+ var backslash = /\\/g;
641
+ var enclosure = /[\{\[].*[\}\]]$/;
642
+ var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/;
643
+ var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g;
644
+
645
+ /**
646
+ * @param {string} str
647
+ * @param {Object} opts
648
+ * @param {boolean} [opts.flipBackslashes=true]
649
+ * @returns {string}
650
+ */
651
+ var globParent$1 = function globParent(str, opts) {
652
+ var options = Object.assign({ flipBackslashes: true }, opts);
653
+
654
+ // flip windows path separators
655
+ if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) {
656
+ str = str.replace(backslash, slash);
657
+ }
658
+
659
+ // special case for strings ending in enclosure containing path separator
660
+ if (enclosure.test(str)) {
661
+ str += slash;
662
+ }
663
+
664
+ // preserves full path in case of trailing path separator
665
+ str += 'a';
666
+
667
+ // remove path parts that are globby
668
+ do {
669
+ str = pathPosixDirname(str);
670
+ } while (isGlob$1(str) || globby.test(str));
671
+
672
+ // remove escape chars and return result
673
+ return str.replace(escaped, '$1');
674
+ };
675
+
676
+ /*@__PURE__*/rollup.getDefaultExportFromCjs(globParent$1);
677
+
678
+ var utils$3 = {};
679
+
680
+ (function (exports) {
681
+
682
+ exports.isInteger = num => {
683
+ if (typeof num === 'number') {
684
+ return Number.isInteger(num);
685
+ }
686
+ if (typeof num === 'string' && num.trim() !== '') {
687
+ return Number.isInteger(Number(num));
688
+ }
689
+ return false;
690
+ };
691
+
692
+ /**
693
+ * Find a node of the given type
694
+ */
695
+
696
+ exports.find = (node, type) => node.nodes.find(node => node.type === type);
697
+
698
+ /**
699
+ * Find a node of the given type
700
+ */
701
+
702
+ exports.exceedsLimit = (min, max, step = 1, limit) => {
703
+ if (limit === false) return false;
704
+ if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
705
+ return ((Number(max) - Number(min)) / Number(step)) >= limit;
706
+ };
707
+
708
+ /**
709
+ * Escape the given node with '\\' before node.value
710
+ */
711
+
712
+ exports.escapeNode = (block, n = 0, type) => {
713
+ let node = block.nodes[n];
714
+ if (!node) return;
715
+
716
+ if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
717
+ if (node.escaped !== true) {
718
+ node.value = '\\' + node.value;
719
+ node.escaped = true;
720
+ }
721
+ }
722
+ };
723
+
724
+ /**
725
+ * Returns true if the given brace node should be enclosed in literal braces
726
+ */
727
+
728
+ exports.encloseBrace = node => {
729
+ if (node.type !== 'brace') return false;
730
+ if ((node.commas >> 0 + node.ranges >> 0) === 0) {
731
+ node.invalid = true;
732
+ return true;
733
+ }
734
+ return false;
735
+ };
736
+
737
+ /**
738
+ * Returns true if a brace node is invalid.
739
+ */
740
+
741
+ exports.isInvalidBrace = block => {
742
+ if (block.type !== 'brace') return false;
743
+ if (block.invalid === true || block.dollar) return true;
744
+ if ((block.commas >> 0 + block.ranges >> 0) === 0) {
745
+ block.invalid = true;
746
+ return true;
747
+ }
748
+ if (block.open !== true || block.close !== true) {
749
+ block.invalid = true;
750
+ return true;
751
+ }
752
+ return false;
753
+ };
754
+
755
+ /**
756
+ * Returns true if a node is an open or close node
757
+ */
758
+
759
+ exports.isOpenOrClose = node => {
760
+ if (node.type === 'open' || node.type === 'close') {
761
+ return true;
762
+ }
763
+ return node.open === true || node.close === true;
764
+ };
765
+
766
+ /**
767
+ * Reduce an array of text nodes.
768
+ */
769
+
770
+ exports.reduce = nodes => nodes.reduce((acc, node) => {
771
+ if (node.type === 'text') acc.push(node.value);
772
+ if (node.type === 'range') node.type = 'text';
773
+ return acc;
774
+ }, []);
775
+
776
+ /**
777
+ * Flatten an array
778
+ */
779
+
780
+ exports.flatten = (...args) => {
781
+ const result = [];
782
+ const flat = arr => {
783
+ for (let i = 0; i < arr.length; i++) {
784
+ let ele = arr[i];
785
+ Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
786
+ }
787
+ return result;
788
+ };
789
+ flat(args);
790
+ return result;
791
+ };
792
+ } (utils$3));
793
+
794
+ /*@__PURE__*/rollup.getDefaultExportFromCjs(utils$3);
795
+
796
+ const utils$2 = utils$3;
797
+
798
+ var stringify$4 = (ast, options = {}) => {
799
+ let stringify = (node, parent = {}) => {
800
+ let invalidBlock = options.escapeInvalid && utils$2.isInvalidBrace(parent);
801
+ let invalidNode = node.invalid === true && options.escapeInvalid === true;
802
+ let output = '';
803
+
804
+ if (node.value) {
805
+ if ((invalidBlock || invalidNode) && utils$2.isOpenOrClose(node)) {
806
+ return '\\' + node.value;
807
+ }
808
+ return node.value;
809
+ }
810
+
811
+ if (node.value) {
812
+ return node.value;
813
+ }
814
+
815
+ if (node.nodes) {
816
+ for (let child of node.nodes) {
817
+ output += stringify(child);
818
+ }
819
+ }
820
+ return output;
821
+ };
822
+
823
+ return stringify(ast);
824
+ };
825
+
826
+ /*@__PURE__*/rollup.getDefaultExportFromCjs(stringify$4);
827
+
828
+ /*!
829
+ * is-number <https://github.com/jonschlinkert/is-number>
830
+ *
831
+ * Copyright (c) 2014-present, Jon Schlinkert.
832
+ * Released under the MIT License.
833
+ */
834
+
835
+ var isNumber$2 = function(num) {
836
+ if (typeof num === 'number') {
837
+ return num - num === 0;
838
+ }
839
+ if (typeof num === 'string' && num.trim() !== '') {
840
+ return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
841
+ }
842
+ return false;
843
+ };
844
+
845
+ /*@__PURE__*/rollup.getDefaultExportFromCjs(isNumber$2);
846
+
847
+ /*!
848
+ * to-regex-range <https://github.com/micromatch/to-regex-range>
849
+ *
850
+ * Copyright (c) 2015-present, Jon Schlinkert.
851
+ * Released under the MIT License.
852
+ */
853
+
854
+ const isNumber$1 = isNumber$2;
855
+
856
+ const toRegexRange$1 = (min, max, options) => {
857
+ if (isNumber$1(min) === false) {
858
+ throw new TypeError('toRegexRange: expected the first argument to be a number');
859
+ }
860
+
861
+ if (max === void 0 || min === max) {
862
+ return String(min);
863
+ }
864
+
865
+ if (isNumber$1(max) === false) {
866
+ throw new TypeError('toRegexRange: expected the second argument to be a number.');
867
+ }
868
+
869
+ let opts = { relaxZeros: true, ...options };
870
+ if (typeof opts.strictZeros === 'boolean') {
871
+ opts.relaxZeros = opts.strictZeros === false;
872
+ }
873
+
874
+ let relax = String(opts.relaxZeros);
875
+ let shorthand = String(opts.shorthand);
876
+ let capture = String(opts.capture);
877
+ let wrap = String(opts.wrap);
878
+ let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
879
+
880
+ if (toRegexRange$1.cache.hasOwnProperty(cacheKey)) {
881
+ return toRegexRange$1.cache[cacheKey].result;
882
+ }
883
+
884
+ let a = Math.min(min, max);
885
+ let b = Math.max(min, max);
886
+
887
+ if (Math.abs(a - b) === 1) {
888
+ let result = min + '|' + max;
889
+ if (opts.capture) {
890
+ return `(${result})`;
891
+ }
892
+ if (opts.wrap === false) {
893
+ return result;
894
+ }
895
+ return `(?:${result})`;
896
+ }
897
+
898
+ let isPadded = hasPadding(min) || hasPadding(max);
899
+ let state = { min, max, a, b };
900
+ let positives = [];
901
+ let negatives = [];
902
+
903
+ if (isPadded) {
904
+ state.isPadded = isPadded;
905
+ state.maxLen = String(state.max).length;
906
+ }
907
+
908
+ if (a < 0) {
909
+ let newMin = b < 0 ? Math.abs(b) : 1;
910
+ negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
911
+ a = state.a = 0;
912
+ }
913
+
914
+ if (b >= 0) {
915
+ positives = splitToPatterns(a, b, state, opts);
916
+ }
917
+
918
+ state.negatives = negatives;
919
+ state.positives = positives;
920
+ state.result = collatePatterns(negatives, positives);
921
+
922
+ if (opts.capture === true) {
923
+ state.result = `(${state.result})`;
924
+ } else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
925
+ state.result = `(?:${state.result})`;
926
+ }
927
+
928
+ toRegexRange$1.cache[cacheKey] = state;
929
+ return state.result;
930
+ };
931
+
932
+ function collatePatterns(neg, pos, options) {
933
+ let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
934
+ let onlyPositive = filterPatterns(pos, neg, '', false) || [];
935
+ let intersected = filterPatterns(neg, pos, '-?', true) || [];
936
+ let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
937
+ return subpatterns.join('|');
938
+ }
939
+
940
+ function splitToRanges(min, max) {
941
+ let nines = 1;
942
+ let zeros = 1;
943
+
944
+ let stop = countNines(min, nines);
945
+ let stops = new Set([max]);
946
+
947
+ while (min <= stop && stop <= max) {
948
+ stops.add(stop);
949
+ nines += 1;
950
+ stop = countNines(min, nines);
951
+ }
952
+
953
+ stop = countZeros(max + 1, zeros) - 1;
954
+
955
+ while (min < stop && stop <= max) {
956
+ stops.add(stop);
957
+ zeros += 1;
958
+ stop = countZeros(max + 1, zeros) - 1;
959
+ }
960
+
961
+ stops = [...stops];
962
+ stops.sort(compare);
963
+ return stops;
964
+ }
965
+
966
+ /**
967
+ * Convert a range to a regex pattern
968
+ * @param {Number} `start`
969
+ * @param {Number} `stop`
970
+ * @return {String}
971
+ */
972
+
973
+ function rangeToPattern(start, stop, options) {
974
+ if (start === stop) {
975
+ return { pattern: start, count: [], digits: 0 };
976
+ }
977
+
978
+ let zipped = zip(start, stop);
979
+ let digits = zipped.length;
980
+ let pattern = '';
981
+ let count = 0;
982
+
983
+ for (let i = 0; i < digits; i++) {
984
+ let [startDigit, stopDigit] = zipped[i];
985
+
986
+ if (startDigit === stopDigit) {
987
+ pattern += startDigit;
988
+
989
+ } else if (startDigit !== '0' || stopDigit !== '9') {
990
+ pattern += toCharacterClass(startDigit, stopDigit);
991
+
992
+ } else {
993
+ count++;
994
+ }
995
+ }
996
+
997
+ if (count) {
998
+ pattern += options.shorthand === true ? '\\d' : '[0-9]';
999
+ }
1000
+
1001
+ return { pattern, count: [count], digits };
1002
+ }
1003
+
1004
+ function splitToPatterns(min, max, tok, options) {
1005
+ let ranges = splitToRanges(min, max);
1006
+ let tokens = [];
1007
+ let start = min;
1008
+ let prev;
1009
+
1010
+ for (let i = 0; i < ranges.length; i++) {
1011
+ let max = ranges[i];
1012
+ let obj = rangeToPattern(String(start), String(max), options);
1013
+ let zeros = '';
1014
+
1015
+ if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
1016
+ if (prev.count.length > 1) {
1017
+ prev.count.pop();
1018
+ }
1019
+
1020
+ prev.count.push(obj.count[0]);
1021
+ prev.string = prev.pattern + toQuantifier(prev.count);
1022
+ start = max + 1;
1023
+ continue;
1024
+ }
1025
+
1026
+ if (tok.isPadded) {
1027
+ zeros = padZeros(max, tok, options);
1028
+ }
1029
+
1030
+ obj.string = zeros + obj.pattern + toQuantifier(obj.count);
1031
+ tokens.push(obj);
1032
+ start = max + 1;
1033
+ prev = obj;
1034
+ }
1035
+
1036
+ return tokens;
1037
+ }
1038
+
1039
+ function filterPatterns(arr, comparison, prefix, intersection, options) {
1040
+ let result = [];
1041
+
1042
+ for (let ele of arr) {
1043
+ let { string } = ele;
1044
+
1045
+ // only push if _both_ are negative...
1046
+ if (!intersection && !contains(comparison, 'string', string)) {
1047
+ result.push(prefix + string);
1048
+ }
1049
+
1050
+ // or _both_ are positive
1051
+ if (intersection && contains(comparison, 'string', string)) {
1052
+ result.push(prefix + string);
1053
+ }
1054
+ }
1055
+ return result;
1056
+ }
1057
+
1058
+ /**
1059
+ * Zip strings
1060
+ */
1061
+
1062
+ function zip(a, b) {
1063
+ let arr = [];
1064
+ for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]);
1065
+ return arr;
1066
+ }
1067
+
1068
+ function compare(a, b) {
1069
+ return a > b ? 1 : b > a ? -1 : 0;
1070
+ }
1071
+
1072
+ function contains(arr, key, val) {
1073
+ return arr.some(ele => ele[key] === val);
1074
+ }
1075
+
1076
+ function countNines(min, len) {
1077
+ return Number(String(min).slice(0, -len) + '9'.repeat(len));
1078
+ }
1079
+
1080
+ function countZeros(integer, zeros) {
1081
+ return integer - (integer % Math.pow(10, zeros));
1082
+ }
1083
+
1084
+ function toQuantifier(digits) {
1085
+ let [start = 0, stop = ''] = digits;
1086
+ if (stop || start > 1) {
1087
+ return `{${start + (stop ? ',' + stop : '')}}`;
1088
+ }
1089
+ return '';
1090
+ }
1091
+
1092
+ function toCharacterClass(a, b, options) {
1093
+ return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
1094
+ }
1095
+
1096
+ function hasPadding(str) {
1097
+ return /^-?(0+)\d/.test(str);
1098
+ }
1099
+
1100
+ function padZeros(value, tok, options) {
1101
+ if (!tok.isPadded) {
1102
+ return value;
1103
+ }
1104
+
1105
+ let diff = Math.abs(tok.maxLen - String(value).length);
1106
+ let relax = options.relaxZeros !== false;
1107
+
1108
+ switch (diff) {
1109
+ case 0:
1110
+ return '';
1111
+ case 1:
1112
+ return relax ? '0?' : '0';
1113
+ case 2:
1114
+ return relax ? '0{0,2}' : '00';
1115
+ default: {
1116
+ return relax ? `0{0,${diff}}` : `0{${diff}}`;
1117
+ }
1118
+ }
1119
+ }
1120
+
1121
+ /**
1122
+ * Cache
1123
+ */
1124
+
1125
+ toRegexRange$1.cache = {};
1126
+ toRegexRange$1.clearCache = () => (toRegexRange$1.cache = {});
1127
+
1128
+ /**
1129
+ * Expose `toRegexRange`
1130
+ */
1131
+
1132
+ var toRegexRange_1 = toRegexRange$1;
1133
+
1134
+ /*@__PURE__*/rollup.getDefaultExportFromCjs(toRegexRange_1);
1135
+
1136
+ /*!
1137
+ * fill-range <https://github.com/jonschlinkert/fill-range>
1138
+ *
1139
+ * Copyright (c) 2014-present, Jon Schlinkert.
1140
+ * Licensed under the MIT License.
1141
+ */
1142
+
1143
+ const util = require$$2;
1144
+ const toRegexRange = toRegexRange_1;
1145
+
1146
+ const isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
1147
+
1148
+ const transform = toNumber => {
1149
+ return value => toNumber === true ? Number(value) : String(value);
1150
+ };
1151
+
1152
+ const isValidValue = value => {
1153
+ return typeof value === 'number' || (typeof value === 'string' && value !== '');
1154
+ };
1155
+
1156
+ const isNumber = num => Number.isInteger(+num);
1157
+
1158
+ const zeros = input => {
1159
+ let value = `${input}`;
1160
+ let index = -1;
1161
+ if (value[0] === '-') value = value.slice(1);
1162
+ if (value === '0') return false;
1163
+ while (value[++index] === '0');
1164
+ return index > 0;
1165
+ };
1166
+
1167
+ const stringify$3 = (start, end, options) => {
1168
+ if (typeof start === 'string' || typeof end === 'string') {
1169
+ return true;
1170
+ }
1171
+ return options.stringify === true;
1172
+ };
1173
+
1174
+ const pad = (input, maxLength, toNumber) => {
1175
+ if (maxLength > 0) {
1176
+ let dash = input[0] === '-' ? '-' : '';
1177
+ if (dash) input = input.slice(1);
1178
+ input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
1179
+ }
1180
+ if (toNumber === false) {
1181
+ return String(input);
1182
+ }
1183
+ return input;
1184
+ };
1185
+
1186
+ const toMaxLen = (input, maxLength) => {
1187
+ let negative = input[0] === '-' ? '-' : '';
1188
+ if (negative) {
1189
+ input = input.slice(1);
1190
+ maxLength--;
1191
+ }
1192
+ while (input.length < maxLength) input = '0' + input;
1193
+ return negative ? ('-' + input) : input;
1194
+ };
1195
+
1196
+ const toSequence = (parts, options) => {
1197
+ parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
1198
+ parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
1199
+
1200
+ let prefix = options.capture ? '' : '?:';
1201
+ let positives = '';
1202
+ let negatives = '';
1203
+ let result;
1204
+
1205
+ if (parts.positives.length) {
1206
+ positives = parts.positives.join('|');
1207
+ }
1208
+
1209
+ if (parts.negatives.length) {
1210
+ negatives = `-(${prefix}${parts.negatives.join('|')})`;
1211
+ }
1212
+
1213
+ if (positives && negatives) {
1214
+ result = `${positives}|${negatives}`;
1215
+ } else {
1216
+ result = positives || negatives;
1217
+ }
1218
+
1219
+ if (options.wrap) {
1220
+ return `(${prefix}${result})`;
1221
+ }
1222
+
1223
+ return result;
1224
+ };
1225
+
1226
+ const toRange = (a, b, isNumbers, options) => {
1227
+ if (isNumbers) {
1228
+ return toRegexRange(a, b, { wrap: false, ...options });
1229
+ }
1230
+
1231
+ let start = String.fromCharCode(a);
1232
+ if (a === b) return start;
1233
+
1234
+ let stop = String.fromCharCode(b);
1235
+ return `[${start}-${stop}]`;
1236
+ };
1237
+
1238
+ const toRegex = (start, end, options) => {
1239
+ if (Array.isArray(start)) {
1240
+ let wrap = options.wrap === true;
1241
+ let prefix = options.capture ? '' : '?:';
1242
+ return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
1243
+ }
1244
+ return toRegexRange(start, end, options);
1245
+ };
1246
+
1247
+ const rangeError = (...args) => {
1248
+ return new RangeError('Invalid range arguments: ' + util.inspect(...args));
1249
+ };
1250
+
1251
+ const invalidRange = (start, end, options) => {
1252
+ if (options.strictRanges === true) throw rangeError([start, end]);
1253
+ return [];
1254
+ };
1255
+
1256
+ const invalidStep = (step, options) => {
1257
+ if (options.strictRanges === true) {
1258
+ throw new TypeError(`Expected step "${step}" to be a number`);
1259
+ }
1260
+ return [];
1261
+ };
1262
+
1263
+ const fillNumbers = (start, end, step = 1, options = {}) => {
1264
+ let a = Number(start);
1265
+ let b = Number(end);
1266
+
1267
+ if (!Number.isInteger(a) || !Number.isInteger(b)) {
1268
+ if (options.strictRanges === true) throw rangeError([start, end]);
1269
+ return [];
1270
+ }
1271
+
1272
+ // fix negative zero
1273
+ if (a === 0) a = 0;
1274
+ if (b === 0) b = 0;
1275
+
1276
+ let descending = a > b;
1277
+ let startString = String(start);
1278
+ let endString = String(end);
1279
+ let stepString = String(step);
1280
+ step = Math.max(Math.abs(step), 1);
1281
+
1282
+ let padded = zeros(startString) || zeros(endString) || zeros(stepString);
1283
+ let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
1284
+ let toNumber = padded === false && stringify$3(start, end, options) === false;
1285
+ let format = options.transform || transform(toNumber);
1286
+
1287
+ if (options.toRegex && step === 1) {
1288
+ return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
1289
+ }
1290
+
1291
+ let parts = { negatives: [], positives: [] };
1292
+ let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
1293
+ let range = [];
1294
+ let index = 0;
1295
+
1296
+ while (descending ? a >= b : a <= b) {
1297
+ if (options.toRegex === true && step > 1) {
1298
+ push(a);
1299
+ } else {
1300
+ range.push(pad(format(a, index), maxLen, toNumber));
1301
+ }
1302
+ a = descending ? a - step : a + step;
1303
+ index++;
1304
+ }
1305
+
1306
+ if (options.toRegex === true) {
1307
+ return step > 1
1308
+ ? toSequence(parts, options)
1309
+ : toRegex(range, null, { wrap: false, ...options });
1310
+ }
1311
+
1312
+ return range;
1313
+ };
1314
+
1315
+ const fillLetters = (start, end, step = 1, options = {}) => {
1316
+ if ((!isNumber(start) && start.length > 1) || (!isNumber(end) && end.length > 1)) {
1317
+ return invalidRange(start, end, options);
1318
+ }
1319
+
1320
+
1321
+ let format = options.transform || (val => String.fromCharCode(val));
1322
+ let a = `${start}`.charCodeAt(0);
1323
+ let b = `${end}`.charCodeAt(0);
1324
+
1325
+ let descending = a > b;
1326
+ let min = Math.min(a, b);
1327
+ let max = Math.max(a, b);
1328
+
1329
+ if (options.toRegex && step === 1) {
1330
+ return toRange(min, max, false, options);
1331
+ }
1332
+
1333
+ let range = [];
1334
+ let index = 0;
1335
+
1336
+ while (descending ? a >= b : a <= b) {
1337
+ range.push(format(a, index));
1338
+ a = descending ? a - step : a + step;
1339
+ index++;
1340
+ }
1341
+
1342
+ if (options.toRegex === true) {
1343
+ return toRegex(range, null, { wrap: false, options });
1344
+ }
1345
+
1346
+ return range;
1347
+ };
1348
+
1349
+ const fill$2 = (start, end, step, options = {}) => {
1350
+ if (end == null && isValidValue(start)) {
1351
+ return [start];
1352
+ }
1353
+
1354
+ if (!isValidValue(start) || !isValidValue(end)) {
1355
+ return invalidRange(start, end, options);
1356
+ }
1357
+
1358
+ if (typeof step === 'function') {
1359
+ return fill$2(start, end, 1, { transform: step });
1360
+ }
1361
+
1362
+ if (isObject(step)) {
1363
+ return fill$2(start, end, 0, step);
1364
+ }
1365
+
1366
+ let opts = { ...options };
1367
+ if (opts.capture === true) opts.wrap = true;
1368
+ step = step || opts.step || 1;
1369
+
1370
+ if (!isNumber(step)) {
1371
+ if (step != null && !isObject(step)) return invalidStep(step, opts);
1372
+ return fill$2(start, end, 1, step);
1373
+ }
1374
+
1375
+ if (isNumber(start) && isNumber(end)) {
1376
+ return fillNumbers(start, end, step, opts);
1377
+ }
1378
+
1379
+ return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
1380
+ };
1381
+
1382
+ var fillRange = fill$2;
1383
+
1384
+ /*@__PURE__*/rollup.getDefaultExportFromCjs(fillRange);
1385
+
1386
+ const fill$1 = fillRange;
1387
+ const utils$1 = utils$3;
1388
+
1389
+ const compile$1 = (ast, options = {}) => {
1390
+ let walk = (node, parent = {}) => {
1391
+ let invalidBlock = utils$1.isInvalidBrace(parent);
1392
+ let invalidNode = node.invalid === true && options.escapeInvalid === true;
1393
+ let invalid = invalidBlock === true || invalidNode === true;
1394
+ let prefix = options.escapeInvalid === true ? '\\' : '';
1395
+ let output = '';
1396
+
1397
+ if (node.isOpen === true) {
1398
+ return prefix + node.value;
1399
+ }
1400
+ if (node.isClose === true) {
1401
+ return prefix + node.value;
1402
+ }
1403
+
1404
+ if (node.type === 'open') {
1405
+ return invalid ? (prefix + node.value) : '(';
1406
+ }
1407
+
1408
+ if (node.type === 'close') {
1409
+ return invalid ? (prefix + node.value) : ')';
1410
+ }
1411
+
1412
+ if (node.type === 'comma') {
1413
+ return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
1414
+ }
1415
+
1416
+ if (node.value) {
1417
+ return node.value;
1418
+ }
1419
+
1420
+ if (node.nodes && node.ranges > 0) {
1421
+ let args = utils$1.reduce(node.nodes);
1422
+ let range = fill$1(...args, { ...options, wrap: false, toRegex: true });
1423
+
1424
+ if (range.length !== 0) {
1425
+ return args.length > 1 && range.length > 1 ? `(${range})` : range;
1426
+ }
1427
+ }
1428
+
1429
+ if (node.nodes) {
1430
+ for (let child of node.nodes) {
1431
+ output += walk(child, node);
1432
+ }
1433
+ }
1434
+ return output;
1435
+ };
1436
+
1437
+ return walk(ast);
1438
+ };
1439
+
1440
+ var compile_1 = compile$1;
1441
+
1442
+ /*@__PURE__*/rollup.getDefaultExportFromCjs(compile_1);
1443
+
1444
+ const fill = fillRange;
1445
+ const stringify$2 = stringify$4;
1446
+ const utils = utils$3;
1447
+
1448
+ const append = (queue = '', stash = '', enclose = false) => {
1449
+ let result = [];
1450
+
1451
+ queue = [].concat(queue);
1452
+ stash = [].concat(stash);
1453
+
1454
+ if (!stash.length) return queue;
1455
+ if (!queue.length) {
1456
+ return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash;
1457
+ }
1458
+
1459
+ for (let item of queue) {
1460
+ if (Array.isArray(item)) {
1461
+ for (let value of item) {
1462
+ result.push(append(value, stash, enclose));
1463
+ }
1464
+ } else {
1465
+ for (let ele of stash) {
1466
+ if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
1467
+ result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele));
1468
+ }
1469
+ }
1470
+ }
1471
+ return utils.flatten(result);
1472
+ };
1473
+
1474
+ const expand$1 = (ast, options = {}) => {
1475
+ let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
1476
+
1477
+ let walk = (node, parent = {}) => {
1478
+ node.queue = [];
1479
+
1480
+ let p = parent;
1481
+ let q = parent.queue;
1482
+
1483
+ while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
1484
+ p = p.parent;
1485
+ q = p.queue;
1486
+ }
1487
+
1488
+ if (node.invalid || node.dollar) {
1489
+ q.push(append(q.pop(), stringify$2(node, options)));
1490
+ return;
1491
+ }
1492
+
1493
+ if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
1494
+ q.push(append(q.pop(), ['{}']));
1495
+ return;
1496
+ }
1497
+
1498
+ if (node.nodes && node.ranges > 0) {
1499
+ let args = utils.reduce(node.nodes);
1500
+
1501
+ if (utils.exceedsLimit(...args, options.step, rangeLimit)) {
1502
+ throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
1503
+ }
1504
+
1505
+ let range = fill(...args, options);
1506
+ if (range.length === 0) {
1507
+ range = stringify$2(node, options);
1508
+ }
1509
+
1510
+ q.push(append(q.pop(), range));
1511
+ node.nodes = [];
1512
+ return;
1513
+ }
1514
+
1515
+ let enclose = utils.encloseBrace(node);
1516
+ let queue = node.queue;
1517
+ let block = node;
1518
+
1519
+ while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
1520
+ block = block.parent;
1521
+ queue = block.queue;
1522
+ }
1523
+
1524
+ for (let i = 0; i < node.nodes.length; i++) {
1525
+ let child = node.nodes[i];
1526
+
1527
+ if (child.type === 'comma' && node.type === 'brace') {
1528
+ if (i === 1) queue.push('');
1529
+ queue.push('');
1530
+ continue;
1531
+ }
1532
+
1533
+ if (child.type === 'close') {
1534
+ q.push(append(q.pop(), queue, enclose));
1535
+ continue;
1536
+ }
1537
+
1538
+ if (child.value && child.type !== 'open') {
1539
+ queue.push(append(queue.pop(), child.value));
1540
+ continue;
1541
+ }
1542
+
1543
+ if (child.nodes) {
1544
+ walk(child, node);
1545
+ }
1546
+ }
1547
+
1548
+ return queue;
1549
+ };
1550
+
1551
+ return utils.flatten(walk(ast));
1552
+ };
1553
+
1554
+ var expand_1 = expand$1;
1555
+
1556
+ /*@__PURE__*/rollup.getDefaultExportFromCjs(expand_1);
1557
+
1558
+ var constants$1 = {
1559
+ MAX_LENGTH: 1024 * 64,
1560
+
1561
+ // Digits
1562
+ CHAR_0: '0', /* 0 */
1563
+ CHAR_9: '9', /* 9 */
1564
+
1565
+ // Alphabet chars.
1566
+ CHAR_UPPERCASE_A: 'A', /* A */
1567
+ CHAR_LOWERCASE_A: 'a', /* a */
1568
+ CHAR_UPPERCASE_Z: 'Z', /* Z */
1569
+ CHAR_LOWERCASE_Z: 'z', /* z */
1570
+
1571
+ CHAR_LEFT_PARENTHESES: '(', /* ( */
1572
+ CHAR_RIGHT_PARENTHESES: ')', /* ) */
1573
+
1574
+ CHAR_ASTERISK: '*', /* * */
1575
+
1576
+ // Non-alphabetic chars.
1577
+ CHAR_AMPERSAND: '&', /* & */
1578
+ CHAR_AT: '@', /* @ */
1579
+ CHAR_BACKSLASH: '\\', /* \ */
1580
+ CHAR_BACKTICK: '`', /* ` */
1581
+ CHAR_CARRIAGE_RETURN: '\r', /* \r */
1582
+ CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */
1583
+ CHAR_COLON: ':', /* : */
1584
+ CHAR_COMMA: ',', /* , */
1585
+ CHAR_DOLLAR: '$', /* . */
1586
+ CHAR_DOT: '.', /* . */
1587
+ CHAR_DOUBLE_QUOTE: '"', /* " */
1588
+ CHAR_EQUAL: '=', /* = */
1589
+ CHAR_EXCLAMATION_MARK: '!', /* ! */
1590
+ CHAR_FORM_FEED: '\f', /* \f */
1591
+ CHAR_FORWARD_SLASH: '/', /* / */
1592
+ CHAR_HASH: '#', /* # */
1593
+ CHAR_HYPHEN_MINUS: '-', /* - */
1594
+ CHAR_LEFT_ANGLE_BRACKET: '<', /* < */
1595
+ CHAR_LEFT_CURLY_BRACE: '{', /* { */
1596
+ CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
1597
+ CHAR_LINE_FEED: '\n', /* \n */
1598
+ CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
1599
+ CHAR_PERCENT: '%', /* % */
1600
+ CHAR_PLUS: '+', /* + */
1601
+ CHAR_QUESTION_MARK: '?', /* ? */
1602
+ CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */
1603
+ CHAR_RIGHT_CURLY_BRACE: '}', /* } */
1604
+ CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
1605
+ CHAR_SEMICOLON: ';', /* ; */
1606
+ CHAR_SINGLE_QUOTE: '\'', /* ' */
1607
+ CHAR_SPACE: ' ', /* */
1608
+ CHAR_TAB: '\t', /* \t */
1609
+ CHAR_UNDERSCORE: '_', /* _ */
1610
+ CHAR_VERTICAL_LINE: '|', /* | */
1611
+ CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
1612
+ };
1613
+
1614
+ /*@__PURE__*/rollup.getDefaultExportFromCjs(constants$1);
1615
+
1616
+ const stringify$1 = stringify$4;
1617
+
1618
+ /**
1619
+ * Constants
1620
+ */
1621
+
1622
+ const {
1623
+ MAX_LENGTH,
1624
+ CHAR_BACKSLASH, /* \ */
1625
+ CHAR_BACKTICK, /* ` */
1626
+ CHAR_COMMA, /* , */
1627
+ CHAR_DOT, /* . */
1628
+ CHAR_LEFT_PARENTHESES, /* ( */
1629
+ CHAR_RIGHT_PARENTHESES, /* ) */
1630
+ CHAR_LEFT_CURLY_BRACE, /* { */
1631
+ CHAR_RIGHT_CURLY_BRACE, /* } */
1632
+ CHAR_LEFT_SQUARE_BRACKET, /* [ */
1633
+ CHAR_RIGHT_SQUARE_BRACKET, /* ] */
1634
+ CHAR_DOUBLE_QUOTE, /* " */
1635
+ CHAR_SINGLE_QUOTE, /* ' */
1636
+ CHAR_NO_BREAK_SPACE,
1637
+ CHAR_ZERO_WIDTH_NOBREAK_SPACE
1638
+ } = constants$1;
1639
+
1640
+ /**
1641
+ * parse
1642
+ */
1643
+
1644
+ const parse$1 = (input, options = {}) => {
1645
+ if (typeof input !== 'string') {
1646
+ throw new TypeError('Expected a string');
1647
+ }
1648
+
1649
+ let opts = options || {};
1650
+ let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
1651
+ if (input.length > max) {
1652
+ throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
1653
+ }
1654
+
1655
+ let ast = { type: 'root', input, nodes: [] };
1656
+ let stack = [ast];
1657
+ let block = ast;
1658
+ let prev = ast;
1659
+ let brackets = 0;
1660
+ let length = input.length;
1661
+ let index = 0;
1662
+ let depth = 0;
1663
+ let value;
1664
+
1665
+ /**
1666
+ * Helpers
1667
+ */
1668
+
1669
+ const advance = () => input[index++];
1670
+ const push = node => {
1671
+ if (node.type === 'text' && prev.type === 'dot') {
1672
+ prev.type = 'text';
1673
+ }
1674
+
1675
+ if (prev && prev.type === 'text' && node.type === 'text') {
1676
+ prev.value += node.value;
1677
+ return;
1678
+ }
1679
+
1680
+ block.nodes.push(node);
1681
+ node.parent = block;
1682
+ node.prev = prev;
1683
+ prev = node;
1684
+ return node;
1685
+ };
1686
+
1687
+ push({ type: 'bos' });
1688
+
1689
+ while (index < length) {
1690
+ block = stack[stack.length - 1];
1691
+ value = advance();
1692
+
1693
+ /**
1694
+ * Invalid chars
1695
+ */
1696
+
1697
+ if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
1698
+ continue;
1699
+ }
1700
+
1701
+ /**
1702
+ * Escaped chars
1703
+ */
1704
+
1705
+ if (value === CHAR_BACKSLASH) {
1706
+ push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
1707
+ continue;
1708
+ }
1709
+
1710
+ /**
1711
+ * Right square bracket (literal): ']'
1712
+ */
1713
+
1714
+ if (value === CHAR_RIGHT_SQUARE_BRACKET) {
1715
+ push({ type: 'text', value: '\\' + value });
1716
+ continue;
1717
+ }
1718
+
1719
+ /**
1720
+ * Left square bracket: '['
1721
+ */
1722
+
1723
+ if (value === CHAR_LEFT_SQUARE_BRACKET) {
1724
+ brackets++;
1725
+ let next;
1726
+
1727
+ while (index < length && (next = advance())) {
1728
+ value += next;
1729
+
1730
+ if (next === CHAR_LEFT_SQUARE_BRACKET) {
1731
+ brackets++;
1732
+ continue;
1733
+ }
1734
+
1735
+ if (next === CHAR_BACKSLASH) {
1736
+ value += advance();
1737
+ continue;
1738
+ }
1739
+
1740
+ if (next === CHAR_RIGHT_SQUARE_BRACKET) {
1741
+ brackets--;
1742
+
1743
+ if (brackets === 0) {
1744
+ break;
1745
+ }
1746
+ }
1747
+ }
1748
+
1749
+ push({ type: 'text', value });
1750
+ continue;
1751
+ }
1752
+
1753
+ /**
1754
+ * Parentheses
1755
+ */
1756
+
1757
+ if (value === CHAR_LEFT_PARENTHESES) {
1758
+ block = push({ type: 'paren', nodes: [] });
1759
+ stack.push(block);
1760
+ push({ type: 'text', value });
1761
+ continue;
1762
+ }
1763
+
1764
+ if (value === CHAR_RIGHT_PARENTHESES) {
1765
+ if (block.type !== 'paren') {
1766
+ push({ type: 'text', value });
1767
+ continue;
1768
+ }
1769
+ block = stack.pop();
1770
+ push({ type: 'text', value });
1771
+ block = stack[stack.length - 1];
1772
+ continue;
1773
+ }
1774
+
1775
+ /**
1776
+ * Quotes: '|"|`
1777
+ */
1778
+
1779
+ if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
1780
+ let open = value;
1781
+ let next;
1782
+
1783
+ if (options.keepQuotes !== true) {
1784
+ value = '';
1785
+ }
1786
+
1787
+ while (index < length && (next = advance())) {
1788
+ if (next === CHAR_BACKSLASH) {
1789
+ value += next + advance();
1790
+ continue;
1791
+ }
1792
+
1793
+ if (next === open) {
1794
+ if (options.keepQuotes === true) value += next;
1795
+ break;
1796
+ }
1797
+
1798
+ value += next;
1799
+ }
1800
+
1801
+ push({ type: 'text', value });
1802
+ continue;
1803
+ }
1804
+
1805
+ /**
1806
+ * Left curly brace: '{'
1807
+ */
1808
+
1809
+ if (value === CHAR_LEFT_CURLY_BRACE) {
1810
+ depth++;
1811
+
1812
+ let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
1813
+ let brace = {
1814
+ type: 'brace',
1815
+ open: true,
1816
+ close: false,
1817
+ dollar,
1818
+ depth,
1819
+ commas: 0,
1820
+ ranges: 0,
1821
+ nodes: []
1822
+ };
1823
+
1824
+ block = push(brace);
1825
+ stack.push(block);
1826
+ push({ type: 'open', value });
1827
+ continue;
1828
+ }
1829
+
1830
+ /**
1831
+ * Right curly brace: '}'
1832
+ */
1833
+
1834
+ if (value === CHAR_RIGHT_CURLY_BRACE) {
1835
+ if (block.type !== 'brace') {
1836
+ push({ type: 'text', value });
1837
+ continue;
1838
+ }
1839
+
1840
+ let type = 'close';
1841
+ block = stack.pop();
1842
+ block.close = true;
1843
+
1844
+ push({ type, value });
1845
+ depth--;
1846
+
1847
+ block = stack[stack.length - 1];
1848
+ continue;
1849
+ }
1850
+
1851
+ /**
1852
+ * Comma: ','
1853
+ */
1854
+
1855
+ if (value === CHAR_COMMA && depth > 0) {
1856
+ if (block.ranges > 0) {
1857
+ block.ranges = 0;
1858
+ let open = block.nodes.shift();
1859
+ block.nodes = [open, { type: 'text', value: stringify$1(block) }];
1860
+ }
1861
+
1862
+ push({ type: 'comma', value });
1863
+ block.commas++;
1864
+ continue;
1865
+ }
1866
+
1867
+ /**
1868
+ * Dot: '.'
1869
+ */
1870
+
1871
+ if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
1872
+ let siblings = block.nodes;
1873
+
1874
+ if (depth === 0 || siblings.length === 0) {
1875
+ push({ type: 'text', value });
1876
+ continue;
1877
+ }
1878
+
1879
+ if (prev.type === 'dot') {
1880
+ block.range = [];
1881
+ prev.value += value;
1882
+ prev.type = 'range';
1883
+
1884
+ if (block.nodes.length !== 3 && block.nodes.length !== 5) {
1885
+ block.invalid = true;
1886
+ block.ranges = 0;
1887
+ prev.type = 'text';
1888
+ continue;
1889
+ }
1890
+
1891
+ block.ranges++;
1892
+ block.args = [];
1893
+ continue;
1894
+ }
1895
+
1896
+ if (prev.type === 'range') {
1897
+ siblings.pop();
1898
+
1899
+ let before = siblings[siblings.length - 1];
1900
+ before.value += prev.value + value;
1901
+ prev = before;
1902
+ block.ranges--;
1903
+ continue;
1904
+ }
1905
+
1906
+ push({ type: 'dot', value });
1907
+ continue;
1908
+ }
1909
+
1910
+ /**
1911
+ * Text
1912
+ */
1913
+
1914
+ push({ type: 'text', value });
1915
+ }
1916
+
1917
+ // Mark imbalanced braces and brackets as invalid
1918
+ do {
1919
+ block = stack.pop();
1920
+
1921
+ if (block.type !== 'root') {
1922
+ block.nodes.forEach(node => {
1923
+ if (!node.nodes) {
1924
+ if (node.type === 'open') node.isOpen = true;
1925
+ if (node.type === 'close') node.isClose = true;
1926
+ if (!node.nodes) node.type = 'text';
1927
+ node.invalid = true;
1928
+ }
1929
+ });
1930
+
1931
+ // get the location of the block on parent.nodes (block's siblings)
1932
+ let parent = stack[stack.length - 1];
1933
+ let index = parent.nodes.indexOf(block);
1934
+ // replace the (invalid) block with it's nodes
1935
+ parent.nodes.splice(index, 1, ...block.nodes);
1936
+ }
1937
+ } while (stack.length > 0);
1938
+
1939
+ push({ type: 'eos' });
1940
+ return ast;
1941
+ };
1942
+
1943
+ var parse_1 = parse$1;
1944
+
1945
+ /*@__PURE__*/rollup.getDefaultExportFromCjs(parse_1);
1946
+
1947
+ const stringify = stringify$4;
1948
+ const compile = compile_1;
1949
+ const expand = expand_1;
1950
+ const parse = parse_1;
1951
+
1952
+ /**
1953
+ * Expand the given pattern or create a regex-compatible string.
1954
+ *
1955
+ * ```js
1956
+ * const braces = require('braces');
1957
+ * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
1958
+ * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
1959
+ * ```
1960
+ * @param {String} `str`
1961
+ * @param {Object} `options`
1962
+ * @return {String}
1963
+ * @api public
1964
+ */
1965
+
1966
+ const braces$1 = (input, options = {}) => {
1967
+ let output = [];
1968
+
1969
+ if (Array.isArray(input)) {
1970
+ for (let pattern of input) {
1971
+ let result = braces$1.create(pattern, options);
1972
+ if (Array.isArray(result)) {
1973
+ output.push(...result);
1974
+ } else {
1975
+ output.push(result);
1976
+ }
1977
+ }
1978
+ } else {
1979
+ output = [].concat(braces$1.create(input, options));
1980
+ }
1981
+
1982
+ if (options && options.expand === true && options.nodupes === true) {
1983
+ output = [...new Set(output)];
1984
+ }
1985
+ return output;
1986
+ };
1987
+
1988
+ /**
1989
+ * Parse the given `str` with the given `options`.
1990
+ *
1991
+ * ```js
1992
+ * // braces.parse(pattern, [, options]);
1993
+ * const ast = braces.parse('a/{b,c}/d');
1994
+ * console.log(ast);
1995
+ * ```
1996
+ * @param {String} pattern Brace pattern to parse
1997
+ * @param {Object} options
1998
+ * @return {Object} Returns an AST
1999
+ * @api public
2000
+ */
2001
+
2002
+ braces$1.parse = (input, options = {}) => parse(input, options);
2003
+
2004
+ /**
2005
+ * Creates a braces string from an AST, or an AST node.
2006
+ *
2007
+ * ```js
2008
+ * const braces = require('braces');
2009
+ * let ast = braces.parse('foo/{a,b}/bar');
2010
+ * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
2011
+ * ```
2012
+ * @param {String} `input` Brace pattern or AST.
2013
+ * @param {Object} `options`
2014
+ * @return {Array} Returns an array of expanded values.
2015
+ * @api public
2016
+ */
2017
+
2018
+ braces$1.stringify = (input, options = {}) => {
2019
+ if (typeof input === 'string') {
2020
+ return stringify(braces$1.parse(input, options), options);
2021
+ }
2022
+ return stringify(input, options);
2023
+ };
2024
+
2025
+ /**
2026
+ * Compiles a brace pattern into a regex-compatible, optimized string.
2027
+ * This method is called by the main [braces](#braces) function by default.
2028
+ *
2029
+ * ```js
2030
+ * const braces = require('braces');
2031
+ * console.log(braces.compile('a/{b,c}/d'));
2032
+ * //=> ['a/(b|c)/d']
2033
+ * ```
2034
+ * @param {String} `input` Brace pattern or AST.
2035
+ * @param {Object} `options`
2036
+ * @return {Array} Returns an array of expanded values.
2037
+ * @api public
2038
+ */
2039
+
2040
+ braces$1.compile = (input, options = {}) => {
2041
+ if (typeof input === 'string') {
2042
+ input = braces$1.parse(input, options);
2043
+ }
2044
+ return compile(input, options);
2045
+ };
2046
+
2047
+ /**
2048
+ * Expands a brace pattern into an array. This method is called by the
2049
+ * main [braces](#braces) function when `options.expand` is true. Before
2050
+ * using this method it's recommended that you read the [performance notes](#performance))
2051
+ * and advantages of using [.compile](#compile) instead.
2052
+ *
2053
+ * ```js
2054
+ * const braces = require('braces');
2055
+ * console.log(braces.expand('a/{b,c}/d'));
2056
+ * //=> ['a/b/d', 'a/c/d'];
2057
+ * ```
2058
+ * @param {String} `pattern` Brace pattern
2059
+ * @param {Object} `options`
2060
+ * @return {Array} Returns an array of expanded values.
2061
+ * @api public
2062
+ */
2063
+
2064
+ braces$1.expand = (input, options = {}) => {
2065
+ if (typeof input === 'string') {
2066
+ input = braces$1.parse(input, options);
2067
+ }
2068
+
2069
+ let result = expand(input, options);
2070
+
2071
+ // filter out empty strings if specified
2072
+ if (options.noempty === true) {
2073
+ result = result.filter(Boolean);
2074
+ }
2075
+
2076
+ // filter out duplicates if specified
2077
+ if (options.nodupes === true) {
2078
+ result = [...new Set(result)];
2079
+ }
2080
+
2081
+ return result;
2082
+ };
2083
+
2084
+ /**
2085
+ * Processes a brace pattern and returns either an expanded array
2086
+ * (if `options.expand` is true), a highly optimized regex-compatible string.
2087
+ * This method is called by the main [braces](#braces) function.
2088
+ *
2089
+ * ```js
2090
+ * const braces = require('braces');
2091
+ * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
2092
+ * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
2093
+ * ```
2094
+ * @param {String} `pattern` Brace pattern
2095
+ * @param {Object} `options`
2096
+ * @return {Array} Returns an array of expanded values.
2097
+ * @api public
2098
+ */
2099
+
2100
+ braces$1.create = (input, options = {}) => {
2101
+ if (input === '' || input.length < 3) {
2102
+ return [input];
2103
+ }
2104
+
2105
+ return options.expand !== true
2106
+ ? braces$1.compile(input, options)
2107
+ : braces$1.expand(input, options);
2108
+ };
2109
+
2110
+ /**
2111
+ * Expose "braces"
2112
+ */
2113
+
2114
+ var braces_1 = braces$1;
2115
+
2116
+ /*@__PURE__*/rollup.getDefaultExportFromCjs(braces_1);
2117
+
2118
+ const require$$0 = [
2119
+ "3dm",
2120
+ "3ds",
2121
+ "3g2",
2122
+ "3gp",
2123
+ "7z",
2124
+ "a",
2125
+ "aac",
2126
+ "adp",
2127
+ "ai",
2128
+ "aif",
2129
+ "aiff",
2130
+ "alz",
2131
+ "ape",
2132
+ "apk",
2133
+ "appimage",
2134
+ "ar",
2135
+ "arj",
2136
+ "asf",
2137
+ "au",
2138
+ "avi",
2139
+ "bak",
2140
+ "baml",
2141
+ "bh",
2142
+ "bin",
2143
+ "bk",
2144
+ "bmp",
2145
+ "btif",
2146
+ "bz2",
2147
+ "bzip2",
2148
+ "cab",
2149
+ "caf",
2150
+ "cgm",
2151
+ "class",
2152
+ "cmx",
2153
+ "cpio",
2154
+ "cr2",
2155
+ "cur",
2156
+ "dat",
2157
+ "dcm",
2158
+ "deb",
2159
+ "dex",
2160
+ "djvu",
2161
+ "dll",
2162
+ "dmg",
2163
+ "dng",
2164
+ "doc",
2165
+ "docm",
2166
+ "docx",
2167
+ "dot",
2168
+ "dotm",
2169
+ "dra",
2170
+ "DS_Store",
2171
+ "dsk",
2172
+ "dts",
2173
+ "dtshd",
2174
+ "dvb",
2175
+ "dwg",
2176
+ "dxf",
2177
+ "ecelp4800",
2178
+ "ecelp7470",
2179
+ "ecelp9600",
2180
+ "egg",
2181
+ "eol",
2182
+ "eot",
2183
+ "epub",
2184
+ "exe",
2185
+ "f4v",
2186
+ "fbs",
2187
+ "fh",
2188
+ "fla",
2189
+ "flac",
2190
+ "flatpak",
2191
+ "fli",
2192
+ "flv",
2193
+ "fpx",
2194
+ "fst",
2195
+ "fvt",
2196
+ "g3",
2197
+ "gh",
2198
+ "gif",
2199
+ "graffle",
2200
+ "gz",
2201
+ "gzip",
2202
+ "h261",
2203
+ "h263",
2204
+ "h264",
2205
+ "icns",
2206
+ "ico",
2207
+ "ief",
2208
+ "img",
2209
+ "ipa",
2210
+ "iso",
2211
+ "jar",
2212
+ "jpeg",
2213
+ "jpg",
2214
+ "jpgv",
2215
+ "jpm",
2216
+ "jxr",
2217
+ "key",
2218
+ "ktx",
2219
+ "lha",
2220
+ "lib",
2221
+ "lvp",
2222
+ "lz",
2223
+ "lzh",
2224
+ "lzma",
2225
+ "lzo",
2226
+ "m3u",
2227
+ "m4a",
2228
+ "m4v",
2229
+ "mar",
2230
+ "mdi",
2231
+ "mht",
2232
+ "mid",
2233
+ "midi",
2234
+ "mj2",
2235
+ "mka",
2236
+ "mkv",
2237
+ "mmr",
2238
+ "mng",
2239
+ "mobi",
2240
+ "mov",
2241
+ "movie",
2242
+ "mp3",
2243
+ "mp4",
2244
+ "mp4a",
2245
+ "mpeg",
2246
+ "mpg",
2247
+ "mpga",
2248
+ "mxu",
2249
+ "nef",
2250
+ "npx",
2251
+ "numbers",
2252
+ "nupkg",
2253
+ "o",
2254
+ "odp",
2255
+ "ods",
2256
+ "odt",
2257
+ "oga",
2258
+ "ogg",
2259
+ "ogv",
2260
+ "otf",
2261
+ "ott",
2262
+ "pages",
2263
+ "pbm",
2264
+ "pcx",
2265
+ "pdb",
2266
+ "pdf",
2267
+ "pea",
2268
+ "pgm",
2269
+ "pic",
2270
+ "png",
2271
+ "pnm",
2272
+ "pot",
2273
+ "potm",
2274
+ "potx",
2275
+ "ppa",
2276
+ "ppam",
2277
+ "ppm",
2278
+ "pps",
2279
+ "ppsm",
2280
+ "ppsx",
2281
+ "ppt",
2282
+ "pptm",
2283
+ "pptx",
2284
+ "psd",
2285
+ "pya",
2286
+ "pyc",
2287
+ "pyo",
2288
+ "pyv",
2289
+ "qt",
2290
+ "rar",
2291
+ "ras",
2292
+ "raw",
2293
+ "resources",
2294
+ "rgb",
2295
+ "rip",
2296
+ "rlc",
2297
+ "rmf",
2298
+ "rmvb",
2299
+ "rpm",
2300
+ "rtf",
2301
+ "rz",
2302
+ "s3m",
2303
+ "s7z",
2304
+ "scpt",
2305
+ "sgi",
2306
+ "shar",
2307
+ "snap",
2308
+ "sil",
2309
+ "sketch",
2310
+ "slk",
2311
+ "smv",
2312
+ "snk",
2313
+ "so",
2314
+ "stl",
2315
+ "suo",
2316
+ "sub",
2317
+ "swf",
2318
+ "tar",
2319
+ "tbz",
2320
+ "tbz2",
2321
+ "tga",
2322
+ "tgz",
2323
+ "thmx",
2324
+ "tif",
2325
+ "tiff",
2326
+ "tlz",
2327
+ "ttc",
2328
+ "ttf",
2329
+ "txz",
2330
+ "udf",
2331
+ "uvh",
2332
+ "uvi",
2333
+ "uvm",
2334
+ "uvp",
2335
+ "uvs",
2336
+ "uvu",
2337
+ "viv",
2338
+ "vob",
2339
+ "war",
2340
+ "wav",
2341
+ "wax",
2342
+ "wbmp",
2343
+ "wdp",
2344
+ "weba",
2345
+ "webm",
2346
+ "webp",
2347
+ "whl",
2348
+ "wim",
2349
+ "wm",
2350
+ "wma",
2351
+ "wmv",
2352
+ "wmx",
2353
+ "woff",
2354
+ "woff2",
2355
+ "wrm",
2356
+ "wvx",
2357
+ "xbm",
2358
+ "xif",
2359
+ "xla",
2360
+ "xlam",
2361
+ "xls",
2362
+ "xlsb",
2363
+ "xlsm",
2364
+ "xlsx",
2365
+ "xlt",
2366
+ "xltm",
2367
+ "xltx",
2368
+ "xm",
2369
+ "xmind",
2370
+ "xpi",
2371
+ "xpm",
2372
+ "xwd",
2373
+ "xz",
2374
+ "z",
2375
+ "zip",
2376
+ "zipx"
2377
+ ];
2378
+
2379
+ var binaryExtensions$1 = require$$0;
2380
+
2381
+ /*@__PURE__*/rollup.getDefaultExportFromCjs(binaryExtensions$1);
2382
+
2383
+ const path = require$$0$2;
2384
+ const binaryExtensions = binaryExtensions$1;
2385
+
2386
+ const extensions = new Set(binaryExtensions);
2387
+
2388
+ var isBinaryPath$1 = filePath => extensions.has(path.extname(filePath).slice(1).toLowerCase());
2389
+
2390
+ /*@__PURE__*/rollup.getDefaultExportFromCjs(isBinaryPath$1);
2391
+
2392
+ var constants = {};
2393
+
2394
+ (function (exports) {
2395
+
2396
+ const {sep} = require$$0$2;
2397
+ const {platform} = process;
2398
+ const os = require$$2$1;
2399
+
2400
+ exports.EV_ALL = 'all';
2401
+ exports.EV_READY = 'ready';
2402
+ exports.EV_ADD = 'add';
2403
+ exports.EV_CHANGE = 'change';
2404
+ exports.EV_ADD_DIR = 'addDir';
2405
+ exports.EV_UNLINK = 'unlink';
2406
+ exports.EV_UNLINK_DIR = 'unlinkDir';
2407
+ exports.EV_RAW = 'raw';
2408
+ exports.EV_ERROR = 'error';
2409
+
2410
+ exports.STR_DATA = 'data';
2411
+ exports.STR_END = 'end';
2412
+ exports.STR_CLOSE = 'close';
2413
+
2414
+ exports.FSEVENT_CREATED = 'created';
2415
+ exports.FSEVENT_MODIFIED = 'modified';
2416
+ exports.FSEVENT_DELETED = 'deleted';
2417
+ exports.FSEVENT_MOVED = 'moved';
2418
+ exports.FSEVENT_CLONED = 'cloned';
2419
+ exports.FSEVENT_UNKNOWN = 'unknown';
2420
+ exports.FSEVENT_TYPE_FILE = 'file';
2421
+ exports.FSEVENT_TYPE_DIRECTORY = 'directory';
2422
+ exports.FSEVENT_TYPE_SYMLINK = 'symlink';
2423
+
2424
+ exports.KEY_LISTENERS = 'listeners';
2425
+ exports.KEY_ERR = 'errHandlers';
2426
+ exports.KEY_RAW = 'rawEmitters';
2427
+ exports.HANDLER_KEYS = [exports.KEY_LISTENERS, exports.KEY_ERR, exports.KEY_RAW];
2428
+
2429
+ exports.DOT_SLASH = `.${sep}`;
2430
+
2431
+ exports.BACK_SLASH_RE = /\\/g;
2432
+ exports.DOUBLE_SLASH_RE = /\/\//;
2433
+ exports.SLASH_OR_BACK_SLASH_RE = /[/\\]/;
2434
+ exports.DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
2435
+ exports.REPLACER_RE = /^\.[/\\]/;
2436
+
2437
+ exports.SLASH = '/';
2438
+ exports.SLASH_SLASH = '//';
2439
+ exports.BRACE_START = '{';
2440
+ exports.BANG = '!';
2441
+ exports.ONE_DOT = '.';
2442
+ exports.TWO_DOTS = '..';
2443
+ exports.STAR = '*';
2444
+ exports.GLOBSTAR = '**';
2445
+ exports.ROOT_GLOBSTAR = '/**/*';
2446
+ exports.SLASH_GLOBSTAR = '/**';
2447
+ exports.DIR_SUFFIX = 'Dir';
2448
+ exports.ANYMATCH_OPTS = {dot: true};
2449
+ exports.STRING_TYPE = 'string';
2450
+ exports.FUNCTION_TYPE = 'function';
2451
+ exports.EMPTY_STR = '';
2452
+ exports.EMPTY_FN = () => {};
2453
+ exports.IDENTITY_FN = val => val;
2454
+
2455
+ exports.isWindows = platform === 'win32';
2456
+ exports.isMacos = platform === 'darwin';
2457
+ exports.isLinux = platform === 'linux';
2458
+ exports.isIBMi = os.type() === 'OS400';
2459
+ } (constants));
2460
+
2461
+ /*@__PURE__*/rollup.getDefaultExportFromCjs(constants);
2462
+
2463
+ const fs$2 = require$$0$1;
2464
+ const sysPath$2 = require$$0$2;
2465
+ const { promisify: promisify$2 } = require$$2;
2466
+ const isBinaryPath = isBinaryPath$1;
2467
+ const {
2468
+ isWindows: isWindows$1,
2469
+ isLinux,
2470
+ EMPTY_FN: EMPTY_FN$2,
2471
+ EMPTY_STR: EMPTY_STR$1,
2472
+ KEY_LISTENERS,
2473
+ KEY_ERR,
2474
+ KEY_RAW,
2475
+ HANDLER_KEYS,
2476
+ EV_CHANGE: EV_CHANGE$2,
2477
+ EV_ADD: EV_ADD$2,
2478
+ EV_ADD_DIR: EV_ADD_DIR$2,
2479
+ EV_ERROR: EV_ERROR$2,
2480
+ STR_DATA: STR_DATA$1,
2481
+ STR_END: STR_END$2,
2482
+ BRACE_START: BRACE_START$1,
2483
+ STAR
2484
+ } = constants;
2485
+
2486
+ const THROTTLE_MODE_WATCH = 'watch';
2487
+
2488
+ const open = promisify$2(fs$2.open);
2489
+ const stat$2 = promisify$2(fs$2.stat);
2490
+ const lstat$1 = promisify$2(fs$2.lstat);
2491
+ const close = promisify$2(fs$2.close);
2492
+ const fsrealpath = promisify$2(fs$2.realpath);
2493
+
2494
+ const statMethods$1 = { lstat: lstat$1, stat: stat$2 };
2495
+
2496
+ // TODO: emit errors properly. Example: EMFILE on Macos.
2497
+ const foreach = (val, fn) => {
2498
+ if (val instanceof Set) {
2499
+ val.forEach(fn);
2500
+ } else {
2501
+ fn(val);
2502
+ }
2503
+ };
2504
+
2505
+ const addAndConvert = (main, prop, item) => {
2506
+ let container = main[prop];
2507
+ if (!(container instanceof Set)) {
2508
+ main[prop] = container = new Set([container]);
2509
+ }
2510
+ container.add(item);
2511
+ };
2512
+
2513
+ const clearItem = cont => key => {
2514
+ const set = cont[key];
2515
+ if (set instanceof Set) {
2516
+ set.clear();
2517
+ } else {
2518
+ delete cont[key];
2519
+ }
2520
+ };
2521
+
2522
+ const delFromSet = (main, prop, item) => {
2523
+ const container = main[prop];
2524
+ if (container instanceof Set) {
2525
+ container.delete(item);
2526
+ } else if (container === item) {
2527
+ delete main[prop];
2528
+ }
2529
+ };
2530
+
2531
+ const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
2532
+
2533
+ /**
2534
+ * @typedef {String} Path
2535
+ */
2536
+
2537
+ // fs_watch helpers
2538
+
2539
+ // object to hold per-process fs_watch instances
2540
+ // (may be shared across chokidar FSWatcher instances)
2541
+
2542
+ /**
2543
+ * @typedef {Object} FsWatchContainer
2544
+ * @property {Set} listeners
2545
+ * @property {Set} errHandlers
2546
+ * @property {Set} rawEmitters
2547
+ * @property {fs.FSWatcher=} watcher
2548
+ * @property {Boolean=} watcherUnusable
2549
+ */
2550
+
2551
+ /**
2552
+ * @type {Map<String,FsWatchContainer>}
2553
+ */
2554
+ const FsWatchInstances = new Map();
2555
+
2556
+ /**
2557
+ * Instantiates the fs_watch interface
2558
+ * @param {String} path to be watched
2559
+ * @param {Object} options to be passed to fs_watch
2560
+ * @param {Function} listener main event handler
2561
+ * @param {Function} errHandler emits info about errors
2562
+ * @param {Function} emitRaw emits raw event data
2563
+ * @returns {fs.FSWatcher} new fsevents instance
2564
+ */
2565
+ function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
2566
+ const handleEvent = (rawEvent, evPath) => {
2567
+ listener(path);
2568
+ emitRaw(rawEvent, evPath, {watchedPath: path});
2569
+
2570
+ // emit based on events occurring for files from a directory's watcher in
2571
+ // case the file's watcher misses it (and rely on throttling to de-dupe)
2572
+ if (evPath && path !== evPath) {
2573
+ fsWatchBroadcast(
2574
+ sysPath$2.resolve(path, evPath), KEY_LISTENERS, sysPath$2.join(path, evPath)
2575
+ );
2576
+ }
2577
+ };
2578
+ try {
2579
+ return fs$2.watch(path, options, handleEvent);
2580
+ } catch (error) {
2581
+ errHandler(error);
2582
+ }
2583
+ }
2584
+
2585
+ /**
2586
+ * Helper for passing fs_watch event data to a collection of listeners
2587
+ * @param {Path} fullPath absolute path bound to fs_watch instance
2588
+ * @param {String} type listener type
2589
+ * @param {*=} val1 arguments to be passed to listeners
2590
+ * @param {*=} val2
2591
+ * @param {*=} val3
2592
+ */
2593
+ const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
2594
+ const cont = FsWatchInstances.get(fullPath);
2595
+ if (!cont) return;
2596
+ foreach(cont[type], (listener) => {
2597
+ listener(val1, val2, val3);
2598
+ });
2599
+ };
2600
+
2601
+ /**
2602
+ * Instantiates the fs_watch interface or binds listeners
2603
+ * to an existing one covering the same file system entry
2604
+ * @param {String} path
2605
+ * @param {String} fullPath absolute path
2606
+ * @param {Object} options to be passed to fs_watch
2607
+ * @param {Object} handlers container for event listener functions
2608
+ */
2609
+ const setFsWatchListener = (path, fullPath, options, handlers) => {
2610
+ const {listener, errHandler, rawEmitter} = handlers;
2611
+ let cont = FsWatchInstances.get(fullPath);
2612
+
2613
+ /** @type {fs.FSWatcher=} */
2614
+ let watcher;
2615
+ if (!options.persistent) {
2616
+ watcher = createFsWatchInstance(
2617
+ path, options, listener, errHandler, rawEmitter
2618
+ );
2619
+ return watcher.close.bind(watcher);
2620
+ }
2621
+ if (cont) {
2622
+ addAndConvert(cont, KEY_LISTENERS, listener);
2623
+ addAndConvert(cont, KEY_ERR, errHandler);
2624
+ addAndConvert(cont, KEY_RAW, rawEmitter);
2625
+ } else {
2626
+ watcher = createFsWatchInstance(
2627
+ path,
2628
+ options,
2629
+ fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
2630
+ errHandler, // no need to use broadcast here
2631
+ fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
2632
+ );
2633
+ if (!watcher) return;
2634
+ watcher.on(EV_ERROR$2, async (error) => {
2635
+ const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
2636
+ cont.watcherUnusable = true; // documented since Node 10.4.1
2637
+ // Workaround for https://github.com/joyent/node/issues/4337
2638
+ if (isWindows$1 && error.code === 'EPERM') {
2639
+ try {
2640
+ const fd = await open(path, 'r');
2641
+ await close(fd);
2642
+ broadcastErr(error);
2643
+ } catch (err) {}
2644
+ } else {
2645
+ broadcastErr(error);
2646
+ }
2647
+ });
2648
+ cont = {
2649
+ listeners: listener,
2650
+ errHandlers: errHandler,
2651
+ rawEmitters: rawEmitter,
2652
+ watcher
2653
+ };
2654
+ FsWatchInstances.set(fullPath, cont);
2655
+ }
2656
+ // const index = cont.listeners.indexOf(listener);
2657
+
2658
+ // removes this instance's listeners and closes the underlying fs_watch
2659
+ // instance if there are no more listeners left
2660
+ return () => {
2661
+ delFromSet(cont, KEY_LISTENERS, listener);
2662
+ delFromSet(cont, KEY_ERR, errHandler);
2663
+ delFromSet(cont, KEY_RAW, rawEmitter);
2664
+ if (isEmptySet(cont.listeners)) {
2665
+ // Check to protect against issue gh-730.
2666
+ // if (cont.watcherUnusable) {
2667
+ cont.watcher.close();
2668
+ // }
2669
+ FsWatchInstances.delete(fullPath);
2670
+ HANDLER_KEYS.forEach(clearItem(cont));
2671
+ cont.watcher = undefined;
2672
+ Object.freeze(cont);
2673
+ }
2674
+ };
2675
+ };
2676
+
2677
+ // fs_watchFile helpers
2678
+
2679
+ // object to hold per-process fs_watchFile instances
2680
+ // (may be shared across chokidar FSWatcher instances)
2681
+ const FsWatchFileInstances = new Map();
2682
+
2683
+ /**
2684
+ * Instantiates the fs_watchFile interface or binds listeners
2685
+ * to an existing one covering the same file system entry
2686
+ * @param {String} path to be watched
2687
+ * @param {String} fullPath absolute path
2688
+ * @param {Object} options options to be passed to fs_watchFile
2689
+ * @param {Object} handlers container for event listener functions
2690
+ * @returns {Function} closer
2691
+ */
2692
+ const setFsWatchFileListener = (path, fullPath, options, handlers) => {
2693
+ const {listener, rawEmitter} = handlers;
2694
+ let cont = FsWatchFileInstances.get(fullPath);
2695
+
2696
+ const copts = cont && cont.options;
2697
+ if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
2698
+ fs$2.unwatchFile(fullPath);
2699
+ cont = undefined;
2700
+ }
2701
+
2702
+ /* eslint-enable no-unused-vars, prefer-destructuring */
2703
+
2704
+ if (cont) {
2705
+ addAndConvert(cont, KEY_LISTENERS, listener);
2706
+ addAndConvert(cont, KEY_RAW, rawEmitter);
2707
+ } else {
2708
+ // TODO
2709
+ // listeners.add(listener);
2710
+ // rawEmitters.add(rawEmitter);
2711
+ cont = {
2712
+ listeners: listener,
2713
+ rawEmitters: rawEmitter,
2714
+ options,
2715
+ watcher: fs$2.watchFile(fullPath, options, (curr, prev) => {
2716
+ foreach(cont.rawEmitters, (rawEmitter) => {
2717
+ rawEmitter(EV_CHANGE$2, fullPath, {curr, prev});
2718
+ });
2719
+ const currmtime = curr.mtimeMs;
2720
+ if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
2721
+ foreach(cont.listeners, (listener) => listener(path, curr));
2722
+ }
2723
+ })
2724
+ };
2725
+ FsWatchFileInstances.set(fullPath, cont);
2726
+ }
2727
+ // const index = cont.listeners.indexOf(listener);
2728
+
2729
+ // Removes this instance's listeners and closes the underlying fs_watchFile
2730
+ // instance if there are no more listeners left.
2731
+ return () => {
2732
+ delFromSet(cont, KEY_LISTENERS, listener);
2733
+ delFromSet(cont, KEY_RAW, rawEmitter);
2734
+ if (isEmptySet(cont.listeners)) {
2735
+ FsWatchFileInstances.delete(fullPath);
2736
+ fs$2.unwatchFile(fullPath);
2737
+ cont.options = cont.watcher = undefined;
2738
+ Object.freeze(cont);
2739
+ }
2740
+ };
2741
+ };
2742
+
2743
+ /**
2744
+ * @mixin
2745
+ */
2746
+ let NodeFsHandler$1 = class NodeFsHandler {
2747
+
2748
+ /**
2749
+ * @param {import("../index").FSWatcher} fsW
2750
+ */
2751
+ constructor(fsW) {
2752
+ this.fsw = fsW;
2753
+ this._boundHandleError = (error) => fsW._handleError(error);
2754
+ }
2755
+
2756
+ /**
2757
+ * Watch file for changes with fs_watchFile or fs_watch.
2758
+ * @param {String} path to file or dir
2759
+ * @param {Function} listener on fs change
2760
+ * @returns {Function} closer for the watcher instance
2761
+ */
2762
+ _watchWithNodeFs(path, listener) {
2763
+ const opts = this.fsw.options;
2764
+ const directory = sysPath$2.dirname(path);
2765
+ const basename = sysPath$2.basename(path);
2766
+ const parent = this.fsw._getWatchedDir(directory);
2767
+ parent.add(basename);
2768
+ const absolutePath = sysPath$2.resolve(path);
2769
+ const options = {persistent: opts.persistent};
2770
+ if (!listener) listener = EMPTY_FN$2;
2771
+
2772
+ let closer;
2773
+ if (opts.usePolling) {
2774
+ options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?
2775
+ opts.binaryInterval : opts.interval;
2776
+ closer = setFsWatchFileListener(path, absolutePath, options, {
2777
+ listener,
2778
+ rawEmitter: this.fsw._emitRaw
2779
+ });
2780
+ } else {
2781
+ closer = setFsWatchListener(path, absolutePath, options, {
2782
+ listener,
2783
+ errHandler: this._boundHandleError,
2784
+ rawEmitter: this.fsw._emitRaw
2785
+ });
2786
+ }
2787
+ return closer;
2788
+ }
2789
+
2790
+ /**
2791
+ * Watch a file and emit add event if warranted.
2792
+ * @param {Path} file Path
2793
+ * @param {fs.Stats} stats result of fs_stat
2794
+ * @param {Boolean} initialAdd was the file added at watch instantiation?
2795
+ * @returns {Function} closer for the watcher instance
2796
+ */
2797
+ _handleFile(file, stats, initialAdd) {
2798
+ if (this.fsw.closed) {
2799
+ return;
2800
+ }
2801
+ const dirname = sysPath$2.dirname(file);
2802
+ const basename = sysPath$2.basename(file);
2803
+ const parent = this.fsw._getWatchedDir(dirname);
2804
+ // stats is always present
2805
+ let prevStats = stats;
2806
+
2807
+ // if the file is already being watched, do nothing
2808
+ if (parent.has(basename)) return;
2809
+
2810
+ const listener = async (path, newStats) => {
2811
+ if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
2812
+ if (!newStats || newStats.mtimeMs === 0) {
2813
+ try {
2814
+ const newStats = await stat$2(file);
2815
+ if (this.fsw.closed) return;
2816
+ // Check that change event was not fired because of changed only accessTime.
2817
+ const at = newStats.atimeMs;
2818
+ const mt = newStats.mtimeMs;
2819
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) {
2820
+ this.fsw._emit(EV_CHANGE$2, file, newStats);
2821
+ }
2822
+ if (isLinux && prevStats.ino !== newStats.ino) {
2823
+ this.fsw._closeFile(path);
2824
+ prevStats = newStats;
2825
+ this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
2826
+ } else {
2827
+ prevStats = newStats;
2828
+ }
2829
+ } catch (error) {
2830
+ // Fix issues where mtime is null but file is still present
2831
+ this.fsw._remove(dirname, basename);
2832
+ }
2833
+ // add is about to be emitted if file not already tracked in parent
2834
+ } else if (parent.has(basename)) {
2835
+ // Check that change event was not fired because of changed only accessTime.
2836
+ const at = newStats.atimeMs;
2837
+ const mt = newStats.mtimeMs;
2838
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) {
2839
+ this.fsw._emit(EV_CHANGE$2, file, newStats);
2840
+ }
2841
+ prevStats = newStats;
2842
+ }
2843
+ };
2844
+ // kick off the watcher
2845
+ const closer = this._watchWithNodeFs(file, listener);
2846
+
2847
+ // emit an add event if we're supposed to
2848
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
2849
+ if (!this.fsw._throttle(EV_ADD$2, file, 0)) return;
2850
+ this.fsw._emit(EV_ADD$2, file, stats);
2851
+ }
2852
+
2853
+ return closer;
2854
+ }
2855
+
2856
+ /**
2857
+ * Handle symlinks encountered while reading a dir.
2858
+ * @param {Object} entry returned by readdirp
2859
+ * @param {String} directory path of dir being read
2860
+ * @param {String} path of this item
2861
+ * @param {String} item basename of this item
2862
+ * @returns {Promise<Boolean>} true if no more processing is needed for this entry.
2863
+ */
2864
+ async _handleSymlink(entry, directory, path, item) {
2865
+ if (this.fsw.closed) {
2866
+ return;
2867
+ }
2868
+ const full = entry.fullPath;
2869
+ const dir = this.fsw._getWatchedDir(directory);
2870
+
2871
+ if (!this.fsw.options.followSymlinks) {
2872
+ // watch symlink directly (don't follow) and detect changes
2873
+ this.fsw._incrReadyCount();
2874
+
2875
+ let linkPath;
2876
+ try {
2877
+ linkPath = await fsrealpath(path);
2878
+ } catch (e) {
2879
+ this.fsw._emitReady();
2880
+ return true;
2881
+ }
2882
+
2883
+ if (this.fsw.closed) return;
2884
+ if (dir.has(item)) {
2885
+ if (this.fsw._symlinkPaths.get(full) !== linkPath) {
2886
+ this.fsw._symlinkPaths.set(full, linkPath);
2887
+ this.fsw._emit(EV_CHANGE$2, path, entry.stats);
2888
+ }
2889
+ } else {
2890
+ dir.add(item);
2891
+ this.fsw._symlinkPaths.set(full, linkPath);
2892
+ this.fsw._emit(EV_ADD$2, path, entry.stats);
2893
+ }
2894
+ this.fsw._emitReady();
2895
+ return true;
2896
+ }
2897
+
2898
+ // don't follow the same symlink more than once
2899
+ if (this.fsw._symlinkPaths.has(full)) {
2900
+ return true;
2901
+ }
2902
+
2903
+ this.fsw._symlinkPaths.set(full, true);
2904
+ }
2905
+
2906
+ _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
2907
+ // Normalize the directory name on Windows
2908
+ directory = sysPath$2.join(directory, EMPTY_STR$1);
2909
+
2910
+ if (!wh.hasGlob) {
2911
+ throttler = this.fsw._throttle('readdir', directory, 1000);
2912
+ if (!throttler) return;
2913
+ }
2914
+
2915
+ const previous = this.fsw._getWatchedDir(wh.path);
2916
+ const current = new Set();
2917
+
2918
+ let stream = this.fsw._readdirp(directory, {
2919
+ fileFilter: entry => wh.filterPath(entry),
2920
+ directoryFilter: entry => wh.filterDir(entry),
2921
+ depth: 0
2922
+ }).on(STR_DATA$1, async (entry) => {
2923
+ if (this.fsw.closed) {
2924
+ stream = undefined;
2925
+ return;
2926
+ }
2927
+ const item = entry.path;
2928
+ let path = sysPath$2.join(directory, item);
2929
+ current.add(item);
2930
+
2931
+ if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
2932
+ return;
2933
+ }
2934
+
2935
+ if (this.fsw.closed) {
2936
+ stream = undefined;
2937
+ return;
2938
+ }
2939
+ // Files that present in current directory snapshot
2940
+ // but absent in previous are added to watch list and
2941
+ // emit `add` event.
2942
+ if (item === target || !target && !previous.has(item)) {
2943
+ this.fsw._incrReadyCount();
2944
+
2945
+ // ensure relativeness of path is preserved in case of watcher reuse
2946
+ path = sysPath$2.join(dir, sysPath$2.relative(dir, path));
2947
+
2948
+ this._addToNodeFs(path, initialAdd, wh, depth + 1);
2949
+ }
2950
+ }).on(EV_ERROR$2, this._boundHandleError);
2951
+
2952
+ return new Promise(resolve =>
2953
+ stream.once(STR_END$2, () => {
2954
+ if (this.fsw.closed) {
2955
+ stream = undefined;
2956
+ return;
2957
+ }
2958
+ const wasThrottled = throttler ? throttler.clear() : false;
2959
+
2960
+ resolve();
2961
+
2962
+ // Files that absent in current directory snapshot
2963
+ // but present in previous emit `remove` event
2964
+ // and are removed from @watched[directory].
2965
+ previous.getChildren().filter((item) => {
2966
+ return item !== directory &&
2967
+ !current.has(item) &&
2968
+ // in case of intersecting globs;
2969
+ // a path may have been filtered out of this readdir, but
2970
+ // shouldn't be removed because it matches a different glob
2971
+ (!wh.hasGlob || wh.filterPath({
2972
+ fullPath: sysPath$2.resolve(directory, item)
2973
+ }));
2974
+ }).forEach((item) => {
2975
+ this.fsw._remove(directory, item);
2976
+ });
2977
+
2978
+ stream = undefined;
2979
+
2980
+ // one more time for any missed in case changes came in extremely quickly
2981
+ if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
2982
+ })
2983
+ );
2984
+ }
2985
+
2986
+ /**
2987
+ * Read directory to add / remove files from `@watched` list and re-read it on change.
2988
+ * @param {String} dir fs path
2989
+ * @param {fs.Stats} stats
2990
+ * @param {Boolean} initialAdd
2991
+ * @param {Number} depth relative to user-supplied path
2992
+ * @param {String} target child path targeted for watch
2993
+ * @param {Object} wh Common watch helpers for this path
2994
+ * @param {String} realpath
2995
+ * @returns {Promise<Function>} closer for the watcher instance.
2996
+ */
2997
+ async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
2998
+ const parentDir = this.fsw._getWatchedDir(sysPath$2.dirname(dir));
2999
+ const tracked = parentDir.has(sysPath$2.basename(dir));
3000
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
3001
+ if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR$2, dir, stats);
3002
+ }
3003
+
3004
+ // ensure dir is tracked (harmless if redundant)
3005
+ parentDir.add(sysPath$2.basename(dir));
3006
+ this.fsw._getWatchedDir(dir);
3007
+ let throttler;
3008
+ let closer;
3009
+
3010
+ const oDepth = this.fsw.options.depth;
3011
+ if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
3012
+ if (!target) {
3013
+ await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
3014
+ if (this.fsw.closed) return;
3015
+ }
3016
+
3017
+ closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
3018
+ // if current directory is removed, do nothing
3019
+ if (stats && stats.mtimeMs === 0) return;
3020
+
3021
+ this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
3022
+ });
3023
+ }
3024
+ return closer;
3025
+ }
3026
+
3027
+ /**
3028
+ * Handle added file, directory, or glob pattern.
3029
+ * Delegates call to _handleFile / _handleDir after checks.
3030
+ * @param {String} path to file or ir
3031
+ * @param {Boolean} initialAdd was the file added at watch instantiation?
3032
+ * @param {Object} priorWh depth relative to user-supplied path
3033
+ * @param {Number} depth Child path actually targeted for watch
3034
+ * @param {String=} target Child path actually targeted for watch
3035
+ * @returns {Promise}
3036
+ */
3037
+ async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
3038
+ const ready = this.fsw._emitReady;
3039
+ if (this.fsw._isIgnored(path) || this.fsw.closed) {
3040
+ ready();
3041
+ return false;
3042
+ }
3043
+
3044
+ const wh = this.fsw._getWatchHelpers(path, depth);
3045
+ if (!wh.hasGlob && priorWh) {
3046
+ wh.hasGlob = priorWh.hasGlob;
3047
+ wh.globFilter = priorWh.globFilter;
3048
+ wh.filterPath = entry => priorWh.filterPath(entry);
3049
+ wh.filterDir = entry => priorWh.filterDir(entry);
3050
+ }
3051
+
3052
+ // evaluate what is at the path we're being asked to watch
3053
+ try {
3054
+ const stats = await statMethods$1[wh.statMethod](wh.watchPath);
3055
+ if (this.fsw.closed) return;
3056
+ if (this.fsw._isIgnored(wh.watchPath, stats)) {
3057
+ ready();
3058
+ return false;
3059
+ }
3060
+
3061
+ const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START$1);
3062
+ let closer;
3063
+ if (stats.isDirectory()) {
3064
+ const absPath = sysPath$2.resolve(path);
3065
+ const targetPath = follow ? await fsrealpath(path) : path;
3066
+ if (this.fsw.closed) return;
3067
+ closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
3068
+ if (this.fsw.closed) return;
3069
+ // preserve this symlink's target path
3070
+ if (absPath !== targetPath && targetPath !== undefined) {
3071
+ this.fsw._symlinkPaths.set(absPath, targetPath);
3072
+ }
3073
+ } else if (stats.isSymbolicLink()) {
3074
+ const targetPath = follow ? await fsrealpath(path) : path;
3075
+ if (this.fsw.closed) return;
3076
+ const parent = sysPath$2.dirname(wh.watchPath);
3077
+ this.fsw._getWatchedDir(parent).add(wh.watchPath);
3078
+ this.fsw._emit(EV_ADD$2, wh.watchPath, stats);
3079
+ closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
3080
+ if (this.fsw.closed) return;
3081
+
3082
+ // preserve this symlink's target path
3083
+ if (targetPath !== undefined) {
3084
+ this.fsw._symlinkPaths.set(sysPath$2.resolve(path), targetPath);
3085
+ }
3086
+ } else {
3087
+ closer = this._handleFile(wh.watchPath, stats, initialAdd);
3088
+ }
3089
+ ready();
3090
+
3091
+ this.fsw._addPathCloser(path, closer);
3092
+ return false;
3093
+
3094
+ } catch (error) {
3095
+ if (this.fsw._handleError(error)) {
3096
+ ready();
3097
+ return path;
3098
+ }
3099
+ }
3100
+ }
3101
+
3102
+ };
3103
+
3104
+ var nodefsHandler = NodeFsHandler$1;
3105
+
3106
+ /*@__PURE__*/rollup.getDefaultExportFromCjs(nodefsHandler);
3107
+
3108
+ var fseventsHandler = {exports: {}};
3109
+
3110
+ const require$$3 = /*@__PURE__*/rollup.getAugmentedNamespace(fseventsImporter.fseventsImporter);
3111
+
3112
+ const fs$1 = require$$0$1;
3113
+ const sysPath$1 = require$$0$2;
3114
+ const { promisify: promisify$1 } = require$$2;
3115
+
3116
+ let fsevents;
3117
+ try {
3118
+ fsevents = require$$3.getFsEvents();
3119
+ } catch (error) {
3120
+ if (process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR) console.error(error);
3121
+ }
3122
+
3123
+ if (fsevents) {
3124
+ // TODO: real check
3125
+ const mtch = process.version.match(/v(\d+)\.(\d+)/);
3126
+ if (mtch && mtch[1] && mtch[2]) {
3127
+ const maj = Number.parseInt(mtch[1], 10);
3128
+ const min = Number.parseInt(mtch[2], 10);
3129
+ if (maj === 8 && min < 16) {
3130
+ fsevents = undefined;
3131
+ }
3132
+ }
3133
+ }
3134
+
3135
+ const {
3136
+ EV_ADD: EV_ADD$1,
3137
+ EV_CHANGE: EV_CHANGE$1,
3138
+ EV_ADD_DIR: EV_ADD_DIR$1,
3139
+ EV_UNLINK: EV_UNLINK$1,
3140
+ EV_ERROR: EV_ERROR$1,
3141
+ STR_DATA,
3142
+ STR_END: STR_END$1,
3143
+ FSEVENT_CREATED,
3144
+ FSEVENT_MODIFIED,
3145
+ FSEVENT_DELETED,
3146
+ FSEVENT_MOVED,
3147
+ // FSEVENT_CLONED,
3148
+ FSEVENT_UNKNOWN,
3149
+ FSEVENT_TYPE_FILE,
3150
+ FSEVENT_TYPE_DIRECTORY,
3151
+ FSEVENT_TYPE_SYMLINK,
3152
+
3153
+ ROOT_GLOBSTAR,
3154
+ DIR_SUFFIX,
3155
+ DOT_SLASH,
3156
+ FUNCTION_TYPE: FUNCTION_TYPE$1,
3157
+ EMPTY_FN: EMPTY_FN$1,
3158
+ IDENTITY_FN
3159
+ } = constants;
3160
+
3161
+ const Depth = (value) => isNaN(value) ? {} : {depth: value};
3162
+
3163
+ const stat$1 = promisify$1(fs$1.stat);
3164
+ const lstat = promisify$1(fs$1.lstat);
3165
+ const realpath = promisify$1(fs$1.realpath);
3166
+
3167
+ const statMethods = { stat: stat$1, lstat };
3168
+
3169
+ /**
3170
+ * @typedef {String} Path
3171
+ */
3172
+
3173
+ /**
3174
+ * @typedef {Object} FsEventsWatchContainer
3175
+ * @property {Set<Function>} listeners
3176
+ * @property {Function} rawEmitter
3177
+ * @property {{stop: Function}} watcher
3178
+ */
3179
+
3180
+ // fsevents instance helper functions
3181
+ /**
3182
+ * Object to hold per-process fsevents instances (may be shared across chokidar FSWatcher instances)
3183
+ * @type {Map<Path,FsEventsWatchContainer>}
3184
+ */
3185
+ const FSEventsWatchers = new Map();
3186
+
3187
+ // Threshold of duplicate path prefixes at which to start
3188
+ // consolidating going forward
3189
+ const consolidateThreshhold = 10;
3190
+
3191
+ const wrongEventFlags = new Set([
3192
+ 69888, 70400, 71424, 72704, 73472, 131328, 131840, 262912
3193
+ ]);
3194
+
3195
+ /**
3196
+ * Instantiates the fsevents interface
3197
+ * @param {Path} path path to be watched
3198
+ * @param {Function} callback called when fsevents is bound and ready
3199
+ * @returns {{stop: Function}} new fsevents instance
3200
+ */
3201
+ const createFSEventsInstance = (path, callback) => {
3202
+ const stop = fsevents.watch(path, callback);
3203
+ return {stop};
3204
+ };
3205
+
3206
+ /**
3207
+ * Instantiates the fsevents interface or binds listeners to an existing one covering
3208
+ * the same file tree.
3209
+ * @param {Path} path - to be watched
3210
+ * @param {Path} realPath - real path for symlinks
3211
+ * @param {Function} listener - called when fsevents emits events
3212
+ * @param {Function} rawEmitter - passes data to listeners of the 'raw' event
3213
+ * @returns {Function} closer
3214
+ */
3215
+ function setFSEventsListener(path, realPath, listener, rawEmitter) {
3216
+ let watchPath = sysPath$1.extname(realPath) ? sysPath$1.dirname(realPath) : realPath;
3217
+
3218
+ const parentPath = sysPath$1.dirname(watchPath);
3219
+ let cont = FSEventsWatchers.get(watchPath);
3220
+
3221
+ // If we've accumulated a substantial number of paths that
3222
+ // could have been consolidated by watching one directory
3223
+ // above the current one, create a watcher on the parent
3224
+ // path instead, so that we do consolidate going forward.
3225
+ if (couldConsolidate(parentPath)) {
3226
+ watchPath = parentPath;
3227
+ }
3228
+
3229
+ const resolvedPath = sysPath$1.resolve(path);
3230
+ const hasSymlink = resolvedPath !== realPath;
3231
+
3232
+ const filteredListener = (fullPath, flags, info) => {
3233
+ if (hasSymlink) fullPath = fullPath.replace(realPath, resolvedPath);
3234
+ if (
3235
+ fullPath === resolvedPath ||
3236
+ !fullPath.indexOf(resolvedPath + sysPath$1.sep)
3237
+ ) listener(fullPath, flags, info);
3238
+ };
3239
+
3240
+ // check if there is already a watcher on a parent path
3241
+ // modifies `watchPath` to the parent path when it finds a match
3242
+ let watchedParent = false;
3243
+ for (const watchedPath of FSEventsWatchers.keys()) {
3244
+ if (realPath.indexOf(sysPath$1.resolve(watchedPath) + sysPath$1.sep) === 0) {
3245
+ watchPath = watchedPath;
3246
+ cont = FSEventsWatchers.get(watchPath);
3247
+ watchedParent = true;
3248
+ break;
3249
+ }
3250
+ }
3251
+
3252
+ if (cont || watchedParent) {
3253
+ cont.listeners.add(filteredListener);
3254
+ } else {
3255
+ cont = {
3256
+ listeners: new Set([filteredListener]),
3257
+ rawEmitter,
3258
+ watcher: createFSEventsInstance(watchPath, (fullPath, flags) => {
3259
+ if (!cont.listeners.size) return;
3260
+ const info = fsevents.getInfo(fullPath, flags);
3261
+ cont.listeners.forEach(list => {
3262
+ list(fullPath, flags, info);
3263
+ });
3264
+
3265
+ cont.rawEmitter(info.event, fullPath, info);
3266
+ })
3267
+ };
3268
+ FSEventsWatchers.set(watchPath, cont);
3269
+ }
3270
+
3271
+ // removes this instance's listeners and closes the underlying fsevents
3272
+ // instance if there are no more listeners left
3273
+ return () => {
3274
+ const lst = cont.listeners;
3275
+
3276
+ lst.delete(filteredListener);
3277
+ if (!lst.size) {
3278
+ FSEventsWatchers.delete(watchPath);
3279
+ if (cont.watcher) return cont.watcher.stop().then(() => {
3280
+ cont.rawEmitter = cont.watcher = undefined;
3281
+ Object.freeze(cont);
3282
+ });
3283
+ }
3284
+ };
3285
+ }
3286
+
3287
+ // Decide whether or not we should start a new higher-level
3288
+ // parent watcher
3289
+ const couldConsolidate = (path) => {
3290
+ let count = 0;
3291
+ for (const watchPath of FSEventsWatchers.keys()) {
3292
+ if (watchPath.indexOf(path) === 0) {
3293
+ count++;
3294
+ if (count >= consolidateThreshhold) {
3295
+ return true;
3296
+ }
3297
+ }
3298
+ }
3299
+
3300
+ return false;
3301
+ };
3302
+
3303
+ // returns boolean indicating whether fsevents can be used
3304
+ const canUse = () => fsevents && FSEventsWatchers.size < 128;
3305
+
3306
+ // determines subdirectory traversal levels from root to path
3307
+ const calcDepth = (path, root) => {
3308
+ let i = 0;
3309
+ while (!path.indexOf(root) && (path = sysPath$1.dirname(path)) !== root) i++;
3310
+ return i;
3311
+ };
3312
+
3313
+ // returns boolean indicating whether the fsevents' event info has the same type
3314
+ // as the one returned by fs.stat
3315
+ const sameTypes = (info, stats) => (
3316
+ info.type === FSEVENT_TYPE_DIRECTORY && stats.isDirectory() ||
3317
+ info.type === FSEVENT_TYPE_SYMLINK && stats.isSymbolicLink() ||
3318
+ info.type === FSEVENT_TYPE_FILE && stats.isFile()
3319
+ );
3320
+
3321
+ /**
3322
+ * @mixin
3323
+ */
3324
+ let FsEventsHandler$1 = class FsEventsHandler {
3325
+
3326
+ /**
3327
+ * @param {import('../index').FSWatcher} fsw
3328
+ */
3329
+ constructor(fsw) {
3330
+ this.fsw = fsw;
3331
+ }
3332
+ checkIgnored(path, stats) {
3333
+ const ipaths = this.fsw._ignoredPaths;
3334
+ if (this.fsw._isIgnored(path, stats)) {
3335
+ ipaths.add(path);
3336
+ if (stats && stats.isDirectory()) {
3337
+ ipaths.add(path + ROOT_GLOBSTAR);
3338
+ }
3339
+ return true;
3340
+ }
3341
+
3342
+ ipaths.delete(path);
3343
+ ipaths.delete(path + ROOT_GLOBSTAR);
3344
+ }
3345
+
3346
+ addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
3347
+ const event = watchedDir.has(item) ? EV_CHANGE$1 : EV_ADD$1;
3348
+ this.handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts);
3349
+ }
3350
+
3351
+ async checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts) {
3352
+ try {
3353
+ const stats = await stat$1(path);
3354
+ if (this.fsw.closed) return;
3355
+ if (sameTypes(info, stats)) {
3356
+ this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
3357
+ } else {
3358
+ this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
3359
+ }
3360
+ } catch (error) {
3361
+ if (error.code === 'EACCES') {
3362
+ this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
3363
+ } else {
3364
+ this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
3365
+ }
3366
+ }
3367
+ }
3368
+
3369
+ handleEvent(event, path, fullPath, realPath, parent, watchedDir, item, info, opts) {
3370
+ if (this.fsw.closed || this.checkIgnored(path)) return;
3371
+
3372
+ if (event === EV_UNLINK$1) {
3373
+ const isDirectory = info.type === FSEVENT_TYPE_DIRECTORY;
3374
+ // suppress unlink events on never before seen files
3375
+ if (isDirectory || watchedDir.has(item)) {
3376
+ this.fsw._remove(parent, item, isDirectory);
3377
+ }
3378
+ } else {
3379
+ if (event === EV_ADD$1) {
3380
+ // track new directories
3381
+ if (info.type === FSEVENT_TYPE_DIRECTORY) this.fsw._getWatchedDir(path);
3382
+
3383
+ if (info.type === FSEVENT_TYPE_SYMLINK && opts.followSymlinks) {
3384
+ // push symlinks back to the top of the stack to get handled
3385
+ const curDepth = opts.depth === undefined ?
3386
+ undefined : calcDepth(fullPath, realPath) + 1;
3387
+ return this._addToFsEvents(path, false, true, curDepth);
3388
+ }
3389
+
3390
+ // track new paths
3391
+ // (other than symlinks being followed, which will be tracked soon)
3392
+ this.fsw._getWatchedDir(parent).add(item);
3393
+ }
3394
+ /**
3395
+ * @type {'add'|'addDir'|'unlink'|'unlinkDir'}
3396
+ */
3397
+ const eventName = info.type === FSEVENT_TYPE_DIRECTORY ? event + DIR_SUFFIX : event;
3398
+ this.fsw._emit(eventName, path);
3399
+ if (eventName === EV_ADD_DIR$1) this._addToFsEvents(path, false, true);
3400
+ }
3401
+ }
3402
+
3403
+ /**
3404
+ * Handle symlinks encountered during directory scan
3405
+ * @param {String} watchPath - file/dir path to be watched with fsevents
3406
+ * @param {String} realPath - real path (in case of symlinks)
3407
+ * @param {Function} transform - path transformer
3408
+ * @param {Function} globFilter - path filter in case a glob pattern was provided
3409
+ * @returns {Function} closer for the watcher instance
3410
+ */
3411
+ _watchWithFsEvents(watchPath, realPath, transform, globFilter) {
3412
+ if (this.fsw.closed || this.fsw._isIgnored(watchPath)) return;
3413
+ const opts = this.fsw.options;
3414
+ const watchCallback = async (fullPath, flags, info) => {
3415
+ if (this.fsw.closed) return;
3416
+ if (
3417
+ opts.depth !== undefined &&
3418
+ calcDepth(fullPath, realPath) > opts.depth
3419
+ ) return;
3420
+ const path = transform(sysPath$1.join(
3421
+ watchPath, sysPath$1.relative(watchPath, fullPath)
3422
+ ));
3423
+ if (globFilter && !globFilter(path)) return;
3424
+ // ensure directories are tracked
3425
+ const parent = sysPath$1.dirname(path);
3426
+ const item = sysPath$1.basename(path);
3427
+ const watchedDir = this.fsw._getWatchedDir(
3428
+ info.type === FSEVENT_TYPE_DIRECTORY ? path : parent
3429
+ );
3430
+
3431
+ // correct for wrong events emitted
3432
+ if (wrongEventFlags.has(flags) || info.event === FSEVENT_UNKNOWN) {
3433
+ if (typeof opts.ignored === FUNCTION_TYPE$1) {
3434
+ let stats;
3435
+ try {
3436
+ stats = await stat$1(path);
3437
+ } catch (error) {}
3438
+ if (this.fsw.closed) return;
3439
+ if (this.checkIgnored(path, stats)) return;
3440
+ if (sameTypes(info, stats)) {
3441
+ this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
3442
+ } else {
3443
+ this.handleEvent(EV_UNLINK$1, path, fullPath, realPath, parent, watchedDir, item, info, opts);
3444
+ }
3445
+ } else {
3446
+ this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
3447
+ }
3448
+ } else {
3449
+ switch (info.event) {
3450
+ case FSEVENT_CREATED:
3451
+ case FSEVENT_MODIFIED:
3452
+ return this.addOrChange(path, fullPath, realPath, parent, watchedDir, item, info, opts);
3453
+ case FSEVENT_DELETED:
3454
+ case FSEVENT_MOVED:
3455
+ return this.checkExists(path, fullPath, realPath, parent, watchedDir, item, info, opts);
3456
+ }
3457
+ }
3458
+ };
3459
+
3460
+ const closer = setFSEventsListener(
3461
+ watchPath,
3462
+ realPath,
3463
+ watchCallback,
3464
+ this.fsw._emitRaw
3465
+ );
3466
+
3467
+ this.fsw._emitReady();
3468
+ return closer;
3469
+ }
3470
+
3471
+ /**
3472
+ * Handle symlinks encountered during directory scan
3473
+ * @param {String} linkPath path to symlink
3474
+ * @param {String} fullPath absolute path to the symlink
3475
+ * @param {Function} transform pre-existing path transformer
3476
+ * @param {Number} curDepth level of subdirectories traversed to where symlink is
3477
+ * @returns {Promise<void>}
3478
+ */
3479
+ async _handleFsEventsSymlink(linkPath, fullPath, transform, curDepth) {
3480
+ // don't follow the same symlink more than once
3481
+ if (this.fsw.closed || this.fsw._symlinkPaths.has(fullPath)) return;
3482
+
3483
+ this.fsw._symlinkPaths.set(fullPath, true);
3484
+ this.fsw._incrReadyCount();
3485
+
3486
+ try {
3487
+ const linkTarget = await realpath(linkPath);
3488
+ if (this.fsw.closed) return;
3489
+ if (this.fsw._isIgnored(linkTarget)) {
3490
+ return this.fsw._emitReady();
3491
+ }
3492
+
3493
+ this.fsw._incrReadyCount();
3494
+
3495
+ // add the linkTarget for watching with a wrapper for transform
3496
+ // that causes emitted paths to incorporate the link's path
3497
+ this._addToFsEvents(linkTarget || linkPath, (path) => {
3498
+ let aliasedPath = linkPath;
3499
+ if (linkTarget && linkTarget !== DOT_SLASH) {
3500
+ aliasedPath = path.replace(linkTarget, linkPath);
3501
+ } else if (path !== DOT_SLASH) {
3502
+ aliasedPath = sysPath$1.join(linkPath, path);
3503
+ }
3504
+ return transform(aliasedPath);
3505
+ }, false, curDepth);
3506
+ } catch(error) {
3507
+ if (this.fsw._handleError(error)) {
3508
+ return this.fsw._emitReady();
3509
+ }
3510
+ }
3511
+ }
3512
+
3513
+ /**
3514
+ *
3515
+ * @param {Path} newPath
3516
+ * @param {fs.Stats} stats
3517
+ */
3518
+ emitAdd(newPath, stats, processPath, opts, forceAdd) {
3519
+ const pp = processPath(newPath);
3520
+ const isDir = stats.isDirectory();
3521
+ const dirObj = this.fsw._getWatchedDir(sysPath$1.dirname(pp));
3522
+ const base = sysPath$1.basename(pp);
3523
+
3524
+ // ensure empty dirs get tracked
3525
+ if (isDir) this.fsw._getWatchedDir(pp);
3526
+ if (dirObj.has(base)) return;
3527
+ dirObj.add(base);
3528
+
3529
+ if (!opts.ignoreInitial || forceAdd === true) {
3530
+ this.fsw._emit(isDir ? EV_ADD_DIR$1 : EV_ADD$1, pp, stats);
3531
+ }
3532
+ }
3533
+
3534
+ initWatch(realPath, path, wh, processPath) {
3535
+ if (this.fsw.closed) return;
3536
+ const closer = this._watchWithFsEvents(
3537
+ wh.watchPath,
3538
+ sysPath$1.resolve(realPath || wh.watchPath),
3539
+ processPath,
3540
+ wh.globFilter
3541
+ );
3542
+ this.fsw._addPathCloser(path, closer);
3543
+ }
3544
+
3545
+ /**
3546
+ * Handle added path with fsevents
3547
+ * @param {String} path file/dir path or glob pattern
3548
+ * @param {Function|Boolean=} transform converts working path to what the user expects
3549
+ * @param {Boolean=} forceAdd ensure add is emitted
3550
+ * @param {Number=} priorDepth Level of subdirectories already traversed.
3551
+ * @returns {Promise<void>}
3552
+ */
3553
+ async _addToFsEvents(path, transform, forceAdd, priorDepth) {
3554
+ if (this.fsw.closed) {
3555
+ return;
3556
+ }
3557
+ const opts = this.fsw.options;
3558
+ const processPath = typeof transform === FUNCTION_TYPE$1 ? transform : IDENTITY_FN;
3559
+
3560
+ const wh = this.fsw._getWatchHelpers(path);
3561
+
3562
+ // evaluate what is at the path we're being asked to watch
3563
+ try {
3564
+ const stats = await statMethods[wh.statMethod](wh.watchPath);
3565
+ if (this.fsw.closed) return;
3566
+ if (this.fsw._isIgnored(wh.watchPath, stats)) {
3567
+ throw null;
3568
+ }
3569
+ if (stats.isDirectory()) {
3570
+ // emit addDir unless this is a glob parent
3571
+ if (!wh.globFilter) this.emitAdd(processPath(path), stats, processPath, opts, forceAdd);
3572
+
3573
+ // don't recurse further if it would exceed depth setting
3574
+ if (priorDepth && priorDepth > opts.depth) return;
3575
+
3576
+ // scan the contents of the dir
3577
+ this.fsw._readdirp(wh.watchPath, {
3578
+ fileFilter: entry => wh.filterPath(entry),
3579
+ directoryFilter: entry => wh.filterDir(entry),
3580
+ ...Depth(opts.depth - (priorDepth || 0))
3581
+ }).on(STR_DATA, (entry) => {
3582
+ // need to check filterPath on dirs b/c filterDir is less restrictive
3583
+ if (this.fsw.closed) {
3584
+ return;
3585
+ }
3586
+ if (entry.stats.isDirectory() && !wh.filterPath(entry)) return;
3587
+
3588
+ const joinedPath = sysPath$1.join(wh.watchPath, entry.path);
3589
+ const {fullPath} = entry;
3590
+
3591
+ if (wh.followSymlinks && entry.stats.isSymbolicLink()) {
3592
+ // preserve the current depth here since it can't be derived from
3593
+ // real paths past the symlink
3594
+ const curDepth = opts.depth === undefined ?
3595
+ undefined : calcDepth(joinedPath, sysPath$1.resolve(wh.watchPath)) + 1;
3596
+
3597
+ this._handleFsEventsSymlink(joinedPath, fullPath, processPath, curDepth);
3598
+ } else {
3599
+ this.emitAdd(joinedPath, entry.stats, processPath, opts, forceAdd);
3600
+ }
3601
+ }).on(EV_ERROR$1, EMPTY_FN$1).on(STR_END$1, () => {
3602
+ this.fsw._emitReady();
3603
+ });
3604
+ } else {
3605
+ this.emitAdd(wh.watchPath, stats, processPath, opts, forceAdd);
3606
+ this.fsw._emitReady();
3607
+ }
3608
+ } catch (error) {
3609
+ if (!error || this.fsw._handleError(error)) {
3610
+ // TODO: Strange thing: "should not choke on an ignored watch path" will be failed without 2 ready calls -__-
3611
+ this.fsw._emitReady();
3612
+ this.fsw._emitReady();
3613
+ }
3614
+ }
3615
+
3616
+ if (opts.persistent && forceAdd !== true) {
3617
+ if (typeof transform === FUNCTION_TYPE$1) {
3618
+ // realpath has already been resolved
3619
+ this.initWatch(undefined, path, wh, processPath);
3620
+ } else {
3621
+ let realPath;
3622
+ try {
3623
+ realPath = await realpath(wh.watchPath);
3624
+ } catch (e) {}
3625
+ this.initWatch(realPath, path, wh, processPath);
3626
+ }
3627
+ }
3628
+ }
3629
+
3630
+ };
3631
+
3632
+ fseventsHandler.exports = FsEventsHandler$1;
3633
+ fseventsHandler.exports.canUse = canUse;
3634
+
3635
+ var fseventsHandlerExports = fseventsHandler.exports;
3636
+ /*@__PURE__*/rollup.getDefaultExportFromCjs(fseventsHandlerExports);
3637
+
3638
+ const { EventEmitter } = require$$0$3;
3639
+ const fs = require$$0$1;
3640
+ const sysPath = require$$0$2;
3641
+ const { promisify } = require$$2;
3642
+ const readdirp = readdirp_1;
3643
+ const anymatch = anymatchExports.default;
3644
+ const globParent = globParent$1;
3645
+ const isGlob = isGlob$2;
3646
+ const braces = braces_1;
3647
+ const normalizePath = normalizePath$2;
3648
+
3649
+ const NodeFsHandler = nodefsHandler;
3650
+ const FsEventsHandler = fseventsHandlerExports;
3651
+ const {
3652
+ EV_ALL,
3653
+ EV_READY,
3654
+ EV_ADD,
3655
+ EV_CHANGE,
3656
+ EV_UNLINK,
3657
+ EV_ADD_DIR,
3658
+ EV_UNLINK_DIR,
3659
+ EV_RAW,
3660
+ EV_ERROR,
3661
+
3662
+ STR_CLOSE,
3663
+ STR_END,
3664
+
3665
+ BACK_SLASH_RE,
3666
+ DOUBLE_SLASH_RE,
3667
+ SLASH_OR_BACK_SLASH_RE,
3668
+ DOT_RE,
3669
+ REPLACER_RE,
3670
+
3671
+ SLASH,
3672
+ SLASH_SLASH,
3673
+ BRACE_START,
3674
+ BANG,
3675
+ ONE_DOT,
3676
+ TWO_DOTS,
3677
+ GLOBSTAR,
3678
+ SLASH_GLOBSTAR,
3679
+ ANYMATCH_OPTS,
3680
+ STRING_TYPE,
3681
+ FUNCTION_TYPE,
3682
+ EMPTY_STR,
3683
+ EMPTY_FN,
3684
+
3685
+ isWindows,
3686
+ isMacos,
3687
+ isIBMi
3688
+ } = constants;
3689
+
3690
+ const stat = promisify(fs.stat);
3691
+ const readdir = promisify(fs.readdir);
3692
+
3693
+ /**
3694
+ * @typedef {String} Path
3695
+ * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
3696
+ * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
3697
+ */
3698
+
3699
+ /**
3700
+ *
3701
+ * @typedef {Object} WatchHelpers
3702
+ * @property {Boolean} followSymlinks
3703
+ * @property {'stat'|'lstat'} statMethod
3704
+ * @property {Path} path
3705
+ * @property {Path} watchPath
3706
+ * @property {Function} entryPath
3707
+ * @property {Boolean} hasGlob
3708
+ * @property {Object} globFilter
3709
+ * @property {Function} filterPath
3710
+ * @property {Function} filterDir
3711
+ */
3712
+
3713
+ const arrify = (value = []) => Array.isArray(value) ? value : [value];
3714
+ const flatten = (list, result = []) => {
3715
+ list.forEach(item => {
3716
+ if (Array.isArray(item)) {
3717
+ flatten(item, result);
3718
+ } else {
3719
+ result.push(item);
3720
+ }
3721
+ });
3722
+ return result;
3723
+ };
3724
+
3725
+ const unifyPaths = (paths_) => {
3726
+ /**
3727
+ * @type {Array<String>}
3728
+ */
3729
+ const paths = flatten(arrify(paths_));
3730
+ if (!paths.every(p => typeof p === STRING_TYPE)) {
3731
+ throw new TypeError(`Non-string provided as watch path: ${paths}`);
3732
+ }
3733
+ return paths.map(normalizePathToUnix);
3734
+ };
3735
+
3736
+ // If SLASH_SLASH occurs at the beginning of path, it is not replaced
3737
+ // because "//StoragePC/DrivePool/Movies" is a valid network path
3738
+ const toUnix = (string) => {
3739
+ let str = string.replace(BACK_SLASH_RE, SLASH);
3740
+ let prepend = false;
3741
+ if (str.startsWith(SLASH_SLASH)) {
3742
+ prepend = true;
3743
+ }
3744
+ while (str.match(DOUBLE_SLASH_RE)) {
3745
+ str = str.replace(DOUBLE_SLASH_RE, SLASH);
3746
+ }
3747
+ if (prepend) {
3748
+ str = SLASH + str;
3749
+ }
3750
+ return str;
3751
+ };
3752
+
3753
+ // Our version of upath.normalize
3754
+ // TODO: this is not equal to path-normalize module - investigate why
3755
+ const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
3756
+
3757
+ const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
3758
+ if (typeof path !== STRING_TYPE) return path;
3759
+ return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
3760
+ };
3761
+
3762
+ const getAbsolutePath = (path, cwd) => {
3763
+ if (sysPath.isAbsolute(path)) {
3764
+ return path;
3765
+ }
3766
+ if (path.startsWith(BANG)) {
3767
+ return BANG + sysPath.join(cwd, path.slice(1));
3768
+ }
3769
+ return sysPath.join(cwd, path);
3770
+ };
3771
+
3772
+ const undef = (opts, key) => opts[key] === undefined;
3773
+
3774
+ /**
3775
+ * Directory entry.
3776
+ * @property {Path} path
3777
+ * @property {Set<Path>} items
3778
+ */
3779
+ class DirEntry {
3780
+ /**
3781
+ * @param {Path} dir
3782
+ * @param {Function} removeWatcher
3783
+ */
3784
+ constructor(dir, removeWatcher) {
3785
+ this.path = dir;
3786
+ this._removeWatcher = removeWatcher;
3787
+ /** @type {Set<Path>} */
3788
+ this.items = new Set();
3789
+ }
3790
+
3791
+ add(item) {
3792
+ const {items} = this;
3793
+ if (!items) return;
3794
+ if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
3795
+ }
3796
+
3797
+ async remove(item) {
3798
+ const {items} = this;
3799
+ if (!items) return;
3800
+ items.delete(item);
3801
+ if (items.size > 0) return;
3802
+
3803
+ const dir = this.path;
3804
+ try {
3805
+ await readdir(dir);
3806
+ } catch (err) {
3807
+ if (this._removeWatcher) {
3808
+ this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
3809
+ }
3810
+ }
3811
+ }
3812
+
3813
+ has(item) {
3814
+ const {items} = this;
3815
+ if (!items) return;
3816
+ return items.has(item);
3817
+ }
3818
+
3819
+ /**
3820
+ * @returns {Array<String>}
3821
+ */
3822
+ getChildren() {
3823
+ const {items} = this;
3824
+ if (!items) return;
3825
+ return [...items.values()];
3826
+ }
3827
+
3828
+ dispose() {
3829
+ this.items.clear();
3830
+ delete this.path;
3831
+ delete this._removeWatcher;
3832
+ delete this.items;
3833
+ Object.freeze(this);
3834
+ }
3835
+ }
3836
+
3837
+ const STAT_METHOD_F = 'stat';
3838
+ const STAT_METHOD_L = 'lstat';
3839
+ class WatchHelper {
3840
+ constructor(path, watchPath, follow, fsw) {
3841
+ this.fsw = fsw;
3842
+ this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
3843
+ this.watchPath = watchPath;
3844
+ this.fullWatchPath = sysPath.resolve(watchPath);
3845
+ this.hasGlob = watchPath !== path;
3846
+ /** @type {object|boolean} */
3847
+ if (path === EMPTY_STR) this.hasGlob = false;
3848
+ this.globSymlink = this.hasGlob && follow ? undefined : false;
3849
+ this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;
3850
+ this.dirParts = this.getDirParts(path);
3851
+ this.dirParts.forEach((parts) => {
3852
+ if (parts.length > 1) parts.pop();
3853
+ });
3854
+ this.followSymlinks = follow;
3855
+ this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
3856
+ }
3857
+
3858
+ checkGlobSymlink(entry) {
3859
+ // only need to resolve once
3860
+ // first entry should always have entry.parentDir === EMPTY_STR
3861
+ if (this.globSymlink === undefined) {
3862
+ this.globSymlink = entry.fullParentDir === this.fullWatchPath ?
3863
+ false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};
3864
+ }
3865
+
3866
+ if (this.globSymlink) {
3867
+ return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
3868
+ }
3869
+
3870
+ return entry.fullPath;
3871
+ }
3872
+
3873
+ entryPath(entry) {
3874
+ return sysPath.join(this.watchPath,
3875
+ sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))
3876
+ );
3877
+ }
3878
+
3879
+ filterPath(entry) {
3880
+ const {stats} = entry;
3881
+ if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
3882
+ const resolvedPath = this.entryPath(entry);
3883
+ const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ?
3884
+ this.globFilter(resolvedPath) : true;
3885
+ return matchesGlob &&
3886
+ this.fsw._isntIgnored(resolvedPath, stats) &&
3887
+ this.fsw._hasReadPermissions(stats);
3888
+ }
3889
+
3890
+ getDirParts(path) {
3891
+ if (!this.hasGlob) return [];
3892
+ const parts = [];
3893
+ const expandedPath = path.includes(BRACE_START) ? braces.expand(path) : [path];
3894
+ expandedPath.forEach((path) => {
3895
+ parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
3896
+ });
3897
+ return parts;
3898
+ }
3899
+
3900
+ filterDir(entry) {
3901
+ if (this.hasGlob) {
3902
+ const entryParts = this.getDirParts(this.checkGlobSymlink(entry));
3903
+ let globstar = false;
3904
+ this.unmatchedGlob = !this.dirParts.some((parts) => {
3905
+ return parts.every((part, i) => {
3906
+ if (part === GLOBSTAR) globstar = true;
3907
+ return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
3908
+ });
3909
+ });
3910
+ }
3911
+ return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
3912
+ }
3913
+ }
3914
+
3915
+ /**
3916
+ * Watches files & directories for changes. Emitted events:
3917
+ * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
3918
+ *
3919
+ * new FSWatcher()
3920
+ * .add(directories)
3921
+ * .on('add', path => log('File', path, 'was added'))
3922
+ */
3923
+ class FSWatcher extends EventEmitter {
3924
+ // Not indenting methods for history sake; for now.
3925
+ constructor(_opts) {
3926
+ super();
3927
+
3928
+ const opts = {};
3929
+ if (_opts) Object.assign(opts, _opts); // for frozen objects
3930
+
3931
+ /** @type {Map<String, DirEntry>} */
3932
+ this._watched = new Map();
3933
+ /** @type {Map<String, Array>} */
3934
+ this._closers = new Map();
3935
+ /** @type {Set<String>} */
3936
+ this._ignoredPaths = new Set();
3937
+
3938
+ /** @type {Map<ThrottleType, Map>} */
3939
+ this._throttled = new Map();
3940
+
3941
+ /** @type {Map<Path, String|Boolean>} */
3942
+ this._symlinkPaths = new Map();
3943
+
3944
+ this._streams = new Set();
3945
+ this.closed = false;
3946
+
3947
+ // Set up default options.
3948
+ if (undef(opts, 'persistent')) opts.persistent = true;
3949
+ if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;
3950
+ if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;
3951
+ if (undef(opts, 'interval')) opts.interval = 100;
3952
+ if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;
3953
+ if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;
3954
+ opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
3955
+
3956
+ // Enable fsevents on OS X when polling isn't explicitly enabled.
3957
+ if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;
3958
+
3959
+ // If we can't use fsevents, ensure the options reflect it's disabled.
3960
+ const canUseFsEvents = FsEventsHandler.canUse();
3961
+ if (!canUseFsEvents) opts.useFsEvents = false;
3962
+
3963
+ // Use polling on Mac if not using fsevents.
3964
+ // Other platforms use non-polling fs_watch.
3965
+ if (undef(opts, 'usePolling') && !opts.useFsEvents) {
3966
+ opts.usePolling = isMacos;
3967
+ }
3968
+
3969
+ // Always default to polling on IBM i because fs.watch() is not available on IBM i.
3970
+ if(isIBMi) {
3971
+ opts.usePolling = true;
3972
+ }
3973
+
3974
+ // Global override (useful for end-developers that need to force polling for all
3975
+ // instances of chokidar, regardless of usage/dependency depth)
3976
+ const envPoll = process.env.CHOKIDAR_USEPOLLING;
3977
+ if (envPoll !== undefined) {
3978
+ const envLower = envPoll.toLowerCase();
3979
+
3980
+ if (envLower === 'false' || envLower === '0') {
3981
+ opts.usePolling = false;
3982
+ } else if (envLower === 'true' || envLower === '1') {
3983
+ opts.usePolling = true;
3984
+ } else {
3985
+ opts.usePolling = !!envLower;
3986
+ }
3987
+ }
3988
+ const envInterval = process.env.CHOKIDAR_INTERVAL;
3989
+ if (envInterval) {
3990
+ opts.interval = Number.parseInt(envInterval, 10);
3991
+ }
3992
+
3993
+ // Editor atomic write normalization enabled by default with fs.watch
3994
+ if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
3995
+ if (opts.atomic) this._pendingUnlinks = new Map();
3996
+
3997
+ if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;
3998
+
3999
+ if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;
4000
+ if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
4001
+ const awf = opts.awaitWriteFinish;
4002
+ if (awf) {
4003
+ if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
4004
+ if (!awf.pollInterval) awf.pollInterval = 100;
4005
+ this._pendingWrites = new Map();
4006
+ }
4007
+ if (opts.ignored) opts.ignored = arrify(opts.ignored);
4008
+
4009
+ let readyCalls = 0;
4010
+ this._emitReady = () => {
4011
+ readyCalls++;
4012
+ if (readyCalls >= this._readyCount) {
4013
+ this._emitReady = EMPTY_FN;
4014
+ this._readyEmitted = true;
4015
+ // use process.nextTick to allow time for listener to be bound
4016
+ process.nextTick(() => this.emit(EV_READY));
4017
+ }
4018
+ };
4019
+ this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
4020
+ this._readyEmitted = false;
4021
+ this.options = opts;
4022
+
4023
+ // Initialize with proper watcher.
4024
+ if (opts.useFsEvents) {
4025
+ this._fsEventsHandler = new FsEventsHandler(this);
4026
+ } else {
4027
+ this._nodeFsHandler = new NodeFsHandler(this);
4028
+ }
4029
+
4030
+ // You’re frozen when your heart’s not open.
4031
+ Object.freeze(opts);
4032
+ }
4033
+
4034
+ // Public methods
4035
+
4036
+ /**
4037
+ * Adds paths to be watched on an existing FSWatcher instance
4038
+ * @param {Path|Array<Path>} paths_
4039
+ * @param {String=} _origAdd private; for handling non-existent paths to be watched
4040
+ * @param {Boolean=} _internal private; indicates a non-user add
4041
+ * @returns {FSWatcher} for chaining
4042
+ */
4043
+ add(paths_, _origAdd, _internal) {
4044
+ const {cwd, disableGlobbing} = this.options;
4045
+ this.closed = false;
4046
+ let paths = unifyPaths(paths_);
4047
+ if (cwd) {
4048
+ paths = paths.map((path) => {
4049
+ const absPath = getAbsolutePath(path, cwd);
4050
+
4051
+ // Check `path` instead of `absPath` because the cwd portion can't be a glob
4052
+ if (disableGlobbing || !isGlob(path)) {
4053
+ return absPath;
4054
+ }
4055
+ return normalizePath(absPath);
4056
+ });
4057
+ }
4058
+
4059
+ // set aside negated glob strings
4060
+ paths = paths.filter((path) => {
4061
+ if (path.startsWith(BANG)) {
4062
+ this._ignoredPaths.add(path.slice(1));
4063
+ return false;
4064
+ }
4065
+
4066
+ // if a path is being added that was previously ignored, stop ignoring it
4067
+ this._ignoredPaths.delete(path);
4068
+ this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
4069
+
4070
+ // reset the cached userIgnored anymatch fn
4071
+ // to make ignoredPaths changes effective
4072
+ this._userIgnored = undefined;
4073
+
4074
+ return true;
4075
+ });
4076
+
4077
+ if (this.options.useFsEvents && this._fsEventsHandler) {
4078
+ if (!this._readyCount) this._readyCount = paths.length;
4079
+ if (this.options.persistent) this._readyCount *= 2;
4080
+ paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
4081
+ } else {
4082
+ if (!this._readyCount) this._readyCount = 0;
4083
+ this._readyCount += paths.length;
4084
+ Promise.all(
4085
+ paths.map(async path => {
4086
+ const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
4087
+ if (res) this._emitReady();
4088
+ return res;
4089
+ })
4090
+ ).then(results => {
4091
+ if (this.closed) return;
4092
+ results.filter(item => item).forEach(item => {
4093
+ this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
4094
+ });
4095
+ });
4096
+ }
4097
+
4098
+ return this;
4099
+ }
4100
+
4101
+ /**
4102
+ * Close watchers or start ignoring events from specified paths.
4103
+ * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
4104
+ * @returns {FSWatcher} for chaining
4105
+ */
4106
+ unwatch(paths_) {
4107
+ if (this.closed) return this;
4108
+ const paths = unifyPaths(paths_);
4109
+ const {cwd} = this.options;
4110
+
4111
+ paths.forEach((path) => {
4112
+ // convert to absolute path unless relative path already matches
4113
+ if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
4114
+ if (cwd) path = sysPath.join(cwd, path);
4115
+ path = sysPath.resolve(path);
4116
+ }
4117
+
4118
+ this._closePath(path);
4119
+
4120
+ this._ignoredPaths.add(path);
4121
+ if (this._watched.has(path)) {
4122
+ this._ignoredPaths.add(path + SLASH_GLOBSTAR);
4123
+ }
4124
+
4125
+ // reset the cached userIgnored anymatch fn
4126
+ // to make ignoredPaths changes effective
4127
+ this._userIgnored = undefined;
4128
+ });
4129
+
4130
+ return this;
4131
+ }
4132
+
4133
+ /**
4134
+ * Close watchers and remove all listeners from watched paths.
4135
+ * @returns {Promise<void>}.
4136
+ */
4137
+ close() {
4138
+ if (this.closed) return this._closePromise;
4139
+ this.closed = true;
4140
+
4141
+ // Memory management.
4142
+ this.removeAllListeners();
4143
+ const closers = [];
4144
+ this._closers.forEach(closerList => closerList.forEach(closer => {
4145
+ const promise = closer();
4146
+ if (promise instanceof Promise) closers.push(promise);
4147
+ }));
4148
+ this._streams.forEach(stream => stream.destroy());
4149
+ this._userIgnored = undefined;
4150
+ this._readyCount = 0;
4151
+ this._readyEmitted = false;
4152
+ this._watched.forEach(dirent => dirent.dispose());
4153
+ ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {
4154
+ this[`_${key}`].clear();
4155
+ });
4156
+
4157
+ this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();
4158
+ return this._closePromise;
4159
+ }
4160
+
4161
+ /**
4162
+ * Expose list of watched paths
4163
+ * @returns {Object} for chaining
4164
+ */
4165
+ getWatched() {
4166
+ const watchList = {};
4167
+ this._watched.forEach((entry, dir) => {
4168
+ const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
4169
+ watchList[key || ONE_DOT] = entry.getChildren().sort();
4170
+ });
4171
+ return watchList;
4172
+ }
4173
+
4174
+ emitWithAll(event, args) {
4175
+ this.emit(...args);
4176
+ if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
4177
+ }
4178
+
4179
+ // Common helpers
4180
+ // --------------
4181
+
4182
+ /**
4183
+ * Normalize and emit events.
4184
+ * Calling _emit DOES NOT MEAN emit() would be called!
4185
+ * @param {EventName} event Type of event
4186
+ * @param {Path} path File or directory path
4187
+ * @param {*=} val1 arguments to be passed with event
4188
+ * @param {*=} val2
4189
+ * @param {*=} val3
4190
+ * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
4191
+ */
4192
+ async _emit(event, path, val1, val2, val3) {
4193
+ if (this.closed) return;
4194
+
4195
+ const opts = this.options;
4196
+ if (isWindows) path = sysPath.normalize(path);
4197
+ if (opts.cwd) path = sysPath.relative(opts.cwd, path);
4198
+ /** @type Array<any> */
4199
+ const args = [event, path];
4200
+ if (val3 !== undefined) args.push(val1, val2, val3);
4201
+ else if (val2 !== undefined) args.push(val1, val2);
4202
+ else if (val1 !== undefined) args.push(val1);
4203
+
4204
+ const awf = opts.awaitWriteFinish;
4205
+ let pw;
4206
+ if (awf && (pw = this._pendingWrites.get(path))) {
4207
+ pw.lastChange = new Date();
4208
+ return this;
4209
+ }
4210
+
4211
+ if (opts.atomic) {
4212
+ if (event === EV_UNLINK) {
4213
+ this._pendingUnlinks.set(path, args);
4214
+ setTimeout(() => {
4215
+ this._pendingUnlinks.forEach((entry, path) => {
4216
+ this.emit(...entry);
4217
+ this.emit(EV_ALL, ...entry);
4218
+ this._pendingUnlinks.delete(path);
4219
+ });
4220
+ }, typeof opts.atomic === 'number' ? opts.atomic : 100);
4221
+ return this;
4222
+ }
4223
+ if (event === EV_ADD && this._pendingUnlinks.has(path)) {
4224
+ event = args[0] = EV_CHANGE;
4225
+ this._pendingUnlinks.delete(path);
4226
+ }
4227
+ }
4228
+
4229
+ if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
4230
+ const awfEmit = (err, stats) => {
4231
+ if (err) {
4232
+ event = args[0] = EV_ERROR;
4233
+ args[1] = err;
4234
+ this.emitWithAll(event, args);
4235
+ } else if (stats) {
4236
+ // if stats doesn't exist the file must have been deleted
4237
+ if (args.length > 2) {
4238
+ args[2] = stats;
4239
+ } else {
4240
+ args.push(stats);
4241
+ }
4242
+ this.emitWithAll(event, args);
4243
+ }
4244
+ };
4245
+
4246
+ this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
4247
+ return this;
4248
+ }
4249
+
4250
+ if (event === EV_CHANGE) {
4251
+ const isThrottled = !this._throttle(EV_CHANGE, path, 50);
4252
+ if (isThrottled) return this;
4253
+ }
4254
+
4255
+ if (opts.alwaysStat && val1 === undefined &&
4256
+ (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)
4257
+ ) {
4258
+ const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
4259
+ let stats;
4260
+ try {
4261
+ stats = await stat(fullPath);
4262
+ } catch (err) {}
4263
+ // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
4264
+ if (!stats || this.closed) return;
4265
+ args.push(stats);
4266
+ }
4267
+ this.emitWithAll(event, args);
4268
+
4269
+ return this;
4270
+ }
4271
+
4272
+ /**
4273
+ * Common handler for errors
4274
+ * @param {Error} error
4275
+ * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
4276
+ */
4277
+ _handleError(error) {
4278
+ const code = error && error.code;
4279
+ if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&
4280
+ (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))
4281
+ ) {
4282
+ this.emit(EV_ERROR, error);
4283
+ }
4284
+ return error || this.closed;
4285
+ }
4286
+
4287
+ /**
4288
+ * Helper utility for throttling
4289
+ * @param {ThrottleType} actionType type being throttled
4290
+ * @param {Path} path being acted upon
4291
+ * @param {Number} timeout duration of time to suppress duplicate actions
4292
+ * @returns {Object|false} tracking object or false if action should be suppressed
4293
+ */
4294
+ _throttle(actionType, path, timeout) {
4295
+ if (!this._throttled.has(actionType)) {
4296
+ this._throttled.set(actionType, new Map());
4297
+ }
4298
+
4299
+ /** @type {Map<Path, Object>} */
4300
+ const action = this._throttled.get(actionType);
4301
+ /** @type {Object} */
4302
+ const actionPath = action.get(path);
4303
+
4304
+ if (actionPath) {
4305
+ actionPath.count++;
4306
+ return false;
4307
+ }
4308
+
4309
+ let timeoutObject;
4310
+ const clear = () => {
4311
+ const item = action.get(path);
4312
+ const count = item ? item.count : 0;
4313
+ action.delete(path);
4314
+ clearTimeout(timeoutObject);
4315
+ if (item) clearTimeout(item.timeoutObject);
4316
+ return count;
4317
+ };
4318
+ timeoutObject = setTimeout(clear, timeout);
4319
+ const thr = {timeoutObject, clear, count: 0};
4320
+ action.set(path, thr);
4321
+ return thr;
4322
+ }
4323
+
4324
+ _incrReadyCount() {
4325
+ return this._readyCount++;
4326
+ }
4327
+
4328
+ /**
4329
+ * Awaits write operation to finish.
4330
+ * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
4331
+ * @param {Path} path being acted upon
4332
+ * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
4333
+ * @param {EventName} event
4334
+ * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
4335
+ */
4336
+ _awaitWriteFinish(path, threshold, event, awfEmit) {
4337
+ let timeoutHandler;
4338
+
4339
+ let fullPath = path;
4340
+ if (this.options.cwd && !sysPath.isAbsolute(path)) {
4341
+ fullPath = sysPath.join(this.options.cwd, path);
4342
+ }
4343
+
4344
+ const now = new Date();
4345
+
4346
+ const awaitWriteFinish = (prevStat) => {
4347
+ fs.stat(fullPath, (err, curStat) => {
4348
+ if (err || !this._pendingWrites.has(path)) {
4349
+ if (err && err.code !== 'ENOENT') awfEmit(err);
4350
+ return;
4351
+ }
4352
+
4353
+ const now = Number(new Date());
4354
+
4355
+ if (prevStat && curStat.size !== prevStat.size) {
4356
+ this._pendingWrites.get(path).lastChange = now;
4357
+ }
4358
+ const pw = this._pendingWrites.get(path);
4359
+ const df = now - pw.lastChange;
4360
+
4361
+ if (df >= threshold) {
4362
+ this._pendingWrites.delete(path);
4363
+ awfEmit(undefined, curStat);
4364
+ } else {
4365
+ timeoutHandler = setTimeout(
4366
+ awaitWriteFinish,
4367
+ this.options.awaitWriteFinish.pollInterval,
4368
+ curStat
4369
+ );
4370
+ }
4371
+ });
4372
+ };
4373
+
4374
+ if (!this._pendingWrites.has(path)) {
4375
+ this._pendingWrites.set(path, {
4376
+ lastChange: now,
4377
+ cancelWait: () => {
4378
+ this._pendingWrites.delete(path);
4379
+ clearTimeout(timeoutHandler);
4380
+ return event;
4381
+ }
4382
+ });
4383
+ timeoutHandler = setTimeout(
4384
+ awaitWriteFinish,
4385
+ this.options.awaitWriteFinish.pollInterval
4386
+ );
4387
+ }
4388
+ }
4389
+
4390
+ _getGlobIgnored() {
4391
+ return [...this._ignoredPaths.values()];
4392
+ }
4393
+
4394
+ /**
4395
+ * Determines whether user has asked to ignore this path.
4396
+ * @param {Path} path filepath or dir
4397
+ * @param {fs.Stats=} stats result of fs.stat
4398
+ * @returns {Boolean}
4399
+ */
4400
+ _isIgnored(path, stats) {
4401
+ if (this.options.atomic && DOT_RE.test(path)) return true;
4402
+ if (!this._userIgnored) {
4403
+ const {cwd} = this.options;
4404
+ const ign = this.options.ignored;
4405
+
4406
+ const ignored = ign && ign.map(normalizeIgnored(cwd));
4407
+ const paths = arrify(ignored)
4408
+ .filter((path) => typeof path === STRING_TYPE && !isGlob(path))
4409
+ .map((path) => path + SLASH_GLOBSTAR);
4410
+ const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
4411
+ this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);
4412
+ }
4413
+
4414
+ return this._userIgnored([path, stats]);
4415
+ }
4416
+
4417
+ _isntIgnored(path, stat) {
4418
+ return !this._isIgnored(path, stat);
4419
+ }
4420
+
4421
+ /**
4422
+ * Provides a set of common helpers and properties relating to symlink and glob handling.
4423
+ * @param {Path} path file, directory, or glob pattern being watched
4424
+ * @param {Number=} depth at any depth > 0, this isn't a glob
4425
+ * @returns {WatchHelper} object containing helpers for this path
4426
+ */
4427
+ _getWatchHelpers(path, depth) {
4428
+ const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
4429
+ const follow = this.options.followSymlinks;
4430
+
4431
+ return new WatchHelper(path, watchPath, follow, this);
4432
+ }
4433
+
4434
+ // Directory helpers
4435
+ // -----------------
4436
+
4437
+ /**
4438
+ * Provides directory tracking objects
4439
+ * @param {String} directory path of the directory
4440
+ * @returns {DirEntry} the directory's tracking object
4441
+ */
4442
+ _getWatchedDir(directory) {
4443
+ if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
4444
+ const dir = sysPath.resolve(directory);
4445
+ if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
4446
+ return this._watched.get(dir);
4447
+ }
4448
+
4449
+ // File helpers
4450
+ // ------------
4451
+
4452
+ /**
4453
+ * Check for read permissions.
4454
+ * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
4455
+ * @param {fs.Stats} stats - object, result of fs_stat
4456
+ * @returns {Boolean} indicates whether the file can be read
4457
+ */
4458
+ _hasReadPermissions(stats) {
4459
+ if (this.options.ignorePermissionErrors) return true;
4460
+
4461
+ // stats.mode may be bigint
4462
+ const md = stats && Number.parseInt(stats.mode, 10);
4463
+ const st = md & 0o777;
4464
+ const it = Number.parseInt(st.toString(8)[0], 10);
4465
+ return Boolean(4 & it);
4466
+ }
4467
+
4468
+ /**
4469
+ * Handles emitting unlink events for
4470
+ * files and directories, and via recursion, for
4471
+ * files and directories within directories that are unlinked
4472
+ * @param {String} directory within which the following item is located
4473
+ * @param {String} item base path of item/directory
4474
+ * @returns {void}
4475
+ */
4476
+ _remove(directory, item, isDirectory) {
4477
+ // if what is being deleted is a directory, get that directory's paths
4478
+ // for recursive deleting and cleaning of watched object
4479
+ // if it is not a directory, nestedDirectoryChildren will be empty array
4480
+ const path = sysPath.join(directory, item);
4481
+ const fullPath = sysPath.resolve(path);
4482
+ isDirectory = isDirectory != null
4483
+ ? isDirectory
4484
+ : this._watched.has(path) || this._watched.has(fullPath);
4485
+
4486
+ // prevent duplicate handling in case of arriving here nearly simultaneously
4487
+ // via multiple paths (such as _handleFile and _handleDir)
4488
+ if (!this._throttle('remove', path, 100)) return;
4489
+
4490
+ // if the only watched file is removed, watch for its return
4491
+ if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {
4492
+ this.add(directory, item, true);
4493
+ }
4494
+
4495
+ // This will create a new entry in the watched object in either case
4496
+ // so we got to do the directory check beforehand
4497
+ const wp = this._getWatchedDir(path);
4498
+ const nestedDirectoryChildren = wp.getChildren();
4499
+
4500
+ // Recursively remove children directories / files.
4501
+ nestedDirectoryChildren.forEach(nested => this._remove(path, nested));
4502
+
4503
+ // Check if item was on the watched list and remove it
4504
+ const parent = this._getWatchedDir(directory);
4505
+ const wasTracked = parent.has(item);
4506
+ parent.remove(item);
4507
+
4508
+ // Fixes issue #1042 -> Relative paths were detected and added as symlinks
4509
+ // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
4510
+ // but never removed from the map in case the path was deleted.
4511
+ // This leads to an incorrect state if the path was recreated:
4512
+ // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
4513
+ if (this._symlinkPaths.has(fullPath)) {
4514
+ this._symlinkPaths.delete(fullPath);
4515
+ }
4516
+
4517
+ // If we wait for this file to be fully written, cancel the wait.
4518
+ let relPath = path;
4519
+ if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
4520
+ if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
4521
+ const event = this._pendingWrites.get(relPath).cancelWait();
4522
+ if (event === EV_ADD) return;
4523
+ }
4524
+
4525
+ // The Entry will either be a directory that just got removed
4526
+ // or a bogus entry to a file, in either case we have to remove it
4527
+ this._watched.delete(path);
4528
+ this._watched.delete(fullPath);
4529
+ const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
4530
+ if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
4531
+
4532
+ // Avoid conflicts if we later create another file with the same name
4533
+ if (!this.options.useFsEvents) {
4534
+ this._closePath(path);
4535
+ }
4536
+ }
4537
+
4538
+ /**
4539
+ * Closes all watchers for a path
4540
+ * @param {Path} path
4541
+ */
4542
+ _closePath(path) {
4543
+ this._closeFile(path);
4544
+ const dir = sysPath.dirname(path);
4545
+ this._getWatchedDir(dir).remove(sysPath.basename(path));
4546
+ }
4547
+
4548
+ /**
4549
+ * Closes only file-specific watchers
4550
+ * @param {Path} path
4551
+ */
4552
+ _closeFile(path) {
4553
+ const closers = this._closers.get(path);
4554
+ if (!closers) return;
4555
+ closers.forEach(closer => closer());
4556
+ this._closers.delete(path);
4557
+ }
4558
+
4559
+ /**
4560
+ *
4561
+ * @param {Path} path
4562
+ * @param {Function} closer
4563
+ */
4564
+ _addPathCloser(path, closer) {
4565
+ if (!closer) return;
4566
+ let list = this._closers.get(path);
4567
+ if (!list) {
4568
+ list = [];
4569
+ this._closers.set(path, list);
4570
+ }
4571
+ list.push(closer);
4572
+ }
4573
+
4574
+ _readdirp(root, opts) {
4575
+ if (this.closed) return;
4576
+ const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};
4577
+ let stream = readdirp(root, options);
4578
+ this._streams.add(stream);
4579
+ stream.once(STR_CLOSE, () => {
4580
+ stream = undefined;
4581
+ });
4582
+ stream.once(STR_END, () => {
4583
+ if (stream) {
4584
+ this._streams.delete(stream);
4585
+ stream = undefined;
4586
+ }
4587
+ });
4588
+ return stream;
4589
+ }
4590
+
4591
+ }
4592
+
4593
+ // Export FSWatcher class
4594
+ chokidar.FSWatcher = FSWatcher;
4595
+
4596
+ /**
4597
+ * Instantiates watcher with paths to be tracked.
4598
+ * @param {String|Array<String>} paths file/directory paths and/or globs
4599
+ * @param {Object=} options chokidar opts
4600
+ * @returns an instance of FSWatcher for chaining.
4601
+ */
4602
+ const watch = (paths, options) => {
4603
+ const watcher = new FSWatcher(options);
4604
+ watcher.add(paths);
4605
+ return watcher;
4606
+ };
4607
+
4608
+ chokidar.watch = watch;
4609
+
4610
+ exports.chokidar = chokidar;
4611
+ //# sourceMappingURL=index.js.map