@rollup/wasm-node 4.0.0-12

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