@andersbakken/fisk 3.5.7 → 3.6.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,4223 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ var require$$0 = require('fs');
5
+ var require$$1$1 = require('path');
6
+ var require$$1 = require('module');
7
+ var os$1 = require('os');
8
+ var EventEmitter = require('events');
9
+ var require$$0$1 = require('constants');
10
+ var require$$0$2 = require('stream');
11
+ var require$$4 = require('util');
12
+ var assert$1 = require('assert');
13
+ var net = require('net');
14
+
15
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
16
+
17
+ var require$$0__default = /*#__PURE__*/_interopDefaultLegacy(require$$0);
18
+ var require$$1__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$1$1);
19
+ var require$$1__default = /*#__PURE__*/_interopDefaultLegacy(require$$1);
20
+ var os__default = /*#__PURE__*/_interopDefaultLegacy(os$1);
21
+ var EventEmitter__default = /*#__PURE__*/_interopDefaultLegacy(EventEmitter);
22
+ var require$$0__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$0$1);
23
+ var require$$0__default$2 = /*#__PURE__*/_interopDefaultLegacy(require$$0$2);
24
+ var require$$4__default = /*#__PURE__*/_interopDefaultLegacy(require$$4);
25
+ var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert$1);
26
+ var net__default = /*#__PURE__*/_interopDefaultLegacy(net);
27
+
28
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
29
+
30
+ var resolve;
31
+ var hasRequiredResolve;
32
+
33
+ function requireResolve () {
34
+ if (hasRequiredResolve) return resolve;
35
+ hasRequiredResolve = 1;
36
+
37
+ // Dependencies
38
+ var path = require$$1__default$1["default"];
39
+
40
+ // Load global paths
41
+ var globalPaths = require$$1__default["default"].globalPaths;
42
+
43
+ // Guess at NPM's global install dir
44
+ var npmGlobalPrefix;
45
+ if ('win32' === process.platform) {
46
+ npmGlobalPrefix = path.dirname(process.execPath);
47
+ } else {
48
+ npmGlobalPrefix = path.dirname(path.dirname(process.execPath));
49
+ }
50
+ var npmGlobalModuleDir = path.resolve(npmGlobalPrefix, 'lib', 'node_modules');
51
+
52
+ // Save OS-specific path separator
53
+ var sep = path.sep;
54
+
55
+ // If we're in webpack, force it to use the original require() method
56
+ var requireFunction = ("function" === typeof __webpack_require__ || "function" === typeof __non_webpack_require__)
57
+ ? __non_webpack_require__
58
+ : require;
59
+
60
+ // Resolver
61
+ resolve = function resolve(dirname) {
62
+ // Check for environmental variable
63
+ if (process.env.APP_ROOT_PATH) {
64
+ return path.resolve(process.env.APP_ROOT_PATH);
65
+ }
66
+
67
+ // Defer to Yarn Plug'n'Play if enabled
68
+ if (process.versions.pnp) {
69
+ try {
70
+ var pnp = requireFunction('pnpapi');
71
+ return pnp.getPackageInformation(pnp.topLevel).packageLocation;
72
+ } catch (e) {}
73
+ }
74
+
75
+ // Defer to main process in electron renderer
76
+ if ('undefined' !== typeof window && window.process && 'renderer' === window.process.type) {
77
+ try {
78
+ var remote = requireFunction('electron').remote;
79
+ return remote.require('app-root-path').path;
80
+ } catch (e) {}
81
+ }
82
+
83
+ // Defer to AWS Lambda when executing there
84
+ if (process.env.LAMBDA_TASK_ROOT && process.env.AWS_EXECUTION_ENV) {
85
+ return process.env.LAMBDA_TASK_ROOT;
86
+ }
87
+
88
+ var resolved = path.resolve(dirname);
89
+ var alternateMethod = false;
90
+ var appRootPath = null;
91
+
92
+ // Make sure that we're not loaded from a global include path
93
+ // Eg. $HOME/.node_modules
94
+ // $HOME/.node_libraries
95
+ // $PREFIX/lib/node
96
+ globalPaths.forEach(function(globalPath) {
97
+ if (!alternateMethod && 0 === resolved.indexOf(globalPath)) {
98
+ alternateMethod = true;
99
+ }
100
+ });
101
+
102
+ // If the app-root-path library isn't loaded globally,
103
+ // and node_modules exists in the path, just split __dirname
104
+ var nodeModulesDir = sep + 'node_modules';
105
+ if (!alternateMethod && -1 !== resolved.indexOf(nodeModulesDir)) {
106
+ var parts = resolved.split(nodeModulesDir);
107
+ if (parts.length) {
108
+ appRootPath = parts[0];
109
+ parts = null;
110
+ }
111
+ }
112
+
113
+ // If the above didn't work, or this module is loaded globally, then
114
+ // resort to require.main.filename (See http://nodejs.org/api/modules.html)
115
+ if (alternateMethod || null == appRootPath) {
116
+ appRootPath = path.dirname(require.main.filename);
117
+ }
118
+
119
+ // Handle global bin/ directory edge-case
120
+ if (alternateMethod && -1 !== appRootPath.indexOf(npmGlobalModuleDir) && (appRootPath.length - 4) === appRootPath.indexOf(sep + 'bin')) {
121
+ appRootPath = appRootPath.slice(0, -4);
122
+ }
123
+
124
+ // Return
125
+ return appRootPath;
126
+ };
127
+ return resolve;
128
+ }
129
+
130
+ var appRootPath$1 = function(dirname) {
131
+ var path = require$$1__default$1["default"];
132
+ var resolve = requireResolve();
133
+ var appRootPath = resolve(dirname);
134
+
135
+ var publicInterface = {
136
+ resolve: function(pathToModule) {
137
+ return path.join(appRootPath, pathToModule);
138
+ },
139
+
140
+ require: function(pathToModule) {
141
+ return require(publicInterface.resolve(pathToModule));
142
+ },
143
+
144
+ toString: function() {
145
+ return appRootPath;
146
+ },
147
+
148
+ setPath: function(explicitlySetPath) {
149
+ appRootPath = path.resolve(explicitlySetPath);
150
+ publicInterface.path = appRootPath;
151
+ },
152
+
153
+ path: appRootPath
154
+ };
155
+
156
+ return publicInterface;
157
+ };
158
+
159
+ var lib$1 = appRootPath$1;
160
+ var appRootPath = lib$1(__dirname);
161
+
162
+ var xdgBasedir = {};
163
+
164
+ (function (exports) {
165
+ const os = os__default["default"];
166
+ const path = require$$1__default$1["default"];
167
+
168
+ const home = os.homedir();
169
+ const env = process.env;
170
+
171
+ exports.data = env.XDG_DATA_HOME ||
172
+ (home ? path.join(home, '.local', 'share') : null);
173
+
174
+ exports.config = env.XDG_CONFIG_HOME ||
175
+ (home ? path.join(home, '.config') : null);
176
+
177
+ exports.cache = env.XDG_CACHE_HOME || (home ? path.join(home, '.cache') : null);
178
+
179
+ exports.runtime = env.XDG_RUNTIME_DIR || null;
180
+
181
+ exports.dataDirs = (env.XDG_DATA_DIRS || '/usr/local/share/:/usr/share/').split(':');
182
+
183
+ if (exports.data) {
184
+ exports.dataDirs.unshift(exports.data);
185
+ }
186
+
187
+ exports.configDirs = (env.XDG_CONFIG_DIRS || '/etc/xdg').split(':');
188
+
189
+ if (exports.config) {
190
+ exports.configDirs.unshift(exports.config);
191
+ }
192
+ } (xdgBasedir));
193
+
194
+ var minimist;
195
+ var hasRequiredMinimist;
196
+
197
+ function requireMinimist () {
198
+ if (hasRequiredMinimist) return minimist;
199
+ hasRequiredMinimist = 1;
200
+ minimist = function (args, opts) {
201
+ if (!opts) opts = {};
202
+
203
+ var flags = { bools : {}, strings : {}, unknownFn: null };
204
+
205
+ if (typeof opts['unknown'] === 'function') {
206
+ flags.unknownFn = opts['unknown'];
207
+ }
208
+
209
+ if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
210
+ flags.allBools = true;
211
+ } else {
212
+ [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
213
+ flags.bools[key] = true;
214
+ });
215
+ }
216
+
217
+ var aliases = {};
218
+ Object.keys(opts.alias || {}).forEach(function (key) {
219
+ aliases[key] = [].concat(opts.alias[key]);
220
+ aliases[key].forEach(function (x) {
221
+ aliases[x] = [key].concat(aliases[key].filter(function (y) {
222
+ return x !== y;
223
+ }));
224
+ });
225
+ });
226
+
227
+ [].concat(opts.string).filter(Boolean).forEach(function (key) {
228
+ flags.strings[key] = true;
229
+ if (aliases[key]) {
230
+ flags.strings[aliases[key]] = true;
231
+ }
232
+ });
233
+
234
+ var defaults = opts['default'] || {};
235
+
236
+ var argv = { _ : [] };
237
+ Object.keys(flags.bools).forEach(function (key) {
238
+ setArg(key, defaults[key] === undefined ? false : defaults[key]);
239
+ });
240
+
241
+ var notFlags = [];
242
+
243
+ if (args.indexOf('--') !== -1) {
244
+ notFlags = args.slice(args.indexOf('--')+1);
245
+ args = args.slice(0, args.indexOf('--'));
246
+ }
247
+
248
+ function argDefined(key, arg) {
249
+ return (flags.allBools && /^--[^=]+$/.test(arg)) ||
250
+ flags.strings[key] || flags.bools[key] || aliases[key];
251
+ }
252
+
253
+ function setArg (key, val, arg) {
254
+ if (arg && flags.unknownFn && !argDefined(key, arg)) {
255
+ if (flags.unknownFn(arg) === false) return;
256
+ }
257
+
258
+ var value = !flags.strings[key] && isNumber(val)
259
+ ? Number(val) : val
260
+ ;
261
+ setKey(argv, key.split('.'), value);
262
+
263
+ (aliases[key] || []).forEach(function (x) {
264
+ setKey(argv, x.split('.'), value);
265
+ });
266
+ }
267
+
268
+ function setKey (obj, keys, value) {
269
+ var o = obj;
270
+ for (var i = 0; i < keys.length-1; i++) {
271
+ var key = keys[i];
272
+ if (isConstructorOrProto(o, key)) return;
273
+ if (o[key] === undefined) o[key] = {};
274
+ if (o[key] === Object.prototype || o[key] === Number.prototype
275
+ || o[key] === String.prototype) o[key] = {};
276
+ if (o[key] === Array.prototype) o[key] = [];
277
+ o = o[key];
278
+ }
279
+
280
+ var key = keys[keys.length - 1];
281
+ if (isConstructorOrProto(o, key)) return;
282
+ if (o === Object.prototype || o === Number.prototype
283
+ || o === String.prototype) o = {};
284
+ if (o === Array.prototype) o = [];
285
+ if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
286
+ o[key] = value;
287
+ }
288
+ else if (Array.isArray(o[key])) {
289
+ o[key].push(value);
290
+ }
291
+ else {
292
+ o[key] = [ o[key], value ];
293
+ }
294
+ }
295
+
296
+ function aliasIsBoolean(key) {
297
+ return aliases[key].some(function (x) {
298
+ return flags.bools[x];
299
+ });
300
+ }
301
+
302
+ for (var i = 0; i < args.length; i++) {
303
+ var arg = args[i];
304
+
305
+ if (/^--.+=/.test(arg)) {
306
+ // Using [\s\S] instead of . because js doesn't support the
307
+ // 'dotall' regex modifier. See:
308
+ // http://stackoverflow.com/a/1068308/13216
309
+ var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
310
+ var key = m[1];
311
+ var value = m[2];
312
+ if (flags.bools[key]) {
313
+ value = value !== 'false';
314
+ }
315
+ setArg(key, value, arg);
316
+ }
317
+ else if (/^--no-.+/.test(arg)) {
318
+ var key = arg.match(/^--no-(.+)/)[1];
319
+ setArg(key, false, arg);
320
+ }
321
+ else if (/^--.+/.test(arg)) {
322
+ var key = arg.match(/^--(.+)/)[1];
323
+ var next = args[i + 1];
324
+ if (next !== undefined && !/^-/.test(next)
325
+ && !flags.bools[key]
326
+ && !flags.allBools
327
+ && (aliases[key] ? !aliasIsBoolean(key) : true)) {
328
+ setArg(key, next, arg);
329
+ i++;
330
+ }
331
+ else if (/^(true|false)$/.test(next)) {
332
+ setArg(key, next === 'true', arg);
333
+ i++;
334
+ }
335
+ else {
336
+ setArg(key, flags.strings[key] ? '' : true, arg);
337
+ }
338
+ }
339
+ else if (/^-[^-]+/.test(arg)) {
340
+ var letters = arg.slice(1,-1).split('');
341
+
342
+ var broken = false;
343
+ for (var j = 0; j < letters.length; j++) {
344
+ var next = arg.slice(j+2);
345
+
346
+ if (next === '-') {
347
+ setArg(letters[j], next, arg);
348
+ continue;
349
+ }
350
+
351
+ if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
352
+ setArg(letters[j], next.split('=')[1], arg);
353
+ broken = true;
354
+ break;
355
+ }
356
+
357
+ if (/[A-Za-z]/.test(letters[j])
358
+ && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
359
+ setArg(letters[j], next, arg);
360
+ broken = true;
361
+ break;
362
+ }
363
+
364
+ if (letters[j+1] && letters[j+1].match(/\W/)) {
365
+ setArg(letters[j], arg.slice(j+2), arg);
366
+ broken = true;
367
+ break;
368
+ }
369
+ else {
370
+ setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
371
+ }
372
+ }
373
+
374
+ var key = arg.slice(-1)[0];
375
+ if (!broken && key !== '-') {
376
+ if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
377
+ && !flags.bools[key]
378
+ && (aliases[key] ? !aliasIsBoolean(key) : true)) {
379
+ setArg(key, args[i+1], arg);
380
+ i++;
381
+ }
382
+ else if (args[i+1] && /^(true|false)$/.test(args[i+1])) {
383
+ setArg(key, args[i+1] === 'true', arg);
384
+ i++;
385
+ }
386
+ else {
387
+ setArg(key, flags.strings[key] ? '' : true, arg);
388
+ }
389
+ }
390
+ }
391
+ else {
392
+ if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
393
+ argv._.push(
394
+ flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
395
+ );
396
+ }
397
+ if (opts.stopEarly) {
398
+ argv._.push.apply(argv._, args.slice(i + 1));
399
+ break;
400
+ }
401
+ }
402
+ }
403
+
404
+ Object.keys(defaults).forEach(function (key) {
405
+ if (!hasKey(argv, key.split('.'))) {
406
+ setKey(argv, key.split('.'), defaults[key]);
407
+
408
+ (aliases[key] || []).forEach(function (x) {
409
+ setKey(argv, x.split('.'), defaults[key]);
410
+ });
411
+ }
412
+ });
413
+
414
+ if (opts['--']) {
415
+ argv['--'] = new Array();
416
+ notFlags.forEach(function(key) {
417
+ argv['--'].push(key);
418
+ });
419
+ }
420
+ else {
421
+ notFlags.forEach(function(key) {
422
+ argv._.push(key);
423
+ });
424
+ }
425
+
426
+ return argv;
427
+ };
428
+
429
+ function hasKey (obj, keys) {
430
+ var o = obj;
431
+ keys.slice(0,-1).forEach(function (key) {
432
+ o = (o[key] || {});
433
+ });
434
+
435
+ var key = keys[keys.length - 1];
436
+ return key in o;
437
+ }
438
+
439
+ function isNumber (x) {
440
+ if (typeof x === 'number') return true;
441
+ if (/^0x[0-9a-f]+$/i.test(x)) return true;
442
+ return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
443
+ }
444
+
445
+
446
+ function isConstructorOrProto (obj, key) {
447
+ return key === 'constructor' && typeof obj[key] === 'function' || key === '__proto__';
448
+ }
449
+ return minimist;
450
+ }
451
+
452
+ /*global require,module,process*/
453
+
454
+ const fs$k = require$$0__default["default"];
455
+ const path$h = require$$1__default$1["default"];
456
+ const appPath = appRootPath;
457
+ const xdg = xdgBasedir;
458
+
459
+ function split(data)
460
+ {
461
+ const pre = data.split("\n");
462
+ // rejoin with lines that starts with a whitespace
463
+ const out = [];
464
+ let cur = "";
465
+ for (let i = 0; i < pre.length; ++i) {
466
+ let line = pre[i].replace(/\t/g, " ");
467
+ if (!line.length)
468
+ continue;
469
+ if (!cur.length || /\s/.test(line[0])) {
470
+ let idx = 0;
471
+ while (/\s/.test(line[idx]))
472
+ ++idx;
473
+ cur += line.substr(idx ? idx - 1 : 0);
474
+ idx = cur.length - 1;
475
+ while (idx >= 0 && /\s/.test(cur[idx]))
476
+ --idx;
477
+ if (idx < cur.length - 1)
478
+ cur = cur.substr(0, idx + 1);
479
+ } else if (cur.length > 0) {
480
+ out.push(cur.trim());
481
+ cur = line.trim();
482
+ }
483
+ }
484
+ if (cur.length > 0) {
485
+ out.push(cur.trim());
486
+ }
487
+ return out;
488
+ }
489
+
490
+ function realValue(v)
491
+ {
492
+ if (typeof v !== "string")
493
+ return v;
494
+ if (/^[-0-9.]+$/.exec(v)) {
495
+ const vf = parseFloat(v);
496
+ if (!isNaN(vf))
497
+ return vf;
498
+ }
499
+ switch (v) {
500
+ case "true":
501
+ return true;
502
+ case "false":
503
+ return false;
504
+ }
505
+ return v;
506
+ }
507
+
508
+ class Options {
509
+ constructor(options, argv) {
510
+ this.argv = Object.assign({}, argv);
511
+ this.prefix = options.prefix;
512
+ this.additionalFiles = options.additionalFiles || [];
513
+ this.applicationPath = options.noApplicationPath ? "" : appPath.toString();
514
+ this.debug = options.debug;
515
+ this.options = {};
516
+ this.configDirs = this.argv["config-dir"] || options.configDirs || xdg.configDirs;
517
+ this._read();
518
+ }
519
+
520
+ value(name) {
521
+ // foo-bar becomes FOO_BAR as env
522
+ if (name in this.argv)
523
+ return this.argv[name];
524
+ const envname = (this.prefix + "_" + name).replace(/-/g, "_").toUpperCase();
525
+ if (envname in process.env)
526
+ return realValue(process.env[envname]);
527
+
528
+ if (name in this.options)
529
+ return this.options[name];
530
+ return undefined;
531
+ }
532
+
533
+ _homedir() {
534
+ let home = process.env.home;
535
+ if (home) {
536
+ return path$h.join(home, ".config");
537
+ }
538
+ return undefined;
539
+ }
540
+
541
+ _log(...args) {
542
+ if (this.debug)
543
+ console.log(...args);
544
+ }
545
+
546
+ _read() {
547
+ // if we have a config file passed, read it
548
+ let file = this.value("config-file");
549
+ if (!file && this.prefix)
550
+ file = this.prefix + ".conf";
551
+ if (!file)
552
+ return;
553
+
554
+ let data = [];
555
+ let seen = new Set();
556
+ const Failed = 0;
557
+ const Success = 1;
558
+ const Seen = 2;
559
+ const read = file => {
560
+ if (seen.has(file))
561
+ return Seen;
562
+ seen.add(file);
563
+ try {
564
+ const contents = fs$k.readFileSync(file, "utf8");
565
+ this._log(`Loaded ${contents.length} bytes from ${file}`);
566
+
567
+ if (contents) {
568
+ data.push({ file: file, contents: contents });
569
+ return Success;
570
+ }
571
+ } catch (e) {
572
+ this._log(`Failed to load ${file}`);
573
+ }
574
+ return Failed;
575
+ };
576
+
577
+ // console.log("about to read file", file, "additionalFiles", this.additionalFiles, "configDirs", this.configDirs, "applicationPath", this.applicationPath, "homedir", this._homedir());
578
+ if (path$h.isAbsolute(file)) {
579
+ read(file);
580
+ } else {
581
+ this.additionalFiles.forEach(file => {
582
+ if (path$h.isAbsolute(file) && read(file) == Failed)
583
+ read(file + ".conf");
584
+ });
585
+ ([this.applicationPath, this._homedir()].concat(this.configDirs)).forEach(root => {
586
+ // in case we appended with undefined
587
+ if (!root)
588
+ return;
589
+ this.additionalFiles.forEach(additional => {
590
+ if (!path$h.isAbsolute(additional)) {
591
+ let file = path$h.join(root, additional);
592
+ if (read(file) == Failed)
593
+ read(file + ".conf");
594
+ }
595
+ });
596
+
597
+ let filePath = path$h.join(root, file);
598
+ if (read(filePath) == Failed)
599
+ read(filePath + ".conf");
600
+ });
601
+ }
602
+ for (let i = data.length - 1; i >= 0; --i) {
603
+ let str = data[i].contents;
604
+ if (!str)
605
+ continue;
606
+ try {
607
+ let obj = JSON.parse(str);
608
+ for (let key in obj) {
609
+ this._log(`Assigning ${JSON.stringify(obj[key])} over ${JSON.stringify(this.options[key])} for ${key} from ${data[i].file} (JSON)`);
610
+ this.options[key] = obj[key];
611
+ }
612
+ } catch (err) {
613
+ const items = split(str);
614
+ for (let j = 0; j < items.length; ++j) {
615
+ const item = items[j].trim();
616
+ if (!item.length)
617
+ continue;
618
+ if (item[0] === "#")
619
+ continue;
620
+ const eq = item.indexOf("=");
621
+ if (eq === -1) {
622
+ this._log("Couldn't find =", item);
623
+ continue;
624
+ }
625
+ const key = item.substr(0, eq).trim();
626
+ if (!key.length) {
627
+ this._log("empty key", item);
628
+ continue;
629
+ }
630
+ const value = item.substr(eq + 1).trim();
631
+ this._log(`Assigning ${value} over ${this.options[key]} for ${key} from ${data[i].file} (INI)`);
632
+ this.options[key] = value;
633
+ }
634
+ }
635
+ }
636
+ }
637
+ }
638
+
639
+ const data = {};
640
+
641
+ var options = function(options, argv) {
642
+ if (!argv)
643
+ argv = requireMinimist()(process.argv.slice(2));
644
+ if (!(options instanceof Object))
645
+ options = { prefix: options || "" };
646
+
647
+ data.options = new Options(options, argv);
648
+ let ret = function(name, defaultValue) {
649
+ const val = data.options.value(name);
650
+ if (typeof val === "undefined")
651
+ return defaultValue;
652
+ return val;
653
+ };
654
+ ret.prefix = options.prefix;
655
+ ret.int = function(name, defaultValue) {
656
+ const v = parseInt(data.options.value(name));
657
+ if (typeof v === "number" && !isNaN(v))
658
+ return v;
659
+ return defaultValue;
660
+ };
661
+ ret.float = function(name, defaultValue) {
662
+ const v = parseFloat(data.options.value(name));
663
+ if (typeof v === "number" && !isNaN(v))
664
+ return v;
665
+ return defaultValue;
666
+ };
667
+ ret.json = function(name, defaultValue) {
668
+ const opt = data.options.value(name);
669
+ if (opt === undefined)
670
+ return defaultValue;
671
+ if (typeof opt !== "string")
672
+ return opt;
673
+ try {
674
+ const json = JSON.parse(opt);
675
+ return json;
676
+ } catch (e) {
677
+ }
678
+ return defaultValue;
679
+ };
680
+ return ret;
681
+ };
682
+
683
+ const Constants = {
684
+ // client codes
685
+ get AcquireCppSlot() {
686
+ return 1;
687
+ },
688
+ get AcquireCompileSlot() {
689
+ return 2;
690
+ },
691
+ get ReleaseCppSlot() {
692
+ return 3;
693
+ },
694
+ get ReleaseCompileSlot() {
695
+ return 4;
696
+ },
697
+ get JSON() {
698
+ return 5;
699
+ },
700
+ // daemon codes
701
+ get CppSlotAcquired() {
702
+ return 10;
703
+ },
704
+ get CompileSlotAcquired() {
705
+ return 11;
706
+ },
707
+ get JSONResponse() {
708
+ return 12;
709
+ }
710
+ };
711
+
712
+ class ClientBuffer {
713
+ constructor() {
714
+ this.buffers = [];
715
+ this.offset = 0;
716
+ }
717
+ write(buffer) {
718
+ this.buffers.push(buffer);
719
+ // console.log("write", buffer.length, this.buffers.length, this.available);
720
+ }
721
+ peek() {
722
+ if (!this.available) {
723
+ throw new Error("No data available");
724
+ }
725
+ return this.buffers[0][this.offset];
726
+ }
727
+ read(len) {
728
+ if (!len) {
729
+ throw new Error("Don't be a tool");
730
+ }
731
+ if (len > this.available) {
732
+ throw new Error("We don't have this many bytes available " + len + ">" + this.available);
733
+ }
734
+ // console.log("read", len, this.available);
735
+ let ret;
736
+ if (this.buffers[0].length - this.offset >= len) {
737
+ // buffers[0] is enough
738
+ const buf = this.buffers[0];
739
+ if (buf.length - this.offset === len) {
740
+ ret = this.offset ? buf.slice(this.offset) : buf;
741
+ this.offset = 0;
742
+ this.buffers.splice(0, 1);
743
+ return ret;
744
+ }
745
+ ret = buf.slice(this.offset, this.offset + len);
746
+ this.offset += len;
747
+ return ret;
748
+ }
749
+ ret = Buffer.allocUnsafe(len);
750
+ let retOffset = 0;
751
+ this.buffers[0].copy(ret, 0, this.offset);
752
+ retOffset += this.buffers[0].length - this.offset;
753
+ this.offset = 0;
754
+ this.buffers.splice(0, 1);
755
+ while (retOffset < len) {
756
+ const needed = len - retOffset;
757
+ const buf = this.buffers[0];
758
+ if (buf.length <= needed) {
759
+ this.buffers[0].copy(ret, retOffset);
760
+ retOffset += this.buffers[0].length;
761
+ this.buffers.splice(0, 1);
762
+ }
763
+ else {
764
+ this.buffers[0].copy(ret, retOffset, 0, needed);
765
+ retOffset += needed;
766
+ this.offset = needed;
767
+ }
768
+ }
769
+ return ret;
770
+ }
771
+ get available() {
772
+ return this.buffers.reduce((total, buf) => total + buf.length, 0) - this.offset;
773
+ }
774
+ }
775
+
776
+ class Compile extends EventEmitter__default["default"] {
777
+ constructor(conn, id, option) {
778
+ super();
779
+ this.debug = option("debug");
780
+ this.id = id;
781
+ this.connection = conn;
782
+ this.buffer = new ClientBuffer();
783
+ this.messageLength = 0;
784
+ this.pid = undefined;
785
+ this.connection.on("data", this._onData.bind(this));
786
+ this.connection.on("end", () => {
787
+ // console.log("connection ended", id);
788
+ this.emit("end");
789
+ });
790
+ this.connection.on("error", (err) => {
791
+ // console.log("connection error", id, err);
792
+ this.emit("error", err);
793
+ });
794
+ }
795
+ send(message) {
796
+ if (this.debug) {
797
+ console.log("Compile::send", message);
798
+ }
799
+ try {
800
+ if (typeof message === "number") {
801
+ this.connection.write(Buffer.from([message]));
802
+ }
803
+ else {
804
+ const msg = Buffer.from(JSON.stringify(message), "utf8");
805
+ const header = Buffer.allocUnsafe(5);
806
+ header.writeUInt8(Constants.JSONResponse, 0);
807
+ header.writeUInt32BE(msg.length, 1);
808
+ if (this.debug) {
809
+ console.log("Compile::send header", header, Constants.JSONResponse);
810
+ }
811
+ this.connection.write(header);
812
+ this.connection.write(msg);
813
+ }
814
+ }
815
+ catch (err) {
816
+ console.error("Got error sending message", err);
817
+ }
818
+ }
819
+ _onData(data) {
820
+ // console.log("got data", data.length);
821
+ this.buffer.write(data);
822
+ let available = this.buffer.available;
823
+ if (this.debug) {
824
+ console.log("Compile::_onData", "id", this.id, "pid", this.pid, data, "available", available, this.messageLength);
825
+ }
826
+ if (!this.pid) {
827
+ if (available < 4) {
828
+ return;
829
+ }
830
+ const pidBuffer = this.buffer.read(4);
831
+ available -= 4;
832
+ this.pid = pidBuffer.readUInt32BE();
833
+ if (this.debug) {
834
+ console.log("Compile::_onData got pid", "id", this.id, "pid", this.pid);
835
+ }
836
+ }
837
+ const emit = (type) => {
838
+ if (this.debug) {
839
+ console.log("Compile::_onData::emit", type, available);
840
+ }
841
+ const read = this.buffer.read(1);
842
+ if (this.debug) {
843
+ console.log("Discarded", read);
844
+ }
845
+ --available;
846
+ this.emit(type);
847
+ };
848
+ while (available) {
849
+ if (!this.messageLength) {
850
+ if (this.debug) {
851
+ console.log("peeking", this.buffer.peek());
852
+ }
853
+ switch (this.buffer.peek()) {
854
+ case Constants.AcquireCppSlot:
855
+ emit("acquireCppSlot");
856
+ continue;
857
+ case Constants.AcquireCompileSlot:
858
+ emit("acquireCompileSlot");
859
+ continue;
860
+ case Constants.ReleaseCppSlot:
861
+ emit("releaseCppSlot");
862
+ continue;
863
+ case Constants.ReleaseCompileSlot:
864
+ emit("releaseCompileSlot");
865
+ continue;
866
+ case Constants.JSON:
867
+ if (available < 5) {
868
+ break;
869
+ }
870
+ this.buffer.read(1);
871
+ this.messageLength = this.buffer.read(4).readUInt32BE();
872
+ available -= 5;
873
+ break;
874
+ default:
875
+ console.error("Bad data", this.buffer.peek(), "available", available);
876
+ throw new Error("Got unexpected type " + this.buffer.peek());
877
+ }
878
+ }
879
+ if (!this.messageLength || this.messageLength > available) {
880
+ // console.log("Still waiting on data", this.messageLength, this.buffer.available);
881
+ break;
882
+ }
883
+ const raw = this.buffer.read(this.messageLength);
884
+ available -= this.messageLength;
885
+ this.messageLength = 0;
886
+ try {
887
+ const msg = JSON.parse(raw.toString("utf8"));
888
+ if (this.debug) {
889
+ console.log("Got json message", msg);
890
+ }
891
+ // console.log("Got message", msg);
892
+ this.emit(msg.type, msg);
893
+ }
894
+ catch (err) {
895
+ console.error("Bad JSON received", err);
896
+ this.connection.destroy();
897
+ break;
898
+ }
899
+ }
900
+ }
901
+ }
902
+
903
+ var libExports = {};
904
+ var lib = {
905
+ get exports(){ return libExports; },
906
+ set exports(v){ libExports = v; },
907
+ };
908
+
909
+ var fs$j = {};
910
+
911
+ var universalify = {};
912
+
913
+ universalify.fromCallback = function (fn) {
914
+ return Object.defineProperty(function () {
915
+ if (typeof arguments[arguments.length - 1] === 'function') fn.apply(this, arguments);
916
+ else {
917
+ return new Promise((resolve, reject) => {
918
+ arguments[arguments.length] = (err, res) => {
919
+ if (err) return reject(err)
920
+ resolve(res);
921
+ };
922
+ arguments.length++;
923
+ fn.apply(this, arguments);
924
+ })
925
+ }
926
+ }, 'name', { value: fn.name })
927
+ };
928
+
929
+ universalify.fromPromise = function (fn) {
930
+ return Object.defineProperty(function () {
931
+ const cb = arguments[arguments.length - 1];
932
+ if (typeof cb !== 'function') return fn.apply(this, arguments)
933
+ else fn.apply(this, arguments).then(r => cb(null, r), cb);
934
+ }, 'name', { value: fn.name })
935
+ };
936
+
937
+ var constants = require$$0__default$1["default"];
938
+
939
+ var origCwd = process.cwd;
940
+ var cwd = null;
941
+
942
+ var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;
943
+
944
+ process.cwd = function() {
945
+ if (!cwd)
946
+ cwd = origCwd.call(process);
947
+ return cwd
948
+ };
949
+ try {
950
+ process.cwd();
951
+ } catch (er) {}
952
+
953
+ // This check is needed until node.js 12 is required
954
+ if (typeof process.chdir === 'function') {
955
+ var chdir = process.chdir;
956
+ process.chdir = function (d) {
957
+ cwd = null;
958
+ chdir.call(process, d);
959
+ };
960
+ if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir);
961
+ }
962
+
963
+ var polyfills$1 = patch$1;
964
+
965
+ function patch$1 (fs) {
966
+ // (re-)implement some things that are known busted or missing.
967
+
968
+ // lchmod, broken prior to 0.6.2
969
+ // back-port the fix here.
970
+ if (constants.hasOwnProperty('O_SYMLINK') &&
971
+ process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
972
+ patchLchmod(fs);
973
+ }
974
+
975
+ // lutimes implementation, or no-op
976
+ if (!fs.lutimes) {
977
+ patchLutimes(fs);
978
+ }
979
+
980
+ // https://github.com/isaacs/node-graceful-fs/issues/4
981
+ // Chown should not fail on einval or eperm if non-root.
982
+ // It should not fail on enosys ever, as this just indicates
983
+ // that a fs doesn't support the intended operation.
984
+
985
+ fs.chown = chownFix(fs.chown);
986
+ fs.fchown = chownFix(fs.fchown);
987
+ fs.lchown = chownFix(fs.lchown);
988
+
989
+ fs.chmod = chmodFix(fs.chmod);
990
+ fs.fchmod = chmodFix(fs.fchmod);
991
+ fs.lchmod = chmodFix(fs.lchmod);
992
+
993
+ fs.chownSync = chownFixSync(fs.chownSync);
994
+ fs.fchownSync = chownFixSync(fs.fchownSync);
995
+ fs.lchownSync = chownFixSync(fs.lchownSync);
996
+
997
+ fs.chmodSync = chmodFixSync(fs.chmodSync);
998
+ fs.fchmodSync = chmodFixSync(fs.fchmodSync);
999
+ fs.lchmodSync = chmodFixSync(fs.lchmodSync);
1000
+
1001
+ fs.stat = statFix(fs.stat);
1002
+ fs.fstat = statFix(fs.fstat);
1003
+ fs.lstat = statFix(fs.lstat);
1004
+
1005
+ fs.statSync = statFixSync(fs.statSync);
1006
+ fs.fstatSync = statFixSync(fs.fstatSync);
1007
+ fs.lstatSync = statFixSync(fs.lstatSync);
1008
+
1009
+ // if lchmod/lchown do not exist, then make them no-ops
1010
+ if (fs.chmod && !fs.lchmod) {
1011
+ fs.lchmod = function (path, mode, cb) {
1012
+ if (cb) process.nextTick(cb);
1013
+ };
1014
+ fs.lchmodSync = function () {};
1015
+ }
1016
+ if (fs.chown && !fs.lchown) {
1017
+ fs.lchown = function (path, uid, gid, cb) {
1018
+ if (cb) process.nextTick(cb);
1019
+ };
1020
+ fs.lchownSync = function () {};
1021
+ }
1022
+
1023
+ // on Windows, A/V software can lock the directory, causing this
1024
+ // to fail with an EACCES or EPERM if the directory contains newly
1025
+ // created files. Try again on failure, for up to 60 seconds.
1026
+
1027
+ // Set the timeout this long because some Windows Anti-Virus, such as Parity
1028
+ // bit9, may lock files for up to a minute, causing npm package install
1029
+ // failures. Also, take care to yield the scheduler. Windows scheduling gives
1030
+ // CPU to a busy looping process, which can cause the program causing the lock
1031
+ // contention to be starved of CPU by node, so the contention doesn't resolve.
1032
+ if (platform === "win32") {
1033
+ fs.rename = typeof fs.rename !== 'function' ? fs.rename
1034
+ : (function (fs$rename) {
1035
+ function rename (from, to, cb) {
1036
+ var start = Date.now();
1037
+ var backoff = 0;
1038
+ fs$rename(from, to, function CB (er) {
1039
+ if (er
1040
+ && (er.code === "EACCES" || er.code === "EPERM")
1041
+ && Date.now() - start < 60000) {
1042
+ setTimeout(function() {
1043
+ fs.stat(to, function (stater, st) {
1044
+ if (stater && stater.code === "ENOENT")
1045
+ fs$rename(from, to, CB);
1046
+ else
1047
+ cb(er);
1048
+ });
1049
+ }, backoff);
1050
+ if (backoff < 100)
1051
+ backoff += 10;
1052
+ return;
1053
+ }
1054
+ if (cb) cb(er);
1055
+ });
1056
+ }
1057
+ if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename);
1058
+ return rename
1059
+ })(fs.rename);
1060
+ }
1061
+
1062
+ // if read() returns EAGAIN, then just try it again.
1063
+ fs.read = typeof fs.read !== 'function' ? fs.read
1064
+ : (function (fs$read) {
1065
+ function read (fd, buffer, offset, length, position, callback_) {
1066
+ var callback;
1067
+ if (callback_ && typeof callback_ === 'function') {
1068
+ var eagCounter = 0;
1069
+ callback = function (er, _, __) {
1070
+ if (er && er.code === 'EAGAIN' && eagCounter < 10) {
1071
+ eagCounter ++;
1072
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback)
1073
+ }
1074
+ callback_.apply(this, arguments);
1075
+ };
1076
+ }
1077
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback)
1078
+ }
1079
+
1080
+ // This ensures `util.promisify` works as it does for native `fs.read`.
1081
+ if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read);
1082
+ return read
1083
+ })(fs.read);
1084
+
1085
+ fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync
1086
+ : (function (fs$readSync) { return function (fd, buffer, offset, length, position) {
1087
+ var eagCounter = 0;
1088
+ while (true) {
1089
+ try {
1090
+ return fs$readSync.call(fs, fd, buffer, offset, length, position)
1091
+ } catch (er) {
1092
+ if (er.code === 'EAGAIN' && eagCounter < 10) {
1093
+ eagCounter ++;
1094
+ continue
1095
+ }
1096
+ throw er
1097
+ }
1098
+ }
1099
+ }})(fs.readSync);
1100
+
1101
+ function patchLchmod (fs) {
1102
+ fs.lchmod = function (path, mode, callback) {
1103
+ fs.open( path
1104
+ , constants.O_WRONLY | constants.O_SYMLINK
1105
+ , mode
1106
+ , function (err, fd) {
1107
+ if (err) {
1108
+ if (callback) callback(err);
1109
+ return
1110
+ }
1111
+ // prefer to return the chmod error, if one occurs,
1112
+ // but still try to close, and report closing errors if they occur.
1113
+ fs.fchmod(fd, mode, function (err) {
1114
+ fs.close(fd, function(err2) {
1115
+ if (callback) callback(err || err2);
1116
+ });
1117
+ });
1118
+ });
1119
+ };
1120
+
1121
+ fs.lchmodSync = function (path, mode) {
1122
+ var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode);
1123
+
1124
+ // prefer to return the chmod error, if one occurs,
1125
+ // but still try to close, and report closing errors if they occur.
1126
+ var threw = true;
1127
+ var ret;
1128
+ try {
1129
+ ret = fs.fchmodSync(fd, mode);
1130
+ threw = false;
1131
+ } finally {
1132
+ if (threw) {
1133
+ try {
1134
+ fs.closeSync(fd);
1135
+ } catch (er) {}
1136
+ } else {
1137
+ fs.closeSync(fd);
1138
+ }
1139
+ }
1140
+ return ret
1141
+ };
1142
+ }
1143
+
1144
+ function patchLutimes (fs) {
1145
+ if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) {
1146
+ fs.lutimes = function (path, at, mt, cb) {
1147
+ fs.open(path, constants.O_SYMLINK, function (er, fd) {
1148
+ if (er) {
1149
+ if (cb) cb(er);
1150
+ return
1151
+ }
1152
+ fs.futimes(fd, at, mt, function (er) {
1153
+ fs.close(fd, function (er2) {
1154
+ if (cb) cb(er || er2);
1155
+ });
1156
+ });
1157
+ });
1158
+ };
1159
+
1160
+ fs.lutimesSync = function (path, at, mt) {
1161
+ var fd = fs.openSync(path, constants.O_SYMLINK);
1162
+ var ret;
1163
+ var threw = true;
1164
+ try {
1165
+ ret = fs.futimesSync(fd, at, mt);
1166
+ threw = false;
1167
+ } finally {
1168
+ if (threw) {
1169
+ try {
1170
+ fs.closeSync(fd);
1171
+ } catch (er) {}
1172
+ } else {
1173
+ fs.closeSync(fd);
1174
+ }
1175
+ }
1176
+ return ret
1177
+ };
1178
+
1179
+ } else if (fs.futimes) {
1180
+ fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb); };
1181
+ fs.lutimesSync = function () {};
1182
+ }
1183
+ }
1184
+
1185
+ function chmodFix (orig) {
1186
+ if (!orig) return orig
1187
+ return function (target, mode, cb) {
1188
+ return orig.call(fs, target, mode, function (er) {
1189
+ if (chownErOk(er)) er = null;
1190
+ if (cb) cb.apply(this, arguments);
1191
+ })
1192
+ }
1193
+ }
1194
+
1195
+ function chmodFixSync (orig) {
1196
+ if (!orig) return orig
1197
+ return function (target, mode) {
1198
+ try {
1199
+ return orig.call(fs, target, mode)
1200
+ } catch (er) {
1201
+ if (!chownErOk(er)) throw er
1202
+ }
1203
+ }
1204
+ }
1205
+
1206
+
1207
+ function chownFix (orig) {
1208
+ if (!orig) return orig
1209
+ return function (target, uid, gid, cb) {
1210
+ return orig.call(fs, target, uid, gid, function (er) {
1211
+ if (chownErOk(er)) er = null;
1212
+ if (cb) cb.apply(this, arguments);
1213
+ })
1214
+ }
1215
+ }
1216
+
1217
+ function chownFixSync (orig) {
1218
+ if (!orig) return orig
1219
+ return function (target, uid, gid) {
1220
+ try {
1221
+ return orig.call(fs, target, uid, gid)
1222
+ } catch (er) {
1223
+ if (!chownErOk(er)) throw er
1224
+ }
1225
+ }
1226
+ }
1227
+
1228
+ function statFix (orig) {
1229
+ if (!orig) return orig
1230
+ // Older versions of Node erroneously returned signed integers for
1231
+ // uid + gid.
1232
+ return function (target, options, cb) {
1233
+ if (typeof options === 'function') {
1234
+ cb = options;
1235
+ options = null;
1236
+ }
1237
+ function callback (er, stats) {
1238
+ if (stats) {
1239
+ if (stats.uid < 0) stats.uid += 0x100000000;
1240
+ if (stats.gid < 0) stats.gid += 0x100000000;
1241
+ }
1242
+ if (cb) cb.apply(this, arguments);
1243
+ }
1244
+ return options ? orig.call(fs, target, options, callback)
1245
+ : orig.call(fs, target, callback)
1246
+ }
1247
+ }
1248
+
1249
+ function statFixSync (orig) {
1250
+ if (!orig) return orig
1251
+ // Older versions of Node erroneously returned signed integers for
1252
+ // uid + gid.
1253
+ return function (target, options) {
1254
+ var stats = options ? orig.call(fs, target, options)
1255
+ : orig.call(fs, target);
1256
+ if (stats) {
1257
+ if (stats.uid < 0) stats.uid += 0x100000000;
1258
+ if (stats.gid < 0) stats.gid += 0x100000000;
1259
+ }
1260
+ return stats;
1261
+ }
1262
+ }
1263
+
1264
+ // ENOSYS means that the fs doesn't support the op. Just ignore
1265
+ // that, because it doesn't matter.
1266
+ //
1267
+ // if there's no getuid, or if getuid() is something other
1268
+ // than 0, and the error is EINVAL or EPERM, then just ignore
1269
+ // it.
1270
+ //
1271
+ // This specific case is a silent failure in cp, install, tar,
1272
+ // and most other unix tools that manage permissions.
1273
+ //
1274
+ // When running as root, or if other types of errors are
1275
+ // encountered, then it's strict.
1276
+ function chownErOk (er) {
1277
+ if (!er)
1278
+ return true
1279
+
1280
+ if (er.code === "ENOSYS")
1281
+ return true
1282
+
1283
+ var nonroot = !process.getuid || process.getuid() !== 0;
1284
+ if (nonroot) {
1285
+ if (er.code === "EINVAL" || er.code === "EPERM")
1286
+ return true
1287
+ }
1288
+
1289
+ return false
1290
+ }
1291
+ }
1292
+
1293
+ var Stream = require$$0__default$2["default"].Stream;
1294
+
1295
+ var legacyStreams = legacy$1;
1296
+
1297
+ function legacy$1 (fs) {
1298
+ return {
1299
+ ReadStream: ReadStream,
1300
+ WriteStream: WriteStream
1301
+ }
1302
+
1303
+ function ReadStream (path, options) {
1304
+ if (!(this instanceof ReadStream)) return new ReadStream(path, options);
1305
+
1306
+ Stream.call(this);
1307
+
1308
+ var self = this;
1309
+
1310
+ this.path = path;
1311
+ this.fd = null;
1312
+ this.readable = true;
1313
+ this.paused = false;
1314
+
1315
+ this.flags = 'r';
1316
+ this.mode = 438; /*=0666*/
1317
+ this.bufferSize = 64 * 1024;
1318
+
1319
+ options = options || {};
1320
+
1321
+ // Mixin options into this
1322
+ var keys = Object.keys(options);
1323
+ for (var index = 0, length = keys.length; index < length; index++) {
1324
+ var key = keys[index];
1325
+ this[key] = options[key];
1326
+ }
1327
+
1328
+ if (this.encoding) this.setEncoding(this.encoding);
1329
+
1330
+ if (this.start !== undefined) {
1331
+ if ('number' !== typeof this.start) {
1332
+ throw TypeError('start must be a Number');
1333
+ }
1334
+ if (this.end === undefined) {
1335
+ this.end = Infinity;
1336
+ } else if ('number' !== typeof this.end) {
1337
+ throw TypeError('end must be a Number');
1338
+ }
1339
+
1340
+ if (this.start > this.end) {
1341
+ throw new Error('start must be <= end');
1342
+ }
1343
+
1344
+ this.pos = this.start;
1345
+ }
1346
+
1347
+ if (this.fd !== null) {
1348
+ process.nextTick(function() {
1349
+ self._read();
1350
+ });
1351
+ return;
1352
+ }
1353
+
1354
+ fs.open(this.path, this.flags, this.mode, function (err, fd) {
1355
+ if (err) {
1356
+ self.emit('error', err);
1357
+ self.readable = false;
1358
+ return;
1359
+ }
1360
+
1361
+ self.fd = fd;
1362
+ self.emit('open', fd);
1363
+ self._read();
1364
+ });
1365
+ }
1366
+
1367
+ function WriteStream (path, options) {
1368
+ if (!(this instanceof WriteStream)) return new WriteStream(path, options);
1369
+
1370
+ Stream.call(this);
1371
+
1372
+ this.path = path;
1373
+ this.fd = null;
1374
+ this.writable = true;
1375
+
1376
+ this.flags = 'w';
1377
+ this.encoding = 'binary';
1378
+ this.mode = 438; /*=0666*/
1379
+ this.bytesWritten = 0;
1380
+
1381
+ options = options || {};
1382
+
1383
+ // Mixin options into this
1384
+ var keys = Object.keys(options);
1385
+ for (var index = 0, length = keys.length; index < length; index++) {
1386
+ var key = keys[index];
1387
+ this[key] = options[key];
1388
+ }
1389
+
1390
+ if (this.start !== undefined) {
1391
+ if ('number' !== typeof this.start) {
1392
+ throw TypeError('start must be a Number');
1393
+ }
1394
+ if (this.start < 0) {
1395
+ throw new Error('start must be >= zero');
1396
+ }
1397
+
1398
+ this.pos = this.start;
1399
+ }
1400
+
1401
+ this.busy = false;
1402
+ this._queue = [];
1403
+
1404
+ if (this.fd === null) {
1405
+ this._open = fs.open;
1406
+ this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
1407
+ this.flush();
1408
+ }
1409
+ }
1410
+ }
1411
+
1412
+ var clone_1 = clone$1;
1413
+
1414
+ var getPrototypeOf = Object.getPrototypeOf || function (obj) {
1415
+ return obj.__proto__
1416
+ };
1417
+
1418
+ function clone$1 (obj) {
1419
+ if (obj === null || typeof obj !== 'object')
1420
+ return obj
1421
+
1422
+ if (obj instanceof Object)
1423
+ var copy = { __proto__: getPrototypeOf(obj) };
1424
+ else
1425
+ var copy = Object.create(null);
1426
+
1427
+ Object.getOwnPropertyNames(obj).forEach(function (key) {
1428
+ Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
1429
+ });
1430
+
1431
+ return copy
1432
+ }
1433
+
1434
+ var fs$i = require$$0__default["default"];
1435
+ var polyfills = polyfills$1;
1436
+ var legacy = legacyStreams;
1437
+ var clone = clone_1;
1438
+
1439
+ var util = require$$4__default["default"];
1440
+
1441
+ /* istanbul ignore next - node 0.x polyfill */
1442
+ var gracefulQueue;
1443
+ var previousSymbol;
1444
+
1445
+ /* istanbul ignore else - node 0.x polyfill */
1446
+ if (typeof Symbol === 'function' && typeof Symbol.for === 'function') {
1447
+ gracefulQueue = Symbol.for('graceful-fs.queue');
1448
+ // This is used in testing by future versions
1449
+ previousSymbol = Symbol.for('graceful-fs.previous');
1450
+ } else {
1451
+ gracefulQueue = '___graceful-fs.queue';
1452
+ previousSymbol = '___graceful-fs.previous';
1453
+ }
1454
+
1455
+ function noop () {}
1456
+
1457
+ function publishQueue(context, queue) {
1458
+ Object.defineProperty(context, gracefulQueue, {
1459
+ get: function() {
1460
+ return queue
1461
+ }
1462
+ });
1463
+ }
1464
+
1465
+ var debug$1 = noop;
1466
+ if (util.debuglog)
1467
+ debug$1 = util.debuglog('gfs4');
1468
+ else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))
1469
+ debug$1 = function() {
1470
+ var m = util.format.apply(util, arguments);
1471
+ m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ');
1472
+ console.error(m);
1473
+ };
1474
+
1475
+ // Once time initialization
1476
+ if (!fs$i[gracefulQueue]) {
1477
+ // This queue can be shared by multiple loaded instances
1478
+ var queue = commonjsGlobal[gracefulQueue] || [];
1479
+ publishQueue(fs$i, queue);
1480
+
1481
+ // Patch fs.close/closeSync to shared queue version, because we need
1482
+ // to retry() whenever a close happens *anywhere* in the program.
1483
+ // This is essential when multiple graceful-fs instances are
1484
+ // in play at the same time.
1485
+ fs$i.close = (function (fs$close) {
1486
+ function close (fd, cb) {
1487
+ return fs$close.call(fs$i, fd, function (err) {
1488
+ // This function uses the graceful-fs shared queue
1489
+ if (!err) {
1490
+ resetQueue();
1491
+ }
1492
+
1493
+ if (typeof cb === 'function')
1494
+ cb.apply(this, arguments);
1495
+ })
1496
+ }
1497
+
1498
+ Object.defineProperty(close, previousSymbol, {
1499
+ value: fs$close
1500
+ });
1501
+ return close
1502
+ })(fs$i.close);
1503
+
1504
+ fs$i.closeSync = (function (fs$closeSync) {
1505
+ function closeSync (fd) {
1506
+ // This function uses the graceful-fs shared queue
1507
+ fs$closeSync.apply(fs$i, arguments);
1508
+ resetQueue();
1509
+ }
1510
+
1511
+ Object.defineProperty(closeSync, previousSymbol, {
1512
+ value: fs$closeSync
1513
+ });
1514
+ return closeSync
1515
+ })(fs$i.closeSync);
1516
+
1517
+ if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
1518
+ process.on('exit', function() {
1519
+ debug$1(fs$i[gracefulQueue]);
1520
+ assert__default["default"].equal(fs$i[gracefulQueue].length, 0);
1521
+ });
1522
+ }
1523
+ }
1524
+
1525
+ if (!commonjsGlobal[gracefulQueue]) {
1526
+ publishQueue(commonjsGlobal, fs$i[gracefulQueue]);
1527
+ }
1528
+
1529
+ var gracefulFs = patch(clone(fs$i));
1530
+ if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs$i.__patched) {
1531
+ gracefulFs = patch(fs$i);
1532
+ fs$i.__patched = true;
1533
+ }
1534
+
1535
+ function patch (fs) {
1536
+ // Everything that references the open() function needs to be in here
1537
+ polyfills(fs);
1538
+ fs.gracefulify = patch;
1539
+
1540
+ fs.createReadStream = createReadStream;
1541
+ fs.createWriteStream = createWriteStream;
1542
+ var fs$readFile = fs.readFile;
1543
+ fs.readFile = readFile;
1544
+ function readFile (path, options, cb) {
1545
+ if (typeof options === 'function')
1546
+ cb = options, options = null;
1547
+
1548
+ return go$readFile(path, options, cb)
1549
+
1550
+ function go$readFile (path, options, cb, startTime) {
1551
+ return fs$readFile(path, options, function (err) {
1552
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
1553
+ enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]);
1554
+ else {
1555
+ if (typeof cb === 'function')
1556
+ cb.apply(this, arguments);
1557
+ }
1558
+ })
1559
+ }
1560
+ }
1561
+
1562
+ var fs$writeFile = fs.writeFile;
1563
+ fs.writeFile = writeFile;
1564
+ function writeFile (path, data, options, cb) {
1565
+ if (typeof options === 'function')
1566
+ cb = options, options = null;
1567
+
1568
+ return go$writeFile(path, data, options, cb)
1569
+
1570
+ function go$writeFile (path, data, options, cb, startTime) {
1571
+ return fs$writeFile(path, data, options, function (err) {
1572
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
1573
+ enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]);
1574
+ else {
1575
+ if (typeof cb === 'function')
1576
+ cb.apply(this, arguments);
1577
+ }
1578
+ })
1579
+ }
1580
+ }
1581
+
1582
+ var fs$appendFile = fs.appendFile;
1583
+ if (fs$appendFile)
1584
+ fs.appendFile = appendFile;
1585
+ function appendFile (path, data, options, cb) {
1586
+ if (typeof options === 'function')
1587
+ cb = options, options = null;
1588
+
1589
+ return go$appendFile(path, data, options, cb)
1590
+
1591
+ function go$appendFile (path, data, options, cb, startTime) {
1592
+ return fs$appendFile(path, data, options, function (err) {
1593
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
1594
+ enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]);
1595
+ else {
1596
+ if (typeof cb === 'function')
1597
+ cb.apply(this, arguments);
1598
+ }
1599
+ })
1600
+ }
1601
+ }
1602
+
1603
+ var fs$copyFile = fs.copyFile;
1604
+ if (fs$copyFile)
1605
+ fs.copyFile = copyFile;
1606
+ function copyFile (src, dest, flags, cb) {
1607
+ if (typeof flags === 'function') {
1608
+ cb = flags;
1609
+ flags = 0;
1610
+ }
1611
+ return go$copyFile(src, dest, flags, cb)
1612
+
1613
+ function go$copyFile (src, dest, flags, cb, startTime) {
1614
+ return fs$copyFile(src, dest, flags, function (err) {
1615
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
1616
+ enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]);
1617
+ else {
1618
+ if (typeof cb === 'function')
1619
+ cb.apply(this, arguments);
1620
+ }
1621
+ })
1622
+ }
1623
+ }
1624
+
1625
+ var fs$readdir = fs.readdir;
1626
+ fs.readdir = readdir;
1627
+ var noReaddirOptionVersions = /^v[0-5]\./;
1628
+ function readdir (path, options, cb) {
1629
+ if (typeof options === 'function')
1630
+ cb = options, options = null;
1631
+
1632
+ var go$readdir = noReaddirOptionVersions.test(process.version)
1633
+ ? function go$readdir (path, options, cb, startTime) {
1634
+ return fs$readdir(path, fs$readdirCallback(
1635
+ path, options, cb, startTime
1636
+ ))
1637
+ }
1638
+ : function go$readdir (path, options, cb, startTime) {
1639
+ return fs$readdir(path, options, fs$readdirCallback(
1640
+ path, options, cb, startTime
1641
+ ))
1642
+ };
1643
+
1644
+ return go$readdir(path, options, cb)
1645
+
1646
+ function fs$readdirCallback (path, options, cb, startTime) {
1647
+ return function (err, files) {
1648
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
1649
+ enqueue([
1650
+ go$readdir,
1651
+ [path, options, cb],
1652
+ err,
1653
+ startTime || Date.now(),
1654
+ Date.now()
1655
+ ]);
1656
+ else {
1657
+ if (files && files.sort)
1658
+ files.sort();
1659
+
1660
+ if (typeof cb === 'function')
1661
+ cb.call(this, err, files);
1662
+ }
1663
+ }
1664
+ }
1665
+ }
1666
+
1667
+ if (process.version.substr(0, 4) === 'v0.8') {
1668
+ var legStreams = legacy(fs);
1669
+ ReadStream = legStreams.ReadStream;
1670
+ WriteStream = legStreams.WriteStream;
1671
+ }
1672
+
1673
+ var fs$ReadStream = fs.ReadStream;
1674
+ if (fs$ReadStream) {
1675
+ ReadStream.prototype = Object.create(fs$ReadStream.prototype);
1676
+ ReadStream.prototype.open = ReadStream$open;
1677
+ }
1678
+
1679
+ var fs$WriteStream = fs.WriteStream;
1680
+ if (fs$WriteStream) {
1681
+ WriteStream.prototype = Object.create(fs$WriteStream.prototype);
1682
+ WriteStream.prototype.open = WriteStream$open;
1683
+ }
1684
+
1685
+ Object.defineProperty(fs, 'ReadStream', {
1686
+ get: function () {
1687
+ return ReadStream
1688
+ },
1689
+ set: function (val) {
1690
+ ReadStream = val;
1691
+ },
1692
+ enumerable: true,
1693
+ configurable: true
1694
+ });
1695
+ Object.defineProperty(fs, 'WriteStream', {
1696
+ get: function () {
1697
+ return WriteStream
1698
+ },
1699
+ set: function (val) {
1700
+ WriteStream = val;
1701
+ },
1702
+ enumerable: true,
1703
+ configurable: true
1704
+ });
1705
+
1706
+ // legacy names
1707
+ var FileReadStream = ReadStream;
1708
+ Object.defineProperty(fs, 'FileReadStream', {
1709
+ get: function () {
1710
+ return FileReadStream
1711
+ },
1712
+ set: function (val) {
1713
+ FileReadStream = val;
1714
+ },
1715
+ enumerable: true,
1716
+ configurable: true
1717
+ });
1718
+ var FileWriteStream = WriteStream;
1719
+ Object.defineProperty(fs, 'FileWriteStream', {
1720
+ get: function () {
1721
+ return FileWriteStream
1722
+ },
1723
+ set: function (val) {
1724
+ FileWriteStream = val;
1725
+ },
1726
+ enumerable: true,
1727
+ configurable: true
1728
+ });
1729
+
1730
+ function ReadStream (path, options) {
1731
+ if (this instanceof ReadStream)
1732
+ return fs$ReadStream.apply(this, arguments), this
1733
+ else
1734
+ return ReadStream.apply(Object.create(ReadStream.prototype), arguments)
1735
+ }
1736
+
1737
+ function ReadStream$open () {
1738
+ var that = this;
1739
+ open(that.path, that.flags, that.mode, function (err, fd) {
1740
+ if (err) {
1741
+ if (that.autoClose)
1742
+ that.destroy();
1743
+
1744
+ that.emit('error', err);
1745
+ } else {
1746
+ that.fd = fd;
1747
+ that.emit('open', fd);
1748
+ that.read();
1749
+ }
1750
+ });
1751
+ }
1752
+
1753
+ function WriteStream (path, options) {
1754
+ if (this instanceof WriteStream)
1755
+ return fs$WriteStream.apply(this, arguments), this
1756
+ else
1757
+ return WriteStream.apply(Object.create(WriteStream.prototype), arguments)
1758
+ }
1759
+
1760
+ function WriteStream$open () {
1761
+ var that = this;
1762
+ open(that.path, that.flags, that.mode, function (err, fd) {
1763
+ if (err) {
1764
+ that.destroy();
1765
+ that.emit('error', err);
1766
+ } else {
1767
+ that.fd = fd;
1768
+ that.emit('open', fd);
1769
+ }
1770
+ });
1771
+ }
1772
+
1773
+ function createReadStream (path, options) {
1774
+ return new fs.ReadStream(path, options)
1775
+ }
1776
+
1777
+ function createWriteStream (path, options) {
1778
+ return new fs.WriteStream(path, options)
1779
+ }
1780
+
1781
+ var fs$open = fs.open;
1782
+ fs.open = open;
1783
+ function open (path, flags, mode, cb) {
1784
+ if (typeof mode === 'function')
1785
+ cb = mode, mode = null;
1786
+
1787
+ return go$open(path, flags, mode, cb)
1788
+
1789
+ function go$open (path, flags, mode, cb, startTime) {
1790
+ return fs$open(path, flags, mode, function (err, fd) {
1791
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
1792
+ enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]);
1793
+ else {
1794
+ if (typeof cb === 'function')
1795
+ cb.apply(this, arguments);
1796
+ }
1797
+ })
1798
+ }
1799
+ }
1800
+
1801
+ return fs
1802
+ }
1803
+
1804
+ function enqueue (elem) {
1805
+ debug$1('ENQUEUE', elem[0].name, elem[1]);
1806
+ fs$i[gracefulQueue].push(elem);
1807
+ retry();
1808
+ }
1809
+
1810
+ // keep track of the timeout between retry() calls
1811
+ var retryTimer;
1812
+
1813
+ // reset the startTime and lastTime to now
1814
+ // this resets the start of the 60 second overall timeout as well as the
1815
+ // delay between attempts so that we'll retry these jobs sooner
1816
+ function resetQueue () {
1817
+ var now = Date.now();
1818
+ for (var i = 0; i < fs$i[gracefulQueue].length; ++i) {
1819
+ // entries that are only a length of 2 are from an older version, don't
1820
+ // bother modifying those since they'll be retried anyway.
1821
+ if (fs$i[gracefulQueue][i].length > 2) {
1822
+ fs$i[gracefulQueue][i][3] = now; // startTime
1823
+ fs$i[gracefulQueue][i][4] = now; // lastTime
1824
+ }
1825
+ }
1826
+ // call retry to make sure we're actively processing the queue
1827
+ retry();
1828
+ }
1829
+
1830
+ function retry () {
1831
+ // clear the timer and remove it to help prevent unintended concurrency
1832
+ clearTimeout(retryTimer);
1833
+ retryTimer = undefined;
1834
+
1835
+ if (fs$i[gracefulQueue].length === 0)
1836
+ return
1837
+
1838
+ var elem = fs$i[gracefulQueue].shift();
1839
+ var fn = elem[0];
1840
+ var args = elem[1];
1841
+ // these items may be unset if they were added by an older graceful-fs
1842
+ var err = elem[2];
1843
+ var startTime = elem[3];
1844
+ var lastTime = elem[4];
1845
+
1846
+ // if we don't have a startTime we have no way of knowing if we've waited
1847
+ // long enough, so go ahead and retry this item now
1848
+ if (startTime === undefined) {
1849
+ debug$1('RETRY', fn.name, args);
1850
+ fn.apply(null, args);
1851
+ } else if (Date.now() - startTime >= 60000) {
1852
+ // it's been more than 60 seconds total, bail now
1853
+ debug$1('TIMEOUT', fn.name, args);
1854
+ var cb = args.pop();
1855
+ if (typeof cb === 'function')
1856
+ cb.call(null, err);
1857
+ } else {
1858
+ // the amount of time between the last attempt and right now
1859
+ var sinceAttempt = Date.now() - lastTime;
1860
+ // the amount of time between when we first tried, and when we last tried
1861
+ // rounded up to at least 1
1862
+ var sinceStart = Math.max(lastTime - startTime, 1);
1863
+ // backoff. wait longer than the total time we've been retrying, but only
1864
+ // up to a maximum of 100ms
1865
+ var desiredDelay = Math.min(sinceStart * 1.2, 100);
1866
+ // it's been long enough since the last retry, do it again
1867
+ if (sinceAttempt >= desiredDelay) {
1868
+ debug$1('RETRY', fn.name, args);
1869
+ fn.apply(null, args.concat([startTime]));
1870
+ } else {
1871
+ // if we can't do this job yet, push it to the end of the queue
1872
+ // and let the next iteration check again
1873
+ fs$i[gracefulQueue].push(elem);
1874
+ }
1875
+ }
1876
+
1877
+ // schedule our next run if one isn't already scheduled
1878
+ if (retryTimer === undefined) {
1879
+ retryTimer = setTimeout(retry, 0);
1880
+ }
1881
+ }
1882
+
1883
+ (function (exports) {
1884
+ // This is adapted from https://github.com/normalize/mz
1885
+ // Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors
1886
+ const u = universalify.fromCallback;
1887
+ const fs = gracefulFs;
1888
+
1889
+ const api = [
1890
+ 'access',
1891
+ 'appendFile',
1892
+ 'chmod',
1893
+ 'chown',
1894
+ 'close',
1895
+ 'copyFile',
1896
+ 'fchmod',
1897
+ 'fchown',
1898
+ 'fdatasync',
1899
+ 'fstat',
1900
+ 'fsync',
1901
+ 'ftruncate',
1902
+ 'futimes',
1903
+ 'lchown',
1904
+ 'link',
1905
+ 'lstat',
1906
+ 'mkdir',
1907
+ 'mkdtemp',
1908
+ 'open',
1909
+ 'readFile',
1910
+ 'readdir',
1911
+ 'readlink',
1912
+ 'realpath',
1913
+ 'rename',
1914
+ 'rmdir',
1915
+ 'stat',
1916
+ 'symlink',
1917
+ 'truncate',
1918
+ 'unlink',
1919
+ 'utimes',
1920
+ 'writeFile'
1921
+ ].filter(key => {
1922
+ // Some commands are not available on some systems. Ex:
1923
+ // fs.copyFile was added in Node.js v8.5.0
1924
+ // fs.mkdtemp was added in Node.js v5.10.0
1925
+ // fs.lchown is not available on at least some Linux
1926
+ return typeof fs[key] === 'function'
1927
+ });
1928
+
1929
+ // Export all keys:
1930
+ Object.keys(fs).forEach(key => {
1931
+ if (key === 'promises') {
1932
+ // fs.promises is a getter property that triggers ExperimentalWarning
1933
+ // Don't re-export it here, the getter is defined in "lib/index.js"
1934
+ return
1935
+ }
1936
+ exports[key] = fs[key];
1937
+ });
1938
+
1939
+ // Universalify async methods:
1940
+ api.forEach(method => {
1941
+ exports[method] = u(fs[method]);
1942
+ });
1943
+
1944
+ // We differ from mz/fs in that we still ship the old, broken, fs.exists()
1945
+ // since we are a drop-in replacement for the native module
1946
+ exports.exists = function (filename, callback) {
1947
+ if (typeof callback === 'function') {
1948
+ return fs.exists(filename, callback)
1949
+ }
1950
+ return new Promise(resolve => {
1951
+ return fs.exists(filename, resolve)
1952
+ })
1953
+ };
1954
+
1955
+ // fs.read() & fs.write need special treatment due to multiple callback args
1956
+
1957
+ exports.read = function (fd, buffer, offset, length, position, callback) {
1958
+ if (typeof callback === 'function') {
1959
+ return fs.read(fd, buffer, offset, length, position, callback)
1960
+ }
1961
+ return new Promise((resolve, reject) => {
1962
+ fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => {
1963
+ if (err) return reject(err)
1964
+ resolve({ bytesRead, buffer });
1965
+ });
1966
+ })
1967
+ };
1968
+
1969
+ // Function signature can be
1970
+ // fs.write(fd, buffer[, offset[, length[, position]]], callback)
1971
+ // OR
1972
+ // fs.write(fd, string[, position[, encoding]], callback)
1973
+ // We need to handle both cases, so we use ...args
1974
+ exports.write = function (fd, buffer, ...args) {
1975
+ if (typeof args[args.length - 1] === 'function') {
1976
+ return fs.write(fd, buffer, ...args)
1977
+ }
1978
+
1979
+ return new Promise((resolve, reject) => {
1980
+ fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => {
1981
+ if (err) return reject(err)
1982
+ resolve({ bytesWritten, buffer });
1983
+ });
1984
+ })
1985
+ };
1986
+ } (fs$j));
1987
+
1988
+ const path$g = require$$1__default$1["default"];
1989
+
1990
+ // get drive on windows
1991
+ function getRootPath (p) {
1992
+ p = path$g.normalize(path$g.resolve(p)).split(path$g.sep);
1993
+ if (p.length > 0) return p[0]
1994
+ return null
1995
+ }
1996
+
1997
+ // http://stackoverflow.com/a/62888/10333 contains more accurate
1998
+ // TODO: expand to include the rest
1999
+ const INVALID_PATH_CHARS = /[<>:"|?*]/;
2000
+
2001
+ function invalidWin32Path$2 (p) {
2002
+ const rp = getRootPath(p);
2003
+ p = p.replace(rp, '');
2004
+ return INVALID_PATH_CHARS.test(p)
2005
+ }
2006
+
2007
+ var win32 = {
2008
+ getRootPath,
2009
+ invalidWin32Path: invalidWin32Path$2
2010
+ };
2011
+
2012
+ const fs$h = gracefulFs;
2013
+ const path$f = require$$1__default$1["default"];
2014
+ const invalidWin32Path$1 = win32.invalidWin32Path;
2015
+
2016
+ const o777$1 = parseInt('0777', 8);
2017
+
2018
+ function mkdirs$2 (p, opts, callback, made) {
2019
+ if (typeof opts === 'function') {
2020
+ callback = opts;
2021
+ opts = {};
2022
+ } else if (!opts || typeof opts !== 'object') {
2023
+ opts = { mode: opts };
2024
+ }
2025
+
2026
+ if (process.platform === 'win32' && invalidWin32Path$1(p)) {
2027
+ const errInval = new Error(p + ' contains invalid WIN32 path characters.');
2028
+ errInval.code = 'EINVAL';
2029
+ return callback(errInval)
2030
+ }
2031
+
2032
+ let mode = opts.mode;
2033
+ const xfs = opts.fs || fs$h;
2034
+
2035
+ if (mode === undefined) {
2036
+ mode = o777$1 & (~process.umask());
2037
+ }
2038
+ if (!made) made = null;
2039
+
2040
+ callback = callback || function () {};
2041
+ p = path$f.resolve(p);
2042
+
2043
+ xfs.mkdir(p, mode, er => {
2044
+ if (!er) {
2045
+ made = made || p;
2046
+ return callback(null, made)
2047
+ }
2048
+ switch (er.code) {
2049
+ case 'ENOENT':
2050
+ if (path$f.dirname(p) === p) return callback(er)
2051
+ mkdirs$2(path$f.dirname(p), opts, (er, made) => {
2052
+ if (er) callback(er, made);
2053
+ else mkdirs$2(p, opts, callback, made);
2054
+ });
2055
+ break
2056
+
2057
+ // In the case of any other error, just see if there's a dir
2058
+ // there already. If so, then hooray! If not, then something
2059
+ // is borked.
2060
+ default:
2061
+ xfs.stat(p, (er2, stat) => {
2062
+ // if the stat fails, then that's super weird.
2063
+ // let the original error be the failure reason.
2064
+ if (er2 || !stat.isDirectory()) callback(er, made);
2065
+ else callback(null, made);
2066
+ });
2067
+ break
2068
+ }
2069
+ });
2070
+ }
2071
+
2072
+ var mkdirs_1$1 = mkdirs$2;
2073
+
2074
+ const fs$g = gracefulFs;
2075
+ const path$e = require$$1__default$1["default"];
2076
+ const invalidWin32Path = win32.invalidWin32Path;
2077
+
2078
+ const o777 = parseInt('0777', 8);
2079
+
2080
+ function mkdirsSync$2 (p, opts, made) {
2081
+ if (!opts || typeof opts !== 'object') {
2082
+ opts = { mode: opts };
2083
+ }
2084
+
2085
+ let mode = opts.mode;
2086
+ const xfs = opts.fs || fs$g;
2087
+
2088
+ if (process.platform === 'win32' && invalidWin32Path(p)) {
2089
+ const errInval = new Error(p + ' contains invalid WIN32 path characters.');
2090
+ errInval.code = 'EINVAL';
2091
+ throw errInval
2092
+ }
2093
+
2094
+ if (mode === undefined) {
2095
+ mode = o777 & (~process.umask());
2096
+ }
2097
+ if (!made) made = null;
2098
+
2099
+ p = path$e.resolve(p);
2100
+
2101
+ try {
2102
+ xfs.mkdirSync(p, mode);
2103
+ made = made || p;
2104
+ } catch (err0) {
2105
+ if (err0.code === 'ENOENT') {
2106
+ if (path$e.dirname(p) === p) throw err0
2107
+ made = mkdirsSync$2(path$e.dirname(p), opts, made);
2108
+ mkdirsSync$2(p, opts, made);
2109
+ } else {
2110
+ // In the case of any other error, just see if there's a dir there
2111
+ // already. If so, then hooray! If not, then something is borked.
2112
+ let stat;
2113
+ try {
2114
+ stat = xfs.statSync(p);
2115
+ } catch (err1) {
2116
+ throw err0
2117
+ }
2118
+ if (!stat.isDirectory()) throw err0
2119
+ }
2120
+ }
2121
+
2122
+ return made
2123
+ }
2124
+
2125
+ var mkdirsSync_1 = mkdirsSync$2;
2126
+
2127
+ const u$b = universalify.fromCallback;
2128
+ const mkdirs$1 = u$b(mkdirs_1$1);
2129
+ const mkdirsSync$1 = mkdirsSync_1;
2130
+
2131
+ var mkdirs_1 = {
2132
+ mkdirs: mkdirs$1,
2133
+ mkdirsSync: mkdirsSync$1,
2134
+ // alias
2135
+ mkdirp: mkdirs$1,
2136
+ mkdirpSync: mkdirsSync$1,
2137
+ ensureDir: mkdirs$1,
2138
+ ensureDirSync: mkdirsSync$1
2139
+ };
2140
+
2141
+ const fs$f = gracefulFs;
2142
+ const os = os__default["default"];
2143
+ const path$d = require$$1__default$1["default"];
2144
+
2145
+ // HFS, ext{2,3}, FAT do not, Node.js v0.10 does not
2146
+ function hasMillisResSync () {
2147
+ let tmpfile = path$d.join('millis-test-sync' + Date.now().toString() + Math.random().toString().slice(2));
2148
+ tmpfile = path$d.join(os.tmpdir(), tmpfile);
2149
+
2150
+ // 550 millis past UNIX epoch
2151
+ const d = new Date(1435410243862);
2152
+ fs$f.writeFileSync(tmpfile, 'https://github.com/jprichardson/node-fs-extra/pull/141');
2153
+ const fd = fs$f.openSync(tmpfile, 'r+');
2154
+ fs$f.futimesSync(fd, d, d);
2155
+ fs$f.closeSync(fd);
2156
+ return fs$f.statSync(tmpfile).mtime > 1435410243000
2157
+ }
2158
+
2159
+ function hasMillisRes (callback) {
2160
+ let tmpfile = path$d.join('millis-test' + Date.now().toString() + Math.random().toString().slice(2));
2161
+ tmpfile = path$d.join(os.tmpdir(), tmpfile);
2162
+
2163
+ // 550 millis past UNIX epoch
2164
+ const d = new Date(1435410243862);
2165
+ fs$f.writeFile(tmpfile, 'https://github.com/jprichardson/node-fs-extra/pull/141', err => {
2166
+ if (err) return callback(err)
2167
+ fs$f.open(tmpfile, 'r+', (err, fd) => {
2168
+ if (err) return callback(err)
2169
+ fs$f.futimes(fd, d, d, err => {
2170
+ if (err) return callback(err)
2171
+ fs$f.close(fd, err => {
2172
+ if (err) return callback(err)
2173
+ fs$f.stat(tmpfile, (err, stats) => {
2174
+ if (err) return callback(err)
2175
+ callback(null, stats.mtime > 1435410243000);
2176
+ });
2177
+ });
2178
+ });
2179
+ });
2180
+ });
2181
+ }
2182
+
2183
+ function timeRemoveMillis (timestamp) {
2184
+ if (typeof timestamp === 'number') {
2185
+ return Math.floor(timestamp / 1000) * 1000
2186
+ } else if (timestamp instanceof Date) {
2187
+ return new Date(Math.floor(timestamp.getTime() / 1000) * 1000)
2188
+ } else {
2189
+ throw new Error('fs-extra: timeRemoveMillis() unknown parameter type')
2190
+ }
2191
+ }
2192
+
2193
+ function utimesMillis (path, atime, mtime, callback) {
2194
+ // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback)
2195
+ fs$f.open(path, 'r+', (err, fd) => {
2196
+ if (err) return callback(err)
2197
+ fs$f.futimes(fd, atime, mtime, futimesErr => {
2198
+ fs$f.close(fd, closeErr => {
2199
+ if (callback) callback(futimesErr || closeErr);
2200
+ });
2201
+ });
2202
+ });
2203
+ }
2204
+
2205
+ function utimesMillisSync (path, atime, mtime) {
2206
+ const fd = fs$f.openSync(path, 'r+');
2207
+ fs$f.futimesSync(fd, atime, mtime);
2208
+ return fs$f.closeSync(fd)
2209
+ }
2210
+
2211
+ var utimes$1 = {
2212
+ hasMillisRes,
2213
+ hasMillisResSync,
2214
+ timeRemoveMillis,
2215
+ utimesMillis,
2216
+ utimesMillisSync
2217
+ };
2218
+
2219
+ /* eslint-disable node/no-deprecated-api */
2220
+ var buffer$1 = function (size) {
2221
+ if (typeof Buffer.allocUnsafe === 'function') {
2222
+ try {
2223
+ return Buffer.allocUnsafe(size)
2224
+ } catch (e) {
2225
+ return new Buffer(size)
2226
+ }
2227
+ }
2228
+ return new Buffer(size)
2229
+ };
2230
+
2231
+ const fs$e = gracefulFs;
2232
+ const path$c = require$$1__default$1["default"];
2233
+ const mkdirpSync$1 = mkdirs_1.mkdirsSync;
2234
+ const utimesSync = utimes$1.utimesMillisSync;
2235
+
2236
+ const notExist$1 = Symbol('notExist');
2237
+ const existsReg$1 = Symbol('existsReg');
2238
+
2239
+ function copySync$2 (src, dest, opts) {
2240
+ if (typeof opts === 'function') {
2241
+ opts = {filter: opts};
2242
+ }
2243
+
2244
+ opts = opts || {};
2245
+ opts.clobber = 'clobber' in opts ? !!opts.clobber : true; // default to true for now
2246
+ opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber; // overwrite falls back to clobber
2247
+
2248
+ // Warn about using preserveTimestamps on 32-bit node
2249
+ if (opts.preserveTimestamps && process.arch === 'ia32') {
2250
+ console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n
2251
+ see https://github.com/jprichardson/node-fs-extra/issues/269`);
2252
+ }
2253
+
2254
+ const resolvedDest = checkPaths$1(src, dest);
2255
+
2256
+ if (opts.filter && !opts.filter(src, dest)) return
2257
+
2258
+ const destParent = path$c.dirname(dest);
2259
+ if (!fs$e.existsSync(destParent)) mkdirpSync$1(destParent);
2260
+ return startCopy$1(resolvedDest, src, dest, opts)
2261
+ }
2262
+
2263
+ function startCopy$1 (resolvedDest, src, dest, opts) {
2264
+ if (opts.filter && !opts.filter(src, dest)) return
2265
+ return getStats$1(resolvedDest, src, dest, opts)
2266
+ }
2267
+
2268
+ function getStats$1 (resolvedDest, src, dest, opts) {
2269
+ const statSync = opts.dereference ? fs$e.statSync : fs$e.lstatSync;
2270
+ const st = statSync(src);
2271
+
2272
+ if (st.isDirectory()) return onDir$1(st, resolvedDest, src, dest, opts)
2273
+ else if (st.isFile() ||
2274
+ st.isCharacterDevice() ||
2275
+ st.isBlockDevice()) return onFile$1(st, resolvedDest, src, dest, opts)
2276
+ else if (st.isSymbolicLink()) return onLink$1(resolvedDest, src, dest, opts)
2277
+ }
2278
+
2279
+ function onFile$1 (srcStat, resolvedDest, src, dest, opts) {
2280
+ if (resolvedDest === notExist$1) return copyFile$1(srcStat, src, dest, opts)
2281
+ else if (resolvedDest === existsReg$1) return mayCopyFile$1(srcStat, src, dest, opts)
2282
+ return mayCopyFile$1(srcStat, src, dest, opts)
2283
+ }
2284
+
2285
+ function mayCopyFile$1 (srcStat, src, dest, opts) {
2286
+ if (opts.overwrite) {
2287
+ fs$e.unlinkSync(dest);
2288
+ return copyFile$1(srcStat, src, dest, opts)
2289
+ } else if (opts.errorOnExist) {
2290
+ throw new Error(`'${dest}' already exists`)
2291
+ }
2292
+ }
2293
+
2294
+ function copyFile$1 (srcStat, src, dest, opts) {
2295
+ if (typeof fs$e.copyFileSync === 'function') {
2296
+ fs$e.copyFileSync(src, dest);
2297
+ fs$e.chmodSync(dest, srcStat.mode);
2298
+ if (opts.preserveTimestamps) {
2299
+ return utimesSync(dest, srcStat.atime, srcStat.mtime)
2300
+ }
2301
+ return
2302
+ }
2303
+ return copyFileFallback$1(srcStat, src, dest, opts)
2304
+ }
2305
+
2306
+ function copyFileFallback$1 (srcStat, src, dest, opts) {
2307
+ const BUF_LENGTH = 64 * 1024;
2308
+ const _buff = buffer$1(BUF_LENGTH);
2309
+
2310
+ const fdr = fs$e.openSync(src, 'r');
2311
+ const fdw = fs$e.openSync(dest, 'w', srcStat.mode);
2312
+ let pos = 0;
2313
+
2314
+ while (pos < srcStat.size) {
2315
+ const bytesRead = fs$e.readSync(fdr, _buff, 0, BUF_LENGTH, pos);
2316
+ fs$e.writeSync(fdw, _buff, 0, bytesRead);
2317
+ pos += bytesRead;
2318
+ }
2319
+
2320
+ if (opts.preserveTimestamps) fs$e.futimesSync(fdw, srcStat.atime, srcStat.mtime);
2321
+
2322
+ fs$e.closeSync(fdr);
2323
+ fs$e.closeSync(fdw);
2324
+ }
2325
+
2326
+ function onDir$1 (srcStat, resolvedDest, src, dest, opts) {
2327
+ if (resolvedDest === notExist$1) {
2328
+ if (isSrcSubdir$3(src, dest)) {
2329
+ throw new Error(`Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`)
2330
+ }
2331
+ return mkDirAndCopy$1(srcStat, src, dest, opts)
2332
+ } else if (resolvedDest === existsReg$1) {
2333
+ if (isSrcSubdir$3(src, dest)) {
2334
+ throw new Error(`Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`)
2335
+ }
2336
+ return mayCopyDir$1(src, dest, opts)
2337
+ }
2338
+ return copyDir$1(src, dest, opts)
2339
+ }
2340
+
2341
+ function mayCopyDir$1 (src, dest, opts) {
2342
+ if (!fs$e.statSync(dest).isDirectory()) {
2343
+ throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)
2344
+ }
2345
+ return copyDir$1(src, dest, opts)
2346
+ }
2347
+
2348
+ function mkDirAndCopy$1 (srcStat, src, dest, opts) {
2349
+ fs$e.mkdirSync(dest, srcStat.mode);
2350
+ fs$e.chmodSync(dest, srcStat.mode);
2351
+ return copyDir$1(src, dest, opts)
2352
+ }
2353
+
2354
+ function copyDir$1 (src, dest, opts) {
2355
+ fs$e.readdirSync(src).forEach(item => copyDirItem$1(item, src, dest, opts));
2356
+ }
2357
+
2358
+ function copyDirItem$1 (item, src, dest, opts) {
2359
+ const srcItem = path$c.join(src, item);
2360
+ const destItem = path$c.join(dest, item);
2361
+ const resolvedDest = checkPaths$1(srcItem, destItem);
2362
+ return startCopy$1(resolvedDest, srcItem, destItem, opts)
2363
+ }
2364
+
2365
+ function onLink$1 (resolvedDest, src, dest, opts) {
2366
+ let resolvedSrc = fs$e.readlinkSync(src);
2367
+
2368
+ if (opts.dereference) {
2369
+ resolvedSrc = path$c.resolve(process.cwd(), resolvedSrc);
2370
+ }
2371
+
2372
+ if (resolvedDest === notExist$1 || resolvedDest === existsReg$1) {
2373
+ // if dest already exists, fs throws error anyway,
2374
+ // so no need to guard against it here.
2375
+ return fs$e.symlinkSync(resolvedSrc, dest)
2376
+ } else {
2377
+ if (opts.dereference) {
2378
+ resolvedDest = path$c.resolve(process.cwd(), resolvedDest);
2379
+ }
2380
+ if (pathsAreIdentical$1(resolvedSrc, resolvedDest)) return
2381
+
2382
+ // prevent copy if src is a subdir of dest since unlinking
2383
+ // dest in this case would result in removing src contents
2384
+ // and therefore a broken symlink would be created.
2385
+ if (fs$e.statSync(dest).isDirectory() && isSrcSubdir$3(resolvedDest, resolvedSrc)) {
2386
+ throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)
2387
+ }
2388
+ return copyLink$1(resolvedSrc, dest)
2389
+ }
2390
+ }
2391
+
2392
+ function copyLink$1 (resolvedSrc, dest) {
2393
+ fs$e.unlinkSync(dest);
2394
+ return fs$e.symlinkSync(resolvedSrc, dest)
2395
+ }
2396
+
2397
+ // return true if dest is a subdir of src, otherwise false.
2398
+ // extract dest base dir and check if that is the same as src basename.
2399
+ function isSrcSubdir$3 (src, dest) {
2400
+ const srcArray = path$c.resolve(src).split(path$c.sep);
2401
+ const destArray = path$c.resolve(dest).split(path$c.sep);
2402
+
2403
+ return srcArray.reduce((acc, current, i) => {
2404
+ return acc && destArray[i] === current
2405
+ }, true)
2406
+ }
2407
+
2408
+ // check if dest exists and is a symlink.
2409
+ function checkDest$1 (dest) {
2410
+ let resolvedPath;
2411
+ try {
2412
+ resolvedPath = fs$e.readlinkSync(dest);
2413
+ } catch (err) {
2414
+ if (err.code === 'ENOENT') return notExist$1
2415
+
2416
+ // dest exists and is a regular file or directory, Windows may throw UNKNOWN error.
2417
+ if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return existsReg$1
2418
+
2419
+ throw err
2420
+ }
2421
+ return resolvedPath // dest exists and is a symlink
2422
+ }
2423
+
2424
+ function pathsAreIdentical$1 (src, dest) {
2425
+ const os = process.platform;
2426
+ const resolvedSrc = path$c.resolve(src);
2427
+ const resolvedDest = path$c.resolve(dest);
2428
+ // case-insensitive paths
2429
+ if (os === 'darwin' || os === 'win32') {
2430
+ return resolvedSrc.toLowerCase() === resolvedDest.toLowerCase()
2431
+ }
2432
+ return resolvedSrc === resolvedDest
2433
+ }
2434
+
2435
+ function checkPaths$1 (src, dest) {
2436
+ const resolvedDest = checkDest$1(dest);
2437
+ if (resolvedDest === notExist$1 || resolvedDest === existsReg$1) {
2438
+ if (pathsAreIdentical$1(src, dest)) throw new Error('Source and destination must not be the same.')
2439
+ return resolvedDest
2440
+ } else {
2441
+ // check resolved dest path if dest is a symlink
2442
+ if (pathsAreIdentical$1(src, resolvedDest)) throw new Error('Source and destination must not be the same.')
2443
+ return resolvedDest
2444
+ }
2445
+ }
2446
+
2447
+ var copySync_1 = copySync$2;
2448
+
2449
+ var copySync$1 = {
2450
+ copySync: copySync_1
2451
+ };
2452
+
2453
+ const u$a = universalify.fromPromise;
2454
+ const fs$d = fs$j;
2455
+
2456
+ function pathExists$8 (path) {
2457
+ return fs$d.access(path).then(() => true).catch(() => false)
2458
+ }
2459
+
2460
+ var pathExists_1 = {
2461
+ pathExists: u$a(pathExists$8),
2462
+ pathExistsSync: fs$d.existsSync
2463
+ };
2464
+
2465
+ const fs$c = gracefulFs;
2466
+ const path$b = require$$1__default$1["default"];
2467
+ const mkdirp$1 = mkdirs_1.mkdirs;
2468
+ const pathExists$7 = pathExists_1.pathExists;
2469
+ const utimes = utimes$1.utimesMillis;
2470
+
2471
+ const notExist = Symbol('notExist');
2472
+ const existsReg = Symbol('existsReg');
2473
+
2474
+ function copy$2 (src, dest, opts, cb) {
2475
+ if (typeof opts === 'function' && !cb) {
2476
+ cb = opts;
2477
+ opts = {};
2478
+ } else if (typeof opts === 'function') {
2479
+ opts = {filter: opts};
2480
+ }
2481
+
2482
+ cb = cb || function () {};
2483
+ opts = opts || {};
2484
+
2485
+ opts.clobber = 'clobber' in opts ? !!opts.clobber : true; // default to true for now
2486
+ opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber; // overwrite falls back to clobber
2487
+
2488
+ // Warn about using preserveTimestamps on 32-bit node
2489
+ if (opts.preserveTimestamps && process.arch === 'ia32') {
2490
+ console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n
2491
+ see https://github.com/jprichardson/node-fs-extra/issues/269`);
2492
+ }
2493
+
2494
+ checkPaths(src, dest, (err, resolvedDest) => {
2495
+ if (err) return cb(err)
2496
+ if (opts.filter) return handleFilter(checkParentDir, resolvedDest, src, dest, opts, cb)
2497
+ return checkParentDir(resolvedDest, src, dest, opts, cb)
2498
+ });
2499
+ }
2500
+
2501
+ function checkParentDir (resolvedDest, src, dest, opts, cb) {
2502
+ const destParent = path$b.dirname(dest);
2503
+ pathExists$7(destParent, (err, dirExists) => {
2504
+ if (err) return cb(err)
2505
+ if (dirExists) return startCopy(resolvedDest, src, dest, opts, cb)
2506
+ mkdirp$1(destParent, err => {
2507
+ if (err) return cb(err)
2508
+ return startCopy(resolvedDest, src, dest, opts, cb)
2509
+ });
2510
+ });
2511
+ }
2512
+
2513
+ function startCopy (resolvedDest, src, dest, opts, cb) {
2514
+ if (opts.filter) return handleFilter(getStats, resolvedDest, src, dest, opts, cb)
2515
+ return getStats(resolvedDest, src, dest, opts, cb)
2516
+ }
2517
+
2518
+ function handleFilter (onInclude, resolvedDest, src, dest, opts, cb) {
2519
+ Promise.resolve(opts.filter(src, dest)).then(include => {
2520
+ if (include) {
2521
+ if (resolvedDest) return onInclude(resolvedDest, src, dest, opts, cb)
2522
+ return onInclude(src, dest, opts, cb)
2523
+ }
2524
+ return cb()
2525
+ }, error => cb(error));
2526
+ }
2527
+
2528
+ function getStats (resolvedDest, src, dest, opts, cb) {
2529
+ const stat = opts.dereference ? fs$c.stat : fs$c.lstat;
2530
+ stat(src, (err, st) => {
2531
+ if (err) return cb(err)
2532
+
2533
+ if (st.isDirectory()) return onDir(st, resolvedDest, src, dest, opts, cb)
2534
+ else if (st.isFile() ||
2535
+ st.isCharacterDevice() ||
2536
+ st.isBlockDevice()) return onFile(st, resolvedDest, src, dest, opts, cb)
2537
+ else if (st.isSymbolicLink()) return onLink(resolvedDest, src, dest, opts, cb)
2538
+ });
2539
+ }
2540
+
2541
+ function onFile (srcStat, resolvedDest, src, dest, opts, cb) {
2542
+ if (resolvedDest === notExist) return copyFile(srcStat, src, dest, opts, cb)
2543
+ else if (resolvedDest === existsReg) return mayCopyFile(srcStat, src, dest, opts, cb)
2544
+ return mayCopyFile(srcStat, src, dest, opts, cb)
2545
+ }
2546
+
2547
+ function mayCopyFile (srcStat, src, dest, opts, cb) {
2548
+ if (opts.overwrite) {
2549
+ fs$c.unlink(dest, err => {
2550
+ if (err) return cb(err)
2551
+ return copyFile(srcStat, src, dest, opts, cb)
2552
+ });
2553
+ } else if (opts.errorOnExist) {
2554
+ return cb(new Error(`'${dest}' already exists`))
2555
+ } else return cb()
2556
+ }
2557
+
2558
+ function copyFile (srcStat, src, dest, opts, cb) {
2559
+ if (typeof fs$c.copyFile === 'function') {
2560
+ return fs$c.copyFile(src, dest, err => {
2561
+ if (err) return cb(err)
2562
+ return setDestModeAndTimestamps(srcStat, dest, opts, cb)
2563
+ })
2564
+ }
2565
+ return copyFileFallback(srcStat, src, dest, opts, cb)
2566
+ }
2567
+
2568
+ function copyFileFallback (srcStat, src, dest, opts, cb) {
2569
+ const rs = fs$c.createReadStream(src);
2570
+ rs.on('error', err => cb(err)).once('open', () => {
2571
+ const ws = fs$c.createWriteStream(dest, { mode: srcStat.mode });
2572
+ ws.on('error', err => cb(err))
2573
+ .on('open', () => rs.pipe(ws))
2574
+ .once('close', () => setDestModeAndTimestamps(srcStat, dest, opts, cb));
2575
+ });
2576
+ }
2577
+
2578
+ function setDestModeAndTimestamps (srcStat, dest, opts, cb) {
2579
+ fs$c.chmod(dest, srcStat.mode, err => {
2580
+ if (err) return cb(err)
2581
+ if (opts.preserveTimestamps) {
2582
+ return utimes(dest, srcStat.atime, srcStat.mtime, cb)
2583
+ }
2584
+ return cb()
2585
+ });
2586
+ }
2587
+
2588
+ function onDir (srcStat, resolvedDest, src, dest, opts, cb) {
2589
+ if (resolvedDest === notExist) {
2590
+ if (isSrcSubdir$2(src, dest)) {
2591
+ return cb(new Error(`Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`))
2592
+ }
2593
+ return mkDirAndCopy(srcStat, src, dest, opts, cb)
2594
+ } else if (resolvedDest === existsReg) {
2595
+ if (isSrcSubdir$2(src, dest)) {
2596
+ return cb(new Error(`Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`))
2597
+ }
2598
+ return mayCopyDir(src, dest, opts, cb)
2599
+ }
2600
+ return copyDir(src, dest, opts, cb)
2601
+ }
2602
+
2603
+ function mayCopyDir (src, dest, opts, cb) {
2604
+ fs$c.stat(dest, (err, st) => {
2605
+ if (err) return cb(err)
2606
+ if (!st.isDirectory()) {
2607
+ return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`))
2608
+ }
2609
+ return copyDir(src, dest, opts, cb)
2610
+ });
2611
+ }
2612
+
2613
+ function mkDirAndCopy (srcStat, src, dest, opts, cb) {
2614
+ fs$c.mkdir(dest, srcStat.mode, err => {
2615
+ if (err) return cb(err)
2616
+ fs$c.chmod(dest, srcStat.mode, err => {
2617
+ if (err) return cb(err)
2618
+ return copyDir(src, dest, opts, cb)
2619
+ });
2620
+ });
2621
+ }
2622
+
2623
+ function copyDir (src, dest, opts, cb) {
2624
+ fs$c.readdir(src, (err, items) => {
2625
+ if (err) return cb(err)
2626
+ return copyDirItems(items, src, dest, opts, cb)
2627
+ });
2628
+ }
2629
+
2630
+ function copyDirItems (items, src, dest, opts, cb) {
2631
+ const item = items.pop();
2632
+ if (!item) return cb()
2633
+ return copyDirItem(items, item, src, dest, opts, cb)
2634
+ }
2635
+
2636
+ function copyDirItem (items, item, src, dest, opts, cb) {
2637
+ const srcItem = path$b.join(src, item);
2638
+ const destItem = path$b.join(dest, item);
2639
+ checkPaths(srcItem, destItem, (err, resolvedDest) => {
2640
+ if (err) return cb(err)
2641
+ startCopy(resolvedDest, srcItem, destItem, opts, err => {
2642
+ if (err) return cb(err)
2643
+ return copyDirItems(items, src, dest, opts, cb)
2644
+ });
2645
+ });
2646
+ }
2647
+
2648
+ function onLink (resolvedDest, src, dest, opts, cb) {
2649
+ fs$c.readlink(src, (err, resolvedSrc) => {
2650
+ if (err) return cb(err)
2651
+
2652
+ if (opts.dereference) {
2653
+ resolvedSrc = path$b.resolve(process.cwd(), resolvedSrc);
2654
+ }
2655
+
2656
+ if (resolvedDest === notExist || resolvedDest === existsReg) {
2657
+ // if dest already exists, fs throws error anyway,
2658
+ // so no need to guard against it here.
2659
+ return fs$c.symlink(resolvedSrc, dest, cb)
2660
+ } else {
2661
+ if (opts.dereference) {
2662
+ resolvedDest = path$b.resolve(process.cwd(), resolvedDest);
2663
+ }
2664
+ if (pathsAreIdentical(resolvedSrc, resolvedDest)) return cb()
2665
+
2666
+ // prevent copy if src is a subdir of dest since unlinking
2667
+ // dest in this case would result in removing src contents
2668
+ // and therefore a broken symlink would be created.
2669
+ fs$c.stat(dest, (err, st) => {
2670
+ if (err) return cb(err)
2671
+ if (st.isDirectory() && isSrcSubdir$2(resolvedDest, resolvedSrc)) {
2672
+ return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`))
2673
+ }
2674
+ return copyLink(resolvedSrc, dest, cb)
2675
+ });
2676
+ }
2677
+ });
2678
+ }
2679
+
2680
+ function copyLink (resolvedSrc, dest, cb) {
2681
+ fs$c.unlink(dest, err => {
2682
+ if (err) return cb(err)
2683
+ return fs$c.symlink(resolvedSrc, dest, cb)
2684
+ });
2685
+ }
2686
+
2687
+ // return true if dest is a subdir of src, otherwise false.
2688
+ // extract dest base dir and check if that is the same as src basename.
2689
+ function isSrcSubdir$2 (src, dest) {
2690
+ const srcArray = path$b.resolve(src).split(path$b.sep);
2691
+ const destArray = path$b.resolve(dest).split(path$b.sep);
2692
+
2693
+ return srcArray.reduce((acc, current, i) => {
2694
+ return acc && destArray[i] === current
2695
+ }, true)
2696
+ }
2697
+
2698
+ // check if dest exists and is a symlink.
2699
+ function checkDest (dest, cb) {
2700
+ fs$c.readlink(dest, (err, resolvedPath) => {
2701
+ if (err) {
2702
+ if (err.code === 'ENOENT') return cb(null, notExist)
2703
+
2704
+ // dest exists and is a regular file or directory, Windows may throw UNKNOWN error.
2705
+ if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return cb(null, existsReg)
2706
+
2707
+ return cb(err)
2708
+ }
2709
+ return cb(null, resolvedPath) // dest exists and is a symlink
2710
+ });
2711
+ }
2712
+
2713
+ function pathsAreIdentical (src, dest) {
2714
+ const os = process.platform;
2715
+ const resolvedSrc = path$b.resolve(src);
2716
+ const resolvedDest = path$b.resolve(dest);
2717
+ // case-insensitive paths
2718
+ if (os === 'darwin' || os === 'win32') {
2719
+ return resolvedSrc.toLowerCase() === resolvedDest.toLowerCase()
2720
+ }
2721
+ return resolvedSrc === resolvedDest
2722
+ }
2723
+
2724
+ function checkPaths (src, dest, cb) {
2725
+ checkDest(dest, (err, resolvedDest) => {
2726
+ if (err) return cb(err)
2727
+ if (resolvedDest === notExist || resolvedDest === existsReg) {
2728
+ if (pathsAreIdentical(src, dest)) return cb(new Error('Source and destination must not be the same.'))
2729
+ return cb(null, resolvedDest)
2730
+ } else {
2731
+ // check resolved dest path if dest is a symlink
2732
+ if (pathsAreIdentical(src, resolvedDest)) return cb(new Error('Source and destination must not be the same.'))
2733
+ return cb(null, resolvedDest)
2734
+ }
2735
+ });
2736
+ }
2737
+
2738
+ var copy_1 = copy$2;
2739
+
2740
+ const u$9 = universalify.fromCallback;
2741
+ var copy$1 = {
2742
+ copy: u$9(copy_1)
2743
+ };
2744
+
2745
+ const fs$b = gracefulFs;
2746
+ const path$a = require$$1__default$1["default"];
2747
+ const assert = assert__default["default"];
2748
+
2749
+ const isWindows = (process.platform === 'win32');
2750
+
2751
+ function defaults (options) {
2752
+ const methods = [
2753
+ 'unlink',
2754
+ 'chmod',
2755
+ 'stat',
2756
+ 'lstat',
2757
+ 'rmdir',
2758
+ 'readdir'
2759
+ ];
2760
+ methods.forEach(m => {
2761
+ options[m] = options[m] || fs$b[m];
2762
+ m = m + 'Sync';
2763
+ options[m] = options[m] || fs$b[m];
2764
+ });
2765
+
2766
+ options.maxBusyTries = options.maxBusyTries || 3;
2767
+ }
2768
+
2769
+ function rimraf$1 (p, options, cb) {
2770
+ let busyTries = 0;
2771
+
2772
+ if (typeof options === 'function') {
2773
+ cb = options;
2774
+ options = {};
2775
+ }
2776
+
2777
+ assert(p, 'rimraf: missing path');
2778
+ assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string');
2779
+ assert.strictEqual(typeof cb, 'function', 'rimraf: callback function required');
2780
+ assert(options, 'rimraf: invalid options argument provided');
2781
+ assert.strictEqual(typeof options, 'object', 'rimraf: options should be object');
2782
+
2783
+ defaults(options);
2784
+
2785
+ rimraf_(p, options, function CB (er) {
2786
+ if (er) {
2787
+ if ((er.code === 'EBUSY' || er.code === 'ENOTEMPTY' || er.code === 'EPERM') &&
2788
+ busyTries < options.maxBusyTries) {
2789
+ busyTries++;
2790
+ const time = busyTries * 100;
2791
+ // try again, with the same exact callback as this one.
2792
+ return setTimeout(() => rimraf_(p, options, CB), time)
2793
+ }
2794
+
2795
+ // already gone
2796
+ if (er.code === 'ENOENT') er = null;
2797
+ }
2798
+
2799
+ cb(er);
2800
+ });
2801
+ }
2802
+
2803
+ // Two possible strategies.
2804
+ // 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR
2805
+ // 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR
2806
+ //
2807
+ // Both result in an extra syscall when you guess wrong. However, there
2808
+ // are likely far more normal files in the world than directories. This
2809
+ // is based on the assumption that a the average number of files per
2810
+ // directory is >= 1.
2811
+ //
2812
+ // If anyone ever complains about this, then I guess the strategy could
2813
+ // be made configurable somehow. But until then, YAGNI.
2814
+ function rimraf_ (p, options, cb) {
2815
+ assert(p);
2816
+ assert(options);
2817
+ assert(typeof cb === 'function');
2818
+
2819
+ // sunos lets the root user unlink directories, which is... weird.
2820
+ // so we have to lstat here and make sure it's not a dir.
2821
+ options.lstat(p, (er, st) => {
2822
+ if (er && er.code === 'ENOENT') {
2823
+ return cb(null)
2824
+ }
2825
+
2826
+ // Windows can EPERM on stat. Life is suffering.
2827
+ if (er && er.code === 'EPERM' && isWindows) {
2828
+ return fixWinEPERM(p, options, er, cb)
2829
+ }
2830
+
2831
+ if (st && st.isDirectory()) {
2832
+ return rmdir(p, options, er, cb)
2833
+ }
2834
+
2835
+ options.unlink(p, er => {
2836
+ if (er) {
2837
+ if (er.code === 'ENOENT') {
2838
+ return cb(null)
2839
+ }
2840
+ if (er.code === 'EPERM') {
2841
+ return (isWindows)
2842
+ ? fixWinEPERM(p, options, er, cb)
2843
+ : rmdir(p, options, er, cb)
2844
+ }
2845
+ if (er.code === 'EISDIR') {
2846
+ return rmdir(p, options, er, cb)
2847
+ }
2848
+ }
2849
+ return cb(er)
2850
+ });
2851
+ });
2852
+ }
2853
+
2854
+ function fixWinEPERM (p, options, er, cb) {
2855
+ assert(p);
2856
+ assert(options);
2857
+ assert(typeof cb === 'function');
2858
+ if (er) {
2859
+ assert(er instanceof Error);
2860
+ }
2861
+
2862
+ options.chmod(p, 0o666, er2 => {
2863
+ if (er2) {
2864
+ cb(er2.code === 'ENOENT' ? null : er);
2865
+ } else {
2866
+ options.stat(p, (er3, stats) => {
2867
+ if (er3) {
2868
+ cb(er3.code === 'ENOENT' ? null : er);
2869
+ } else if (stats.isDirectory()) {
2870
+ rmdir(p, options, er, cb);
2871
+ } else {
2872
+ options.unlink(p, cb);
2873
+ }
2874
+ });
2875
+ }
2876
+ });
2877
+ }
2878
+
2879
+ function fixWinEPERMSync (p, options, er) {
2880
+ let stats;
2881
+
2882
+ assert(p);
2883
+ assert(options);
2884
+ if (er) {
2885
+ assert(er instanceof Error);
2886
+ }
2887
+
2888
+ try {
2889
+ options.chmodSync(p, 0o666);
2890
+ } catch (er2) {
2891
+ if (er2.code === 'ENOENT') {
2892
+ return
2893
+ } else {
2894
+ throw er
2895
+ }
2896
+ }
2897
+
2898
+ try {
2899
+ stats = options.statSync(p);
2900
+ } catch (er3) {
2901
+ if (er3.code === 'ENOENT') {
2902
+ return
2903
+ } else {
2904
+ throw er
2905
+ }
2906
+ }
2907
+
2908
+ if (stats.isDirectory()) {
2909
+ rmdirSync(p, options, er);
2910
+ } else {
2911
+ options.unlinkSync(p);
2912
+ }
2913
+ }
2914
+
2915
+ function rmdir (p, options, originalEr, cb) {
2916
+ assert(p);
2917
+ assert(options);
2918
+ if (originalEr) {
2919
+ assert(originalEr instanceof Error);
2920
+ }
2921
+ assert(typeof cb === 'function');
2922
+
2923
+ // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
2924
+ // if we guessed wrong, and it's not a directory, then
2925
+ // raise the original error.
2926
+ options.rmdir(p, er => {
2927
+ if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) {
2928
+ rmkids(p, options, cb);
2929
+ } else if (er && er.code === 'ENOTDIR') {
2930
+ cb(originalEr);
2931
+ } else {
2932
+ cb(er);
2933
+ }
2934
+ });
2935
+ }
2936
+
2937
+ function rmkids (p, options, cb) {
2938
+ assert(p);
2939
+ assert(options);
2940
+ assert(typeof cb === 'function');
2941
+
2942
+ options.readdir(p, (er, files) => {
2943
+ if (er) return cb(er)
2944
+
2945
+ let n = files.length;
2946
+ let errState;
2947
+
2948
+ if (n === 0) return options.rmdir(p, cb)
2949
+
2950
+ files.forEach(f => {
2951
+ rimraf$1(path$a.join(p, f), options, er => {
2952
+ if (errState) {
2953
+ return
2954
+ }
2955
+ if (er) return cb(errState = er)
2956
+ if (--n === 0) {
2957
+ options.rmdir(p, cb);
2958
+ }
2959
+ });
2960
+ });
2961
+ });
2962
+ }
2963
+
2964
+ // this looks simpler, and is strictly *faster*, but will
2965
+ // tie up the JavaScript thread and fail on excessively
2966
+ // deep directory trees.
2967
+ function rimrafSync (p, options) {
2968
+ let st;
2969
+
2970
+ options = options || {};
2971
+ defaults(options);
2972
+
2973
+ assert(p, 'rimraf: missing path');
2974
+ assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string');
2975
+ assert(options, 'rimraf: missing options');
2976
+ assert.strictEqual(typeof options, 'object', 'rimraf: options should be object');
2977
+
2978
+ try {
2979
+ st = options.lstatSync(p);
2980
+ } catch (er) {
2981
+ if (er.code === 'ENOENT') {
2982
+ return
2983
+ }
2984
+
2985
+ // Windows can EPERM on stat. Life is suffering.
2986
+ if (er.code === 'EPERM' && isWindows) {
2987
+ fixWinEPERMSync(p, options, er);
2988
+ }
2989
+ }
2990
+
2991
+ try {
2992
+ // sunos lets the root user unlink directories, which is... weird.
2993
+ if (st && st.isDirectory()) {
2994
+ rmdirSync(p, options, null);
2995
+ } else {
2996
+ options.unlinkSync(p);
2997
+ }
2998
+ } catch (er) {
2999
+ if (er.code === 'ENOENT') {
3000
+ return
3001
+ } else if (er.code === 'EPERM') {
3002
+ return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er)
3003
+ } else if (er.code !== 'EISDIR') {
3004
+ throw er
3005
+ }
3006
+ rmdirSync(p, options, er);
3007
+ }
3008
+ }
3009
+
3010
+ function rmdirSync (p, options, originalEr) {
3011
+ assert(p);
3012
+ assert(options);
3013
+ if (originalEr) {
3014
+ assert(originalEr instanceof Error);
3015
+ }
3016
+
3017
+ try {
3018
+ options.rmdirSync(p);
3019
+ } catch (er) {
3020
+ if (er.code === 'ENOTDIR') {
3021
+ throw originalEr
3022
+ } else if (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM') {
3023
+ rmkidsSync(p, options);
3024
+ } else if (er.code !== 'ENOENT') {
3025
+ throw er
3026
+ }
3027
+ }
3028
+ }
3029
+
3030
+ function rmkidsSync (p, options) {
3031
+ assert(p);
3032
+ assert(options);
3033
+ options.readdirSync(p).forEach(f => rimrafSync(path$a.join(p, f), options));
3034
+
3035
+ // We only end up here once we got ENOTEMPTY at least once, and
3036
+ // at this point, we are guaranteed to have removed all the kids.
3037
+ // So, we know that it won't be ENOENT or ENOTDIR or anything else.
3038
+ // try really hard to delete stuff on windows, because it has a
3039
+ // PROFOUNDLY annoying habit of not closing handles promptly when
3040
+ // files are deleted, resulting in spurious ENOTEMPTY errors.
3041
+ const retries = isWindows ? 100 : 1;
3042
+ let i = 0;
3043
+ do {
3044
+ let threw = true;
3045
+ try {
3046
+ const ret = options.rmdirSync(p, options);
3047
+ threw = false;
3048
+ return ret
3049
+ } finally {
3050
+ if (++i < retries && threw) continue // eslint-disable-line
3051
+ }
3052
+ } while (true)
3053
+ }
3054
+
3055
+ var rimraf_1 = rimraf$1;
3056
+ rimraf$1.sync = rimrafSync;
3057
+
3058
+ const u$8 = universalify.fromCallback;
3059
+ const rimraf = rimraf_1;
3060
+
3061
+ var remove$2 = {
3062
+ remove: u$8(rimraf),
3063
+ removeSync: rimraf.sync
3064
+ };
3065
+
3066
+ const u$7 = universalify.fromCallback;
3067
+ const fs$a = require$$0__default["default"];
3068
+ const path$9 = require$$1__default$1["default"];
3069
+ const mkdir$5 = mkdirs_1;
3070
+ const remove$1 = remove$2;
3071
+
3072
+ const emptyDir = u$7(function emptyDir (dir, callback) {
3073
+ callback = callback || function () {};
3074
+ fs$a.readdir(dir, (err, items) => {
3075
+ if (err) return mkdir$5.mkdirs(dir, callback)
3076
+
3077
+ items = items.map(item => path$9.join(dir, item));
3078
+
3079
+ deleteItem();
3080
+
3081
+ function deleteItem () {
3082
+ const item = items.pop();
3083
+ if (!item) return callback()
3084
+ remove$1.remove(item, err => {
3085
+ if (err) return callback(err)
3086
+ deleteItem();
3087
+ });
3088
+ }
3089
+ });
3090
+ });
3091
+
3092
+ function emptyDirSync (dir) {
3093
+ let items;
3094
+ try {
3095
+ items = fs$a.readdirSync(dir);
3096
+ } catch (err) {
3097
+ return mkdir$5.mkdirsSync(dir)
3098
+ }
3099
+
3100
+ items.forEach(item => {
3101
+ item = path$9.join(dir, item);
3102
+ remove$1.removeSync(item);
3103
+ });
3104
+ }
3105
+
3106
+ var empty = {
3107
+ emptyDirSync,
3108
+ emptydirSync: emptyDirSync,
3109
+ emptyDir,
3110
+ emptydir: emptyDir
3111
+ };
3112
+
3113
+ const u$6 = universalify.fromCallback;
3114
+ const path$8 = require$$1__default$1["default"];
3115
+ const fs$9 = gracefulFs;
3116
+ const mkdir$4 = mkdirs_1;
3117
+ const pathExists$6 = pathExists_1.pathExists;
3118
+
3119
+ function createFile (file, callback) {
3120
+ function makeFile () {
3121
+ fs$9.writeFile(file, '', err => {
3122
+ if (err) return callback(err)
3123
+ callback();
3124
+ });
3125
+ }
3126
+
3127
+ fs$9.stat(file, (err, stats) => { // eslint-disable-line handle-callback-err
3128
+ if (!err && stats.isFile()) return callback()
3129
+ const dir = path$8.dirname(file);
3130
+ pathExists$6(dir, (err, dirExists) => {
3131
+ if (err) return callback(err)
3132
+ if (dirExists) return makeFile()
3133
+ mkdir$4.mkdirs(dir, err => {
3134
+ if (err) return callback(err)
3135
+ makeFile();
3136
+ });
3137
+ });
3138
+ });
3139
+ }
3140
+
3141
+ function createFileSync (file) {
3142
+ let stats;
3143
+ try {
3144
+ stats = fs$9.statSync(file);
3145
+ } catch (e) {}
3146
+ if (stats && stats.isFile()) return
3147
+
3148
+ const dir = path$8.dirname(file);
3149
+ if (!fs$9.existsSync(dir)) {
3150
+ mkdir$4.mkdirsSync(dir);
3151
+ }
3152
+
3153
+ fs$9.writeFileSync(file, '');
3154
+ }
3155
+
3156
+ var file$1 = {
3157
+ createFile: u$6(createFile),
3158
+ createFileSync
3159
+ };
3160
+
3161
+ const u$5 = universalify.fromCallback;
3162
+ const path$7 = require$$1__default$1["default"];
3163
+ const fs$8 = gracefulFs;
3164
+ const mkdir$3 = mkdirs_1;
3165
+ const pathExists$5 = pathExists_1.pathExists;
3166
+
3167
+ function createLink (srcpath, dstpath, callback) {
3168
+ function makeLink (srcpath, dstpath) {
3169
+ fs$8.link(srcpath, dstpath, err => {
3170
+ if (err) return callback(err)
3171
+ callback(null);
3172
+ });
3173
+ }
3174
+
3175
+ pathExists$5(dstpath, (err, destinationExists) => {
3176
+ if (err) return callback(err)
3177
+ if (destinationExists) return callback(null)
3178
+ fs$8.lstat(srcpath, (err) => {
3179
+ if (err) {
3180
+ err.message = err.message.replace('lstat', 'ensureLink');
3181
+ return callback(err)
3182
+ }
3183
+
3184
+ const dir = path$7.dirname(dstpath);
3185
+ pathExists$5(dir, (err, dirExists) => {
3186
+ if (err) return callback(err)
3187
+ if (dirExists) return makeLink(srcpath, dstpath)
3188
+ mkdir$3.mkdirs(dir, err => {
3189
+ if (err) return callback(err)
3190
+ makeLink(srcpath, dstpath);
3191
+ });
3192
+ });
3193
+ });
3194
+ });
3195
+ }
3196
+
3197
+ function createLinkSync (srcpath, dstpath) {
3198
+ const destinationExists = fs$8.existsSync(dstpath);
3199
+ if (destinationExists) return undefined
3200
+
3201
+ try {
3202
+ fs$8.lstatSync(srcpath);
3203
+ } catch (err) {
3204
+ err.message = err.message.replace('lstat', 'ensureLink');
3205
+ throw err
3206
+ }
3207
+
3208
+ const dir = path$7.dirname(dstpath);
3209
+ const dirExists = fs$8.existsSync(dir);
3210
+ if (dirExists) return fs$8.linkSync(srcpath, dstpath)
3211
+ mkdir$3.mkdirsSync(dir);
3212
+
3213
+ return fs$8.linkSync(srcpath, dstpath)
3214
+ }
3215
+
3216
+ var link$1 = {
3217
+ createLink: u$5(createLink),
3218
+ createLinkSync
3219
+ };
3220
+
3221
+ const path$6 = require$$1__default$1["default"];
3222
+ const fs$7 = gracefulFs;
3223
+ const pathExists$4 = pathExists_1.pathExists;
3224
+
3225
+ /**
3226
+ * Function that returns two types of paths, one relative to symlink, and one
3227
+ * relative to the current working directory. Checks if path is absolute or
3228
+ * relative. If the path is relative, this function checks if the path is
3229
+ * relative to symlink or relative to current working directory. This is an
3230
+ * initiative to find a smarter `srcpath` to supply when building symlinks.
3231
+ * This allows you to determine which path to use out of one of three possible
3232
+ * types of source paths. The first is an absolute path. This is detected by
3233
+ * `path.isAbsolute()`. When an absolute path is provided, it is checked to
3234
+ * see if it exists. If it does it's used, if not an error is returned
3235
+ * (callback)/ thrown (sync). The other two options for `srcpath` are a
3236
+ * relative url. By default Node's `fs.symlink` works by creating a symlink
3237
+ * using `dstpath` and expects the `srcpath` to be relative to the newly
3238
+ * created symlink. If you provide a `srcpath` that does not exist on the file
3239
+ * system it results in a broken symlink. To minimize this, the function
3240
+ * checks to see if the 'relative to symlink' source file exists, and if it
3241
+ * does it will use it. If it does not, it checks if there's a file that
3242
+ * exists that is relative to the current working directory, if does its used.
3243
+ * This preserves the expectations of the original fs.symlink spec and adds
3244
+ * the ability to pass in `relative to current working direcotry` paths.
3245
+ */
3246
+
3247
+ function symlinkPaths$1 (srcpath, dstpath, callback) {
3248
+ if (path$6.isAbsolute(srcpath)) {
3249
+ return fs$7.lstat(srcpath, (err) => {
3250
+ if (err) {
3251
+ err.message = err.message.replace('lstat', 'ensureSymlink');
3252
+ return callback(err)
3253
+ }
3254
+ return callback(null, {
3255
+ 'toCwd': srcpath,
3256
+ 'toDst': srcpath
3257
+ })
3258
+ })
3259
+ } else {
3260
+ const dstdir = path$6.dirname(dstpath);
3261
+ const relativeToDst = path$6.join(dstdir, srcpath);
3262
+ return pathExists$4(relativeToDst, (err, exists) => {
3263
+ if (err) return callback(err)
3264
+ if (exists) {
3265
+ return callback(null, {
3266
+ 'toCwd': relativeToDst,
3267
+ 'toDst': srcpath
3268
+ })
3269
+ } else {
3270
+ return fs$7.lstat(srcpath, (err) => {
3271
+ if (err) {
3272
+ err.message = err.message.replace('lstat', 'ensureSymlink');
3273
+ return callback(err)
3274
+ }
3275
+ return callback(null, {
3276
+ 'toCwd': srcpath,
3277
+ 'toDst': path$6.relative(dstdir, srcpath)
3278
+ })
3279
+ })
3280
+ }
3281
+ })
3282
+ }
3283
+ }
3284
+
3285
+ function symlinkPathsSync$1 (srcpath, dstpath) {
3286
+ let exists;
3287
+ if (path$6.isAbsolute(srcpath)) {
3288
+ exists = fs$7.existsSync(srcpath);
3289
+ if (!exists) throw new Error('absolute srcpath does not exist')
3290
+ return {
3291
+ 'toCwd': srcpath,
3292
+ 'toDst': srcpath
3293
+ }
3294
+ } else {
3295
+ const dstdir = path$6.dirname(dstpath);
3296
+ const relativeToDst = path$6.join(dstdir, srcpath);
3297
+ exists = fs$7.existsSync(relativeToDst);
3298
+ if (exists) {
3299
+ return {
3300
+ 'toCwd': relativeToDst,
3301
+ 'toDst': srcpath
3302
+ }
3303
+ } else {
3304
+ exists = fs$7.existsSync(srcpath);
3305
+ if (!exists) throw new Error('relative srcpath does not exist')
3306
+ return {
3307
+ 'toCwd': srcpath,
3308
+ 'toDst': path$6.relative(dstdir, srcpath)
3309
+ }
3310
+ }
3311
+ }
3312
+ }
3313
+
3314
+ var symlinkPaths_1 = {
3315
+ symlinkPaths: symlinkPaths$1,
3316
+ symlinkPathsSync: symlinkPathsSync$1
3317
+ };
3318
+
3319
+ const fs$6 = gracefulFs;
3320
+
3321
+ function symlinkType$1 (srcpath, type, callback) {
3322
+ callback = (typeof type === 'function') ? type : callback;
3323
+ type = (typeof type === 'function') ? false : type;
3324
+ if (type) return callback(null, type)
3325
+ fs$6.lstat(srcpath, (err, stats) => {
3326
+ if (err) return callback(null, 'file')
3327
+ type = (stats && stats.isDirectory()) ? 'dir' : 'file';
3328
+ callback(null, type);
3329
+ });
3330
+ }
3331
+
3332
+ function symlinkTypeSync$1 (srcpath, type) {
3333
+ let stats;
3334
+
3335
+ if (type) return type
3336
+ try {
3337
+ stats = fs$6.lstatSync(srcpath);
3338
+ } catch (e) {
3339
+ return 'file'
3340
+ }
3341
+ return (stats && stats.isDirectory()) ? 'dir' : 'file'
3342
+ }
3343
+
3344
+ var symlinkType_1 = {
3345
+ symlinkType: symlinkType$1,
3346
+ symlinkTypeSync: symlinkTypeSync$1
3347
+ };
3348
+
3349
+ const u$4 = universalify.fromCallback;
3350
+ const path$5 = require$$1__default$1["default"];
3351
+ const fs$5 = gracefulFs;
3352
+ const _mkdirs = mkdirs_1;
3353
+ const mkdirs = _mkdirs.mkdirs;
3354
+ const mkdirsSync = _mkdirs.mkdirsSync;
3355
+
3356
+ const _symlinkPaths = symlinkPaths_1;
3357
+ const symlinkPaths = _symlinkPaths.symlinkPaths;
3358
+ const symlinkPathsSync = _symlinkPaths.symlinkPathsSync;
3359
+
3360
+ const _symlinkType = symlinkType_1;
3361
+ const symlinkType = _symlinkType.symlinkType;
3362
+ const symlinkTypeSync = _symlinkType.symlinkTypeSync;
3363
+
3364
+ const pathExists$3 = pathExists_1.pathExists;
3365
+
3366
+ function createSymlink (srcpath, dstpath, type, callback) {
3367
+ callback = (typeof type === 'function') ? type : callback;
3368
+ type = (typeof type === 'function') ? false : type;
3369
+
3370
+ pathExists$3(dstpath, (err, destinationExists) => {
3371
+ if (err) return callback(err)
3372
+ if (destinationExists) return callback(null)
3373
+ symlinkPaths(srcpath, dstpath, (err, relative) => {
3374
+ if (err) return callback(err)
3375
+ srcpath = relative.toDst;
3376
+ symlinkType(relative.toCwd, type, (err, type) => {
3377
+ if (err) return callback(err)
3378
+ const dir = path$5.dirname(dstpath);
3379
+ pathExists$3(dir, (err, dirExists) => {
3380
+ if (err) return callback(err)
3381
+ if (dirExists) return fs$5.symlink(srcpath, dstpath, type, callback)
3382
+ mkdirs(dir, err => {
3383
+ if (err) return callback(err)
3384
+ fs$5.symlink(srcpath, dstpath, type, callback);
3385
+ });
3386
+ });
3387
+ });
3388
+ });
3389
+ });
3390
+ }
3391
+
3392
+ function createSymlinkSync (srcpath, dstpath, type) {
3393
+ const destinationExists = fs$5.existsSync(dstpath);
3394
+ if (destinationExists) return undefined
3395
+
3396
+ const relative = symlinkPathsSync(srcpath, dstpath);
3397
+ srcpath = relative.toDst;
3398
+ type = symlinkTypeSync(relative.toCwd, type);
3399
+ const dir = path$5.dirname(dstpath);
3400
+ const exists = fs$5.existsSync(dir);
3401
+ if (exists) return fs$5.symlinkSync(srcpath, dstpath, type)
3402
+ mkdirsSync(dir);
3403
+ return fs$5.symlinkSync(srcpath, dstpath, type)
3404
+ }
3405
+
3406
+ var symlink$1 = {
3407
+ createSymlink: u$4(createSymlink),
3408
+ createSymlinkSync
3409
+ };
3410
+
3411
+ const file = file$1;
3412
+ const link = link$1;
3413
+ const symlink = symlink$1;
3414
+
3415
+ var ensure = {
3416
+ // file
3417
+ createFile: file.createFile,
3418
+ createFileSync: file.createFileSync,
3419
+ ensureFile: file.createFile,
3420
+ ensureFileSync: file.createFileSync,
3421
+ // link
3422
+ createLink: link.createLink,
3423
+ createLinkSync: link.createLinkSync,
3424
+ ensureLink: link.createLink,
3425
+ ensureLinkSync: link.createLinkSync,
3426
+ // symlink
3427
+ createSymlink: symlink.createSymlink,
3428
+ createSymlinkSync: symlink.createSymlinkSync,
3429
+ ensureSymlink: symlink.createSymlink,
3430
+ ensureSymlinkSync: symlink.createSymlinkSync
3431
+ };
3432
+
3433
+ var _fs;
3434
+ try {
3435
+ _fs = gracefulFs;
3436
+ } catch (_) {
3437
+ _fs = require$$0__default["default"];
3438
+ }
3439
+
3440
+ function readFile (file, options, callback) {
3441
+ if (callback == null) {
3442
+ callback = options;
3443
+ options = {};
3444
+ }
3445
+
3446
+ if (typeof options === 'string') {
3447
+ options = {encoding: options};
3448
+ }
3449
+
3450
+ options = options || {};
3451
+ var fs = options.fs || _fs;
3452
+
3453
+ var shouldThrow = true;
3454
+ if ('throws' in options) {
3455
+ shouldThrow = options.throws;
3456
+ }
3457
+
3458
+ fs.readFile(file, options, function (err, data) {
3459
+ if (err) return callback(err)
3460
+
3461
+ data = stripBom(data);
3462
+
3463
+ var obj;
3464
+ try {
3465
+ obj = JSON.parse(data, options ? options.reviver : null);
3466
+ } catch (err2) {
3467
+ if (shouldThrow) {
3468
+ err2.message = file + ': ' + err2.message;
3469
+ return callback(err2)
3470
+ } else {
3471
+ return callback(null, null)
3472
+ }
3473
+ }
3474
+
3475
+ callback(null, obj);
3476
+ });
3477
+ }
3478
+
3479
+ function readFileSync (file, options) {
3480
+ options = options || {};
3481
+ if (typeof options === 'string') {
3482
+ options = {encoding: options};
3483
+ }
3484
+
3485
+ var fs = options.fs || _fs;
3486
+
3487
+ var shouldThrow = true;
3488
+ if ('throws' in options) {
3489
+ shouldThrow = options.throws;
3490
+ }
3491
+
3492
+ try {
3493
+ var content = fs.readFileSync(file, options);
3494
+ content = stripBom(content);
3495
+ return JSON.parse(content, options.reviver)
3496
+ } catch (err) {
3497
+ if (shouldThrow) {
3498
+ err.message = file + ': ' + err.message;
3499
+ throw err
3500
+ } else {
3501
+ return null
3502
+ }
3503
+ }
3504
+ }
3505
+
3506
+ function stringify (obj, options) {
3507
+ var spaces;
3508
+ var EOL = '\n';
3509
+ if (typeof options === 'object' && options !== null) {
3510
+ if (options.spaces) {
3511
+ spaces = options.spaces;
3512
+ }
3513
+ if (options.EOL) {
3514
+ EOL = options.EOL;
3515
+ }
3516
+ }
3517
+
3518
+ var str = JSON.stringify(obj, options ? options.replacer : null, spaces);
3519
+
3520
+ return str.replace(/\n/g, EOL) + EOL
3521
+ }
3522
+
3523
+ function writeFile (file, obj, options, callback) {
3524
+ if (callback == null) {
3525
+ callback = options;
3526
+ options = {};
3527
+ }
3528
+ options = options || {};
3529
+ var fs = options.fs || _fs;
3530
+
3531
+ var str = '';
3532
+ try {
3533
+ str = stringify(obj, options);
3534
+ } catch (err) {
3535
+ // Need to return whether a callback was passed or not
3536
+ if (callback) callback(err, null);
3537
+ return
3538
+ }
3539
+
3540
+ fs.writeFile(file, str, options, callback);
3541
+ }
3542
+
3543
+ function writeFileSync (file, obj, options) {
3544
+ options = options || {};
3545
+ var fs = options.fs || _fs;
3546
+
3547
+ var str = stringify(obj, options);
3548
+ // not sure if fs.writeFileSync returns anything, but just in case
3549
+ return fs.writeFileSync(file, str, options)
3550
+ }
3551
+
3552
+ function stripBom (content) {
3553
+ // we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified
3554
+ if (Buffer.isBuffer(content)) content = content.toString('utf8');
3555
+ content = content.replace(/^\uFEFF/, '');
3556
+ return content
3557
+ }
3558
+
3559
+ var jsonfile$1 = {
3560
+ readFile: readFile,
3561
+ readFileSync: readFileSync,
3562
+ writeFile: writeFile,
3563
+ writeFileSync: writeFileSync
3564
+ };
3565
+
3566
+ var jsonfile_1 = jsonfile$1;
3567
+
3568
+ const u$3 = universalify.fromCallback;
3569
+ const jsonFile$3 = jsonfile_1;
3570
+
3571
+ var jsonfile = {
3572
+ // jsonfile exports
3573
+ readJson: u$3(jsonFile$3.readFile),
3574
+ readJsonSync: jsonFile$3.readFileSync,
3575
+ writeJson: u$3(jsonFile$3.writeFile),
3576
+ writeJsonSync: jsonFile$3.writeFileSync
3577
+ };
3578
+
3579
+ const path$4 = require$$1__default$1["default"];
3580
+ const mkdir$2 = mkdirs_1;
3581
+ const pathExists$2 = pathExists_1.pathExists;
3582
+ const jsonFile$2 = jsonfile;
3583
+
3584
+ function outputJson (file, data, options, callback) {
3585
+ if (typeof options === 'function') {
3586
+ callback = options;
3587
+ options = {};
3588
+ }
3589
+
3590
+ const dir = path$4.dirname(file);
3591
+
3592
+ pathExists$2(dir, (err, itDoes) => {
3593
+ if (err) return callback(err)
3594
+ if (itDoes) return jsonFile$2.writeJson(file, data, options, callback)
3595
+
3596
+ mkdir$2.mkdirs(dir, err => {
3597
+ if (err) return callback(err)
3598
+ jsonFile$2.writeJson(file, data, options, callback);
3599
+ });
3600
+ });
3601
+ }
3602
+
3603
+ var outputJson_1 = outputJson;
3604
+
3605
+ const fs$4 = gracefulFs;
3606
+ const path$3 = require$$1__default$1["default"];
3607
+ const mkdir$1 = mkdirs_1;
3608
+ const jsonFile$1 = jsonfile;
3609
+
3610
+ function outputJsonSync (file, data, options) {
3611
+ const dir = path$3.dirname(file);
3612
+
3613
+ if (!fs$4.existsSync(dir)) {
3614
+ mkdir$1.mkdirsSync(dir);
3615
+ }
3616
+
3617
+ jsonFile$1.writeJsonSync(file, data, options);
3618
+ }
3619
+
3620
+ var outputJsonSync_1 = outputJsonSync;
3621
+
3622
+ const u$2 = universalify.fromCallback;
3623
+ const jsonFile = jsonfile;
3624
+
3625
+ jsonFile.outputJson = u$2(outputJson_1);
3626
+ jsonFile.outputJsonSync = outputJsonSync_1;
3627
+ // aliases
3628
+ jsonFile.outputJSON = jsonFile.outputJson;
3629
+ jsonFile.outputJSONSync = jsonFile.outputJsonSync;
3630
+ jsonFile.writeJSON = jsonFile.writeJson;
3631
+ jsonFile.writeJSONSync = jsonFile.writeJsonSync;
3632
+ jsonFile.readJSON = jsonFile.readJson;
3633
+ jsonFile.readJSONSync = jsonFile.readJsonSync;
3634
+
3635
+ var json = jsonFile;
3636
+
3637
+ const fs$3 = gracefulFs;
3638
+ const path$2 = require$$1__default$1["default"];
3639
+ const copySync = copySync$1.copySync;
3640
+ const removeSync = remove$2.removeSync;
3641
+ const mkdirpSync = mkdirs_1.mkdirsSync;
3642
+ const buffer = buffer$1;
3643
+
3644
+ function moveSync (src, dest, options) {
3645
+ options = options || {};
3646
+ const overwrite = options.overwrite || options.clobber || false;
3647
+
3648
+ src = path$2.resolve(src);
3649
+ dest = path$2.resolve(dest);
3650
+
3651
+ if (src === dest) return fs$3.accessSync(src)
3652
+
3653
+ if (isSrcSubdir$1(src, dest)) throw new Error(`Cannot move '${src}' into itself '${dest}'.`)
3654
+
3655
+ mkdirpSync(path$2.dirname(dest));
3656
+ tryRenameSync();
3657
+
3658
+ function tryRenameSync () {
3659
+ if (overwrite) {
3660
+ try {
3661
+ return fs$3.renameSync(src, dest)
3662
+ } catch (err) {
3663
+ if (err.code === 'ENOTEMPTY' || err.code === 'EEXIST' || err.code === 'EPERM') {
3664
+ removeSync(dest);
3665
+ options.overwrite = false; // just overwriteed it, no need to do it again
3666
+ return moveSync(src, dest, options)
3667
+ }
3668
+
3669
+ if (err.code !== 'EXDEV') throw err
3670
+ return moveSyncAcrossDevice(src, dest, overwrite)
3671
+ }
3672
+ } else {
3673
+ try {
3674
+ fs$3.linkSync(src, dest);
3675
+ return fs$3.unlinkSync(src)
3676
+ } catch (err) {
3677
+ if (err.code === 'EXDEV' || err.code === 'EISDIR' || err.code === 'EPERM' || err.code === 'ENOTSUP') {
3678
+ return moveSyncAcrossDevice(src, dest, overwrite)
3679
+ }
3680
+ throw err
3681
+ }
3682
+ }
3683
+ }
3684
+ }
3685
+
3686
+ function moveSyncAcrossDevice (src, dest, overwrite) {
3687
+ const stat = fs$3.statSync(src);
3688
+
3689
+ if (stat.isDirectory()) {
3690
+ return moveDirSyncAcrossDevice(src, dest, overwrite)
3691
+ } else {
3692
+ return moveFileSyncAcrossDevice(src, dest, overwrite)
3693
+ }
3694
+ }
3695
+
3696
+ function moveFileSyncAcrossDevice (src, dest, overwrite) {
3697
+ const BUF_LENGTH = 64 * 1024;
3698
+ const _buff = buffer(BUF_LENGTH);
3699
+
3700
+ const flags = overwrite ? 'w' : 'wx';
3701
+
3702
+ const fdr = fs$3.openSync(src, 'r');
3703
+ const stat = fs$3.fstatSync(fdr);
3704
+ const fdw = fs$3.openSync(dest, flags, stat.mode);
3705
+ let pos = 0;
3706
+
3707
+ while (pos < stat.size) {
3708
+ const bytesRead = fs$3.readSync(fdr, _buff, 0, BUF_LENGTH, pos);
3709
+ fs$3.writeSync(fdw, _buff, 0, bytesRead);
3710
+ pos += bytesRead;
3711
+ }
3712
+
3713
+ fs$3.closeSync(fdr);
3714
+ fs$3.closeSync(fdw);
3715
+ return fs$3.unlinkSync(src)
3716
+ }
3717
+
3718
+ function moveDirSyncAcrossDevice (src, dest, overwrite) {
3719
+ const options = {
3720
+ overwrite: false
3721
+ };
3722
+
3723
+ if (overwrite) {
3724
+ removeSync(dest);
3725
+ tryCopySync();
3726
+ } else {
3727
+ tryCopySync();
3728
+ }
3729
+
3730
+ function tryCopySync () {
3731
+ copySync(src, dest, options);
3732
+ return removeSync(src)
3733
+ }
3734
+ }
3735
+
3736
+ // return true if dest is a subdir of src, otherwise false.
3737
+ // extract dest base dir and check if that is the same as src basename
3738
+ function isSrcSubdir$1 (src, dest) {
3739
+ try {
3740
+ return fs$3.statSync(src).isDirectory() &&
3741
+ src !== dest &&
3742
+ dest.indexOf(src) > -1 &&
3743
+ dest.split(path$2.dirname(src) + path$2.sep)[1].split(path$2.sep)[0] === path$2.basename(src)
3744
+ } catch (e) {
3745
+ return false
3746
+ }
3747
+ }
3748
+
3749
+ var moveSync_1 = {
3750
+ moveSync
3751
+ };
3752
+
3753
+ const u$1 = universalify.fromCallback;
3754
+ const fs$2 = gracefulFs;
3755
+ const path$1 = require$$1__default$1["default"];
3756
+ const copy = copy$1.copy;
3757
+ const remove = remove$2.remove;
3758
+ const mkdirp = mkdirs_1.mkdirp;
3759
+ const pathExists$1 = pathExists_1.pathExists;
3760
+
3761
+ function move (src, dest, opts, cb) {
3762
+ if (typeof opts === 'function') {
3763
+ cb = opts;
3764
+ opts = {};
3765
+ }
3766
+
3767
+ const overwrite = opts.overwrite || opts.clobber || false;
3768
+
3769
+ src = path$1.resolve(src);
3770
+ dest = path$1.resolve(dest);
3771
+
3772
+ if (src === dest) return fs$2.access(src, cb)
3773
+
3774
+ fs$2.stat(src, (err, st) => {
3775
+ if (err) return cb(err)
3776
+
3777
+ if (st.isDirectory() && isSrcSubdir(src, dest)) {
3778
+ return cb(new Error(`Cannot move '${src}' to a subdirectory of itself, '${dest}'.`))
3779
+ }
3780
+ mkdirp(path$1.dirname(dest), err => {
3781
+ if (err) return cb(err)
3782
+ return doRename(src, dest, overwrite, cb)
3783
+ });
3784
+ });
3785
+ }
3786
+
3787
+ function doRename (src, dest, overwrite, cb) {
3788
+ if (overwrite) {
3789
+ return remove(dest, err => {
3790
+ if (err) return cb(err)
3791
+ return rename(src, dest, overwrite, cb)
3792
+ })
3793
+ }
3794
+ pathExists$1(dest, (err, destExists) => {
3795
+ if (err) return cb(err)
3796
+ if (destExists) return cb(new Error('dest already exists.'))
3797
+ return rename(src, dest, overwrite, cb)
3798
+ });
3799
+ }
3800
+
3801
+ function rename (src, dest, overwrite, cb) {
3802
+ fs$2.rename(src, dest, err => {
3803
+ if (!err) return cb()
3804
+ if (err.code !== 'EXDEV') return cb(err)
3805
+ return moveAcrossDevice(src, dest, overwrite, cb)
3806
+ });
3807
+ }
3808
+
3809
+ function moveAcrossDevice (src, dest, overwrite, cb) {
3810
+ const opts = {
3811
+ overwrite,
3812
+ errorOnExist: true
3813
+ };
3814
+
3815
+ copy(src, dest, opts, err => {
3816
+ if (err) return cb(err)
3817
+ return remove(src, cb)
3818
+ });
3819
+ }
3820
+
3821
+ function isSrcSubdir (src, dest) {
3822
+ const srcArray = src.split(path$1.sep);
3823
+ const destArray = dest.split(path$1.sep);
3824
+
3825
+ return srcArray.reduce((acc, current, i) => {
3826
+ return acc && destArray[i] === current
3827
+ }, true)
3828
+ }
3829
+
3830
+ var move_1 = {
3831
+ move: u$1(move)
3832
+ };
3833
+
3834
+ const u = universalify.fromCallback;
3835
+ const fs$1 = gracefulFs;
3836
+ const path = require$$1__default$1["default"];
3837
+ const mkdir = mkdirs_1;
3838
+ const pathExists = pathExists_1.pathExists;
3839
+
3840
+ function outputFile (file, data, encoding, callback) {
3841
+ if (typeof encoding === 'function') {
3842
+ callback = encoding;
3843
+ encoding = 'utf8';
3844
+ }
3845
+
3846
+ const dir = path.dirname(file);
3847
+ pathExists(dir, (err, itDoes) => {
3848
+ if (err) return callback(err)
3849
+ if (itDoes) return fs$1.writeFile(file, data, encoding, callback)
3850
+
3851
+ mkdir.mkdirs(dir, err => {
3852
+ if (err) return callback(err)
3853
+
3854
+ fs$1.writeFile(file, data, encoding, callback);
3855
+ });
3856
+ });
3857
+ }
3858
+
3859
+ function outputFileSync (file, ...args) {
3860
+ const dir = path.dirname(file);
3861
+ if (fs$1.existsSync(dir)) {
3862
+ return fs$1.writeFileSync(file, ...args)
3863
+ }
3864
+ mkdir.mkdirsSync(dir);
3865
+ fs$1.writeFileSync(file, ...args);
3866
+ }
3867
+
3868
+ var output = {
3869
+ outputFile: u(outputFile),
3870
+ outputFileSync
3871
+ };
3872
+
3873
+ (function (module) {
3874
+
3875
+ module.exports = Object.assign(
3876
+ {},
3877
+ // Export promiseified graceful-fs:
3878
+ fs$j,
3879
+ // Export extra methods:
3880
+ copySync$1,
3881
+ copy$1,
3882
+ empty,
3883
+ ensure,
3884
+ json,
3885
+ mkdirs_1,
3886
+ moveSync_1,
3887
+ move_1,
3888
+ output,
3889
+ pathExists_1,
3890
+ remove$2
3891
+ );
3892
+
3893
+ // Export fs.promises as a getter property so that we don't trigger
3894
+ // ExperimentalWarning before fs.promises is actually accessed.
3895
+ const fs = require$$0__default["default"];
3896
+ if (Object.getOwnPropertyDescriptor(fs, 'promises')) {
3897
+ Object.defineProperty(module.exports, 'promises', {
3898
+ get () { return fs.promises }
3899
+ });
3900
+ }
3901
+ } (lib));
3902
+
3903
+ var fs = libExports;
3904
+
3905
+ class Server extends EventEmitter__default["default"] {
3906
+ constructor(option, common) {
3907
+ super();
3908
+ this.debug = option("debug");
3909
+ this.file = option("socket", require$$1__default$1["default"].join(common.cacheDir(), "socket"));
3910
+ this.server = undefined;
3911
+ this.option = option;
3912
+ this._connections = {};
3913
+ this._connectionId = 0;
3914
+ }
3915
+ close() {
3916
+ if (this.debug) {
3917
+ console.log("Server::close");
3918
+ }
3919
+ if (this.server) {
3920
+ this.server.close();
3921
+ }
3922
+ try {
3923
+ fs.unlinkSync(this.file);
3924
+ }
3925
+ catch (err) {
3926
+ /* */
3927
+ }
3928
+ }
3929
+ listen() {
3930
+ try {
3931
+ fs.unlinkSync(this.file); // this should be more
3932
+ // complicated with attempts to
3933
+ // cleanly shut down and whatnot
3934
+ }
3935
+ catch (err) {
3936
+ /* */
3937
+ }
3938
+ return new Promise((resolve) => {
3939
+ let connected = false;
3940
+ this.server = net__default["default"].createServer(this._onConnection.bind(this)).listen(this.file, () => {
3941
+ fs.chmodSync(this.file, "777");
3942
+ connected = true;
3943
+ resolve();
3944
+ });
3945
+ this.server.on("error", (err) => {
3946
+ if (!connected) {
3947
+ console.error("Got server error", err);
3948
+ setTimeout(this.listen.bind(this), 1000);
3949
+ }
3950
+ });
3951
+ this.server.on("close", () => {
3952
+ if (!connected) {
3953
+ setTimeout(this.listen.bind(this), 1000);
3954
+ }
3955
+ });
3956
+ });
3957
+ }
3958
+ _onConnection(conn) {
3959
+ const compile = new Compile(conn, ++this._connectionId, this.option);
3960
+ if (this.debug) {
3961
+ console.log("Server::_onConnection", compile.id);
3962
+ }
3963
+ if (this._connectionId === Math.pow(2, 31) - 1) {
3964
+ this._connectionId = 0;
3965
+ }
3966
+ this._connections[compile.id] = conn;
3967
+ compile.on("end", () => {
3968
+ if (this.debug) {
3969
+ console.log("Compile::end");
3970
+ }
3971
+ delete this._connections[compile.id];
3972
+ });
3973
+ this.emit("compile", compile);
3974
+ }
3975
+ }
3976
+
3977
+ class Slots extends EventEmitter__default["default"] {
3978
+ constructor(count, name, debug) {
3979
+ super();
3980
+ this.count = count;
3981
+ this.name = name;
3982
+ this.used = new Map();
3983
+ this.debug = debug;
3984
+ this.pending = new Map();
3985
+ if (this.debug) {
3986
+ console.log("Slots created", this.toString());
3987
+ }
3988
+ }
3989
+ acquire(id, data, cb) {
3990
+ if (this.used.size < this.count) {
3991
+ this.used.set(id, data);
3992
+ if (this.debug) {
3993
+ console.log("acquired slot", id, data, this.toString());
3994
+ }
3995
+ cb();
3996
+ }
3997
+ else {
3998
+ if (this.debug) {
3999
+ console.log("pending slot", id, this.toString());
4000
+ }
4001
+ this.pending.set(id, { data: data, cb: cb });
4002
+ }
4003
+ }
4004
+ release(id) {
4005
+ this.pending.delete(id);
4006
+ if (this.used.has(id)) {
4007
+ const data = this.used.get(id);
4008
+ this.used.delete(id);
4009
+ assert__default["default"](this.used.size < this.count);
4010
+ assert__default["default"](this.used.size + 1 === this.count || this.pending.size === 0);
4011
+ if (this.debug) {
4012
+ console.log("released", id, data, this.toString());
4013
+ }
4014
+ // eslint-disable-next-line no-unreachable-loop
4015
+ for (const p of this.pending) {
4016
+ this.used.set(p[0], p[1].data);
4017
+ this.pending.delete(p[0]);
4018
+ p[1].cb();
4019
+ break;
4020
+ }
4021
+ }
4022
+ }
4023
+ toString() {
4024
+ return `${this.name} ${this.used.size}/${this.count}`;
4025
+ }
4026
+ dump() {
4027
+ const pending = {};
4028
+ const used = {};
4029
+ for (const p of this.pending) {
4030
+ pending[p[0]] = p[1].data;
4031
+ }
4032
+ for (const p of this.used) {
4033
+ used[p[0]] = p[1];
4034
+ }
4035
+ return { used: used, pending: pending, capacity: this.count, usedSize: this.used.size };
4036
+ }
4037
+ }
4038
+
4039
+ const Version = 5;
4040
+ function cacheDir(option) {
4041
+ let dir = option("cache-dir");
4042
+ if (!dir) {
4043
+ dir = require$$1__default$1["default"].join(os__default["default"].homedir(), ".cache", "fisk", require$$1__default$1["default"].basename(option.prefix || ""));
4044
+ }
4045
+ return dir;
4046
+ }
4047
+ function validateCache(option) {
4048
+ const dir = cacheDir(option);
4049
+ const file = require$$1__default$1["default"].join(dir, "version");
4050
+ // console.log(dir);
4051
+ let version;
4052
+ try {
4053
+ version = fs.readFileSync(file);
4054
+ if (version.readUInt32BE() === Version) {
4055
+ return;
4056
+ }
4057
+ }
4058
+ catch (err) {
4059
+ /* */
4060
+ }
4061
+ if (version) {
4062
+ console.log(`Wrong version. Destroying cache ${dir}`);
4063
+ }
4064
+ fs.removeSync(dir);
4065
+ fs.mkdirpSync(dir);
4066
+ const buf = Buffer.allocUnsafe(4);
4067
+ buf.writeUInt32BE(Version);
4068
+ fs.writeFileSync(file, buf);
4069
+ }
4070
+ function common$1(option) {
4071
+ validateCache(option);
4072
+ return {
4073
+ cacheDir: cacheDir.bind(undefined, option),
4074
+ Version
4075
+ };
4076
+ }
4077
+
4078
+ const option = options({
4079
+ prefix: "fisk/daemon",
4080
+ noApplicationPath: true,
4081
+ additionalFiles: ["fisk/daemon.conf.override"]
4082
+ });
4083
+ const common = common$1(option);
4084
+ const debug = option("debug");
4085
+ process.on("unhandledRejection", (reason, p) => {
4086
+ console.log("Unhandled Rejection at: Promise", p, "reason:", reason === null || reason === void 0 ? void 0 : reason.stack);
4087
+ process.exit();
4088
+ // if (client)
4089
+ // client.send('log', { message: `Unhandled Rejection at: Promise ${p}, reason: ${reason.stack}` });
4090
+ });
4091
+ process.on("uncaughtException", (err) => {
4092
+ console.error("Uncaught exception", err);
4093
+ process.exit();
4094
+ // if (client)
4095
+ // client.send('log', { message: `Uncaught exception ${err.toString()} ${err.stack}` });
4096
+ });
4097
+ const server = new Server(option, common);
4098
+ server.listen().then(() => {
4099
+ console.log("listening on", server.file);
4100
+ });
4101
+ // server.on("message
4102
+ server.on("error", (err) => {
4103
+ console.error("server error", err);
4104
+ });
4105
+ const cppSlots = new Slots(option.int("cpp-slots", Math.max(os__default["default"].cpus().length * 2, 1)), "cpp", debug);
4106
+ const compileSlots = new Slots(option.int("slots", Math.max(os__default["default"].cpus().length, 1)), "compile", debug);
4107
+ server.on("compile", (compile) => {
4108
+ compile.on("dumpSlots", () => {
4109
+ const ret = { cpp: cppSlots.dump(), compile: compileSlots.dump() };
4110
+ if (debug) {
4111
+ console.log("sending dump", ret);
4112
+ }
4113
+ compile.send(ret);
4114
+ });
4115
+ let requestedCppSlot = false;
4116
+ compile.on("acquireCppSlot", () => {
4117
+ if (debug) {
4118
+ console.log("acquireCppSlot");
4119
+ }
4120
+ assert__default["default"](!requestedCppSlot);
4121
+ requestedCppSlot = true;
4122
+ cppSlots.acquire(compile.id, { pid: compile.pid }, () => {
4123
+ // compile.send({ type: 'cppSlotAcquired' });
4124
+ compile.send(Constants.CppSlotAcquired);
4125
+ });
4126
+ });
4127
+ compile.on("releaseCppSlot", () => {
4128
+ if (debug) {
4129
+ console.log("releaseCppSlot");
4130
+ }
4131
+ assert__default["default"](requestedCppSlot);
4132
+ if (requestedCppSlot) {
4133
+ requestedCppSlot = false;
4134
+ cppSlots.release(compile.id);
4135
+ }
4136
+ });
4137
+ let requestedCompileSlot = false;
4138
+ compile.on("acquireCompileSlot", () => {
4139
+ if (debug) {
4140
+ console.log("acquireCompileSlot");
4141
+ }
4142
+ assert__default["default"](!requestedCompileSlot);
4143
+ requestedCompileSlot = true;
4144
+ compileSlots.acquire(compile.id, { pid: compile.pid }, () => {
4145
+ // compile.send({ type: 'compileSlotAcquired' });
4146
+ compile.send(Constants.CompileSlotAcquired);
4147
+ });
4148
+ });
4149
+ compile.on("releaseCompileSlot", () => {
4150
+ if (debug) {
4151
+ console.log("releaseCompileSlot");
4152
+ }
4153
+ assert__default["default"](requestedCompileSlot);
4154
+ if (requestedCompileSlot) {
4155
+ requestedCompileSlot = false;
4156
+ compileSlots.release(compile.id);
4157
+ }
4158
+ });
4159
+ compile.on("error", (err) => {
4160
+ if (debug) {
4161
+ console.error("Got error from fiskc", compile.id, compile.pid, err);
4162
+ }
4163
+ if (requestedCppSlot) {
4164
+ requestedCppSlot = false;
4165
+ cppSlots.release(compile.id);
4166
+ }
4167
+ if (requestedCompileSlot) {
4168
+ requestedCompileSlot = false;
4169
+ compileSlots.release(compile.id);
4170
+ }
4171
+ });
4172
+ compile.on("end", () => {
4173
+ if (debug) {
4174
+ console.log("got end from", compile.id, compile.pid);
4175
+ }
4176
+ if (requestedCppSlot) {
4177
+ requestedCppSlot = false;
4178
+ cppSlots.release(compile.id);
4179
+ }
4180
+ if (requestedCompileSlot) {
4181
+ requestedCompileSlot = false;
4182
+ compileSlots.release(compile.id);
4183
+ }
4184
+ });
4185
+ });
4186
+ process.on("exit", () => {
4187
+ server.close();
4188
+ });
4189
+ process.on("SIGINT", () => {
4190
+ server.close();
4191
+ process.exit();
4192
+ });
4193
+ /*
4194
+ const client = new Client(option, common.Version);
4195
+
4196
+ let connectInterval;
4197
+ client.on('quit', message => {
4198
+ process.exit(message.code);
4199
+ });
4200
+
4201
+ client.on('connect', () => {
4202
+ console.log('connected');
4203
+ if (connectInterval) {
4204
+ clearInterval(connectInterval);
4205
+ connectInterval = undefined;
4206
+ }
4207
+ });
4208
+
4209
+ client.on('error', err => {
4210
+ console.error('client error', err);
4211
+ });
4212
+
4213
+ client.on('close', () => {
4214
+ console.log('client closed');
4215
+ if (!connectInterval) {
4216
+ connectInterval = setInterval(() => {
4217
+ console.log('Reconnecting...');
4218
+ client.connect();
4219
+ }, 1000);
4220
+ }
4221
+ });
4222
+ */
4223
+ //# sourceMappingURL=fisk-daemon.js.map