rollup 2.57.0

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