rollup 4.0.0-1 → 4.0.0-2

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