@bigbinary/neeto-playwright-commons 4.8.6 → 4.8.7

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.
package/index.js CHANGED
@@ -8,7 +8,7 @@ import path__default, { dirname } from 'path';
8
8
  import { test, expect, chromium, defineConfig, devices } from '@playwright/test';
9
9
  import { getI18nInstance, initI18n } from 'playwright-i18next-fixture';
10
10
  import { curry, isNotNil, not, isEmpty, pluck, isNil, mergeAll, mergeDeepLeft } from 'ramda';
11
- import { execSync, spawn } from 'child_process';
11
+ import { execSync, spawn, spawnSync } from 'child_process';
12
12
  import require$$2$2, { fileURLToPath } from 'url';
13
13
  import dayjs from 'dayjs';
14
14
  import require$$1$3 from 'events';
@@ -33,6 +33,7 @@ import timezone from 'dayjs/plugin/timezone.js';
33
33
  import utc from 'dayjs/plugin/utc.js';
34
34
  import https from 'https';
35
35
  import * as http from 'http';
36
+ import require$$0$c from 'constants';
36
37
 
37
38
  const BASE_URL = "/api/v1";
38
39
  const NEETO_AUTH_BASE_URL = (subdomain = "app") => `https://${subdomain}.neetoauth.net`;
@@ -126175,12 +126176,2134 @@ async function warmup({ urls = DEFAULT_WARMUP_URLS, timeout = 60_000, } = {}) {
126175
126176
  }
126176
126177
  }
126177
126178
 
126179
+ var properLockfile = {exports: {}};
126180
+
126181
+ var lockfile = {};
126182
+
126183
+ var polyfills;
126184
+ var hasRequiredPolyfills;
126185
+
126186
+ function requirePolyfills () {
126187
+ if (hasRequiredPolyfills) return polyfills;
126188
+ hasRequiredPolyfills = 1;
126189
+ var constants = require$$0$c;
126190
+
126191
+ var origCwd = process.cwd;
126192
+ var cwd = null;
126193
+
126194
+ var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;
126195
+
126196
+ process.cwd = function() {
126197
+ if (!cwd)
126198
+ cwd = origCwd.call(process);
126199
+ return cwd
126200
+ };
126201
+ try {
126202
+ process.cwd();
126203
+ } catch (er) {}
126204
+
126205
+ // This check is needed until node.js 12 is required
126206
+ if (typeof process.chdir === 'function') {
126207
+ var chdir = process.chdir;
126208
+ process.chdir = function (d) {
126209
+ cwd = null;
126210
+ chdir.call(process, d);
126211
+ };
126212
+ if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir);
126213
+ }
126214
+
126215
+ polyfills = patch;
126216
+
126217
+ function patch (fs) {
126218
+ // (re-)implement some things that are known busted or missing.
126219
+
126220
+ // lchmod, broken prior to 0.6.2
126221
+ // back-port the fix here.
126222
+ if (constants.hasOwnProperty('O_SYMLINK') &&
126223
+ process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
126224
+ patchLchmod(fs);
126225
+ }
126226
+
126227
+ // lutimes implementation, or no-op
126228
+ if (!fs.lutimes) {
126229
+ patchLutimes(fs);
126230
+ }
126231
+
126232
+ // https://github.com/isaacs/node-graceful-fs/issues/4
126233
+ // Chown should not fail on einval or eperm if non-root.
126234
+ // It should not fail on enosys ever, as this just indicates
126235
+ // that a fs doesn't support the intended operation.
126236
+
126237
+ fs.chown = chownFix(fs.chown);
126238
+ fs.fchown = chownFix(fs.fchown);
126239
+ fs.lchown = chownFix(fs.lchown);
126240
+
126241
+ fs.chmod = chmodFix(fs.chmod);
126242
+ fs.fchmod = chmodFix(fs.fchmod);
126243
+ fs.lchmod = chmodFix(fs.lchmod);
126244
+
126245
+ fs.chownSync = chownFixSync(fs.chownSync);
126246
+ fs.fchownSync = chownFixSync(fs.fchownSync);
126247
+ fs.lchownSync = chownFixSync(fs.lchownSync);
126248
+
126249
+ fs.chmodSync = chmodFixSync(fs.chmodSync);
126250
+ fs.fchmodSync = chmodFixSync(fs.fchmodSync);
126251
+ fs.lchmodSync = chmodFixSync(fs.lchmodSync);
126252
+
126253
+ fs.stat = statFix(fs.stat);
126254
+ fs.fstat = statFix(fs.fstat);
126255
+ fs.lstat = statFix(fs.lstat);
126256
+
126257
+ fs.statSync = statFixSync(fs.statSync);
126258
+ fs.fstatSync = statFixSync(fs.fstatSync);
126259
+ fs.lstatSync = statFixSync(fs.lstatSync);
126260
+
126261
+ // if lchmod/lchown do not exist, then make them no-ops
126262
+ if (fs.chmod && !fs.lchmod) {
126263
+ fs.lchmod = function (path, mode, cb) {
126264
+ if (cb) process.nextTick(cb);
126265
+ };
126266
+ fs.lchmodSync = function () {};
126267
+ }
126268
+ if (fs.chown && !fs.lchown) {
126269
+ fs.lchown = function (path, uid, gid, cb) {
126270
+ if (cb) process.nextTick(cb);
126271
+ };
126272
+ fs.lchownSync = function () {};
126273
+ }
126274
+
126275
+ // on Windows, A/V software can lock the directory, causing this
126276
+ // to fail with an EACCES or EPERM if the directory contains newly
126277
+ // created files. Try again on failure, for up to 60 seconds.
126278
+
126279
+ // Set the timeout this long because some Windows Anti-Virus, such as Parity
126280
+ // bit9, may lock files for up to a minute, causing npm package install
126281
+ // failures. Also, take care to yield the scheduler. Windows scheduling gives
126282
+ // CPU to a busy looping process, which can cause the program causing the lock
126283
+ // contention to be starved of CPU by node, so the contention doesn't resolve.
126284
+ if (platform === "win32") {
126285
+ fs.rename = typeof fs.rename !== 'function' ? fs.rename
126286
+ : (function (fs$rename) {
126287
+ function rename (from, to, cb) {
126288
+ var start = Date.now();
126289
+ var backoff = 0;
126290
+ fs$rename(from, to, function CB (er) {
126291
+ if (er
126292
+ && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY")
126293
+ && Date.now() - start < 60000) {
126294
+ setTimeout(function() {
126295
+ fs.stat(to, function (stater, st) {
126296
+ if (stater && stater.code === "ENOENT")
126297
+ fs$rename(from, to, CB);
126298
+ else
126299
+ cb(er);
126300
+ });
126301
+ }, backoff);
126302
+ if (backoff < 100)
126303
+ backoff += 10;
126304
+ return;
126305
+ }
126306
+ if (cb) cb(er);
126307
+ });
126308
+ }
126309
+ if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename);
126310
+ return rename
126311
+ })(fs.rename);
126312
+ }
126313
+
126314
+ // if read() returns EAGAIN, then just try it again.
126315
+ fs.read = typeof fs.read !== 'function' ? fs.read
126316
+ : (function (fs$read) {
126317
+ function read (fd, buffer, offset, length, position, callback_) {
126318
+ var callback;
126319
+ if (callback_ && typeof callback_ === 'function') {
126320
+ var eagCounter = 0;
126321
+ callback = function (er, _, __) {
126322
+ if (er && er.code === 'EAGAIN' && eagCounter < 10) {
126323
+ eagCounter ++;
126324
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback)
126325
+ }
126326
+ callback_.apply(this, arguments);
126327
+ };
126328
+ }
126329
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback)
126330
+ }
126331
+
126332
+ // This ensures `util.promisify` works as it does for native `fs.read`.
126333
+ if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read);
126334
+ return read
126335
+ })(fs.read);
126336
+
126337
+ fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync
126338
+ : (function (fs$readSync) { return function (fd, buffer, offset, length, position) {
126339
+ var eagCounter = 0;
126340
+ while (true) {
126341
+ try {
126342
+ return fs$readSync.call(fs, fd, buffer, offset, length, position)
126343
+ } catch (er) {
126344
+ if (er.code === 'EAGAIN' && eagCounter < 10) {
126345
+ eagCounter ++;
126346
+ continue
126347
+ }
126348
+ throw er
126349
+ }
126350
+ }
126351
+ }})(fs.readSync);
126352
+
126353
+ function patchLchmod (fs) {
126354
+ fs.lchmod = function (path, mode, callback) {
126355
+ fs.open( path
126356
+ , constants.O_WRONLY | constants.O_SYMLINK
126357
+ , mode
126358
+ , function (err, fd) {
126359
+ if (err) {
126360
+ if (callback) callback(err);
126361
+ return
126362
+ }
126363
+ // prefer to return the chmod error, if one occurs,
126364
+ // but still try to close, and report closing errors if they occur.
126365
+ fs.fchmod(fd, mode, function (err) {
126366
+ fs.close(fd, function(err2) {
126367
+ if (callback) callback(err || err2);
126368
+ });
126369
+ });
126370
+ });
126371
+ };
126372
+
126373
+ fs.lchmodSync = function (path, mode) {
126374
+ var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode);
126375
+
126376
+ // prefer to return the chmod error, if one occurs,
126377
+ // but still try to close, and report closing errors if they occur.
126378
+ var threw = true;
126379
+ var ret;
126380
+ try {
126381
+ ret = fs.fchmodSync(fd, mode);
126382
+ threw = false;
126383
+ } finally {
126384
+ if (threw) {
126385
+ try {
126386
+ fs.closeSync(fd);
126387
+ } catch (er) {}
126388
+ } else {
126389
+ fs.closeSync(fd);
126390
+ }
126391
+ }
126392
+ return ret
126393
+ };
126394
+ }
126395
+
126396
+ function patchLutimes (fs) {
126397
+ if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) {
126398
+ fs.lutimes = function (path, at, mt, cb) {
126399
+ fs.open(path, constants.O_SYMLINK, function (er, fd) {
126400
+ if (er) {
126401
+ if (cb) cb(er);
126402
+ return
126403
+ }
126404
+ fs.futimes(fd, at, mt, function (er) {
126405
+ fs.close(fd, function (er2) {
126406
+ if (cb) cb(er || er2);
126407
+ });
126408
+ });
126409
+ });
126410
+ };
126411
+
126412
+ fs.lutimesSync = function (path, at, mt) {
126413
+ var fd = fs.openSync(path, constants.O_SYMLINK);
126414
+ var ret;
126415
+ var threw = true;
126416
+ try {
126417
+ ret = fs.futimesSync(fd, at, mt);
126418
+ threw = false;
126419
+ } finally {
126420
+ if (threw) {
126421
+ try {
126422
+ fs.closeSync(fd);
126423
+ } catch (er) {}
126424
+ } else {
126425
+ fs.closeSync(fd);
126426
+ }
126427
+ }
126428
+ return ret
126429
+ };
126430
+
126431
+ } else if (fs.futimes) {
126432
+ fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb); };
126433
+ fs.lutimesSync = function () {};
126434
+ }
126435
+ }
126436
+
126437
+ function chmodFix (orig) {
126438
+ if (!orig) return orig
126439
+ return function (target, mode, cb) {
126440
+ return orig.call(fs, target, mode, function (er) {
126441
+ if (chownErOk(er)) er = null;
126442
+ if (cb) cb.apply(this, arguments);
126443
+ })
126444
+ }
126445
+ }
126446
+
126447
+ function chmodFixSync (orig) {
126448
+ if (!orig) return orig
126449
+ return function (target, mode) {
126450
+ try {
126451
+ return orig.call(fs, target, mode)
126452
+ } catch (er) {
126453
+ if (!chownErOk(er)) throw er
126454
+ }
126455
+ }
126456
+ }
126457
+
126458
+
126459
+ function chownFix (orig) {
126460
+ if (!orig) return orig
126461
+ return function (target, uid, gid, cb) {
126462
+ return orig.call(fs, target, uid, gid, function (er) {
126463
+ if (chownErOk(er)) er = null;
126464
+ if (cb) cb.apply(this, arguments);
126465
+ })
126466
+ }
126467
+ }
126468
+
126469
+ function chownFixSync (orig) {
126470
+ if (!orig) return orig
126471
+ return function (target, uid, gid) {
126472
+ try {
126473
+ return orig.call(fs, target, uid, gid)
126474
+ } catch (er) {
126475
+ if (!chownErOk(er)) throw er
126476
+ }
126477
+ }
126478
+ }
126479
+
126480
+ function statFix (orig) {
126481
+ if (!orig) return orig
126482
+ // Older versions of Node erroneously returned signed integers for
126483
+ // uid + gid.
126484
+ return function (target, options, cb) {
126485
+ if (typeof options === 'function') {
126486
+ cb = options;
126487
+ options = null;
126488
+ }
126489
+ function callback (er, stats) {
126490
+ if (stats) {
126491
+ if (stats.uid < 0) stats.uid += 0x100000000;
126492
+ if (stats.gid < 0) stats.gid += 0x100000000;
126493
+ }
126494
+ if (cb) cb.apply(this, arguments);
126495
+ }
126496
+ return options ? orig.call(fs, target, options, callback)
126497
+ : orig.call(fs, target, callback)
126498
+ }
126499
+ }
126500
+
126501
+ function statFixSync (orig) {
126502
+ if (!orig) return orig
126503
+ // Older versions of Node erroneously returned signed integers for
126504
+ // uid + gid.
126505
+ return function (target, options) {
126506
+ var stats = options ? orig.call(fs, target, options)
126507
+ : orig.call(fs, target);
126508
+ if (stats) {
126509
+ if (stats.uid < 0) stats.uid += 0x100000000;
126510
+ if (stats.gid < 0) stats.gid += 0x100000000;
126511
+ }
126512
+ return stats;
126513
+ }
126514
+ }
126515
+
126516
+ // ENOSYS means that the fs doesn't support the op. Just ignore
126517
+ // that, because it doesn't matter.
126518
+ //
126519
+ // if there's no getuid, or if getuid() is something other
126520
+ // than 0, and the error is EINVAL or EPERM, then just ignore
126521
+ // it.
126522
+ //
126523
+ // This specific case is a silent failure in cp, install, tar,
126524
+ // and most other unix tools that manage permissions.
126525
+ //
126526
+ // When running as root, or if other types of errors are
126527
+ // encountered, then it's strict.
126528
+ function chownErOk (er) {
126529
+ if (!er)
126530
+ return true
126531
+
126532
+ if (er.code === "ENOSYS")
126533
+ return true
126534
+
126535
+ var nonroot = !process.getuid || process.getuid() !== 0;
126536
+ if (nonroot) {
126537
+ if (er.code === "EINVAL" || er.code === "EPERM")
126538
+ return true
126539
+ }
126540
+
126541
+ return false
126542
+ }
126543
+ }
126544
+ return polyfills;
126545
+ }
126546
+
126547
+ var legacyStreams;
126548
+ var hasRequiredLegacyStreams;
126549
+
126550
+ function requireLegacyStreams () {
126551
+ if (hasRequiredLegacyStreams) return legacyStreams;
126552
+ hasRequiredLegacyStreams = 1;
126553
+ var Stream = require$$0$6.Stream;
126554
+
126555
+ legacyStreams = legacy;
126556
+
126557
+ function legacy (fs) {
126558
+ return {
126559
+ ReadStream: ReadStream,
126560
+ WriteStream: WriteStream
126561
+ }
126562
+
126563
+ function ReadStream (path, options) {
126564
+ if (!(this instanceof ReadStream)) return new ReadStream(path, options);
126565
+
126566
+ Stream.call(this);
126567
+
126568
+ var self = this;
126569
+
126570
+ this.path = path;
126571
+ this.fd = null;
126572
+ this.readable = true;
126573
+ this.paused = false;
126574
+
126575
+ this.flags = 'r';
126576
+ this.mode = 438; /*=0666*/
126577
+ this.bufferSize = 64 * 1024;
126578
+
126579
+ options = options || {};
126580
+
126581
+ // Mixin options into this
126582
+ var keys = Object.keys(options);
126583
+ for (var index = 0, length = keys.length; index < length; index++) {
126584
+ var key = keys[index];
126585
+ this[key] = options[key];
126586
+ }
126587
+
126588
+ if (this.encoding) this.setEncoding(this.encoding);
126589
+
126590
+ if (this.start !== undefined) {
126591
+ if ('number' !== typeof this.start) {
126592
+ throw TypeError('start must be a Number');
126593
+ }
126594
+ if (this.end === undefined) {
126595
+ this.end = Infinity;
126596
+ } else if ('number' !== typeof this.end) {
126597
+ throw TypeError('end must be a Number');
126598
+ }
126599
+
126600
+ if (this.start > this.end) {
126601
+ throw new Error('start must be <= end');
126602
+ }
126603
+
126604
+ this.pos = this.start;
126605
+ }
126606
+
126607
+ if (this.fd !== null) {
126608
+ process.nextTick(function() {
126609
+ self._read();
126610
+ });
126611
+ return;
126612
+ }
126613
+
126614
+ fs.open(this.path, this.flags, this.mode, function (err, fd) {
126615
+ if (err) {
126616
+ self.emit('error', err);
126617
+ self.readable = false;
126618
+ return;
126619
+ }
126620
+
126621
+ self.fd = fd;
126622
+ self.emit('open', fd);
126623
+ self._read();
126624
+ });
126625
+ }
126626
+
126627
+ function WriteStream (path, options) {
126628
+ if (!(this instanceof WriteStream)) return new WriteStream(path, options);
126629
+
126630
+ Stream.call(this);
126631
+
126632
+ this.path = path;
126633
+ this.fd = null;
126634
+ this.writable = true;
126635
+
126636
+ this.flags = 'w';
126637
+ this.encoding = 'binary';
126638
+ this.mode = 438; /*=0666*/
126639
+ this.bytesWritten = 0;
126640
+
126641
+ options = options || {};
126642
+
126643
+ // Mixin options into this
126644
+ var keys = Object.keys(options);
126645
+ for (var index = 0, length = keys.length; index < length; index++) {
126646
+ var key = keys[index];
126647
+ this[key] = options[key];
126648
+ }
126649
+
126650
+ if (this.start !== undefined) {
126651
+ if ('number' !== typeof this.start) {
126652
+ throw TypeError('start must be a Number');
126653
+ }
126654
+ if (this.start < 0) {
126655
+ throw new Error('start must be >= zero');
126656
+ }
126657
+
126658
+ this.pos = this.start;
126659
+ }
126660
+
126661
+ this.busy = false;
126662
+ this._queue = [];
126663
+
126664
+ if (this.fd === null) {
126665
+ this._open = fs.open;
126666
+ this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
126667
+ this.flush();
126668
+ }
126669
+ }
126670
+ }
126671
+ return legacyStreams;
126672
+ }
126673
+
126674
+ var clone_1;
126675
+ var hasRequiredClone;
126676
+
126677
+ function requireClone () {
126678
+ if (hasRequiredClone) return clone_1;
126679
+ hasRequiredClone = 1;
126680
+
126681
+ clone_1 = clone;
126682
+
126683
+ var getPrototypeOf = Object.getPrototypeOf || function (obj) {
126684
+ return obj.__proto__
126685
+ };
126686
+
126687
+ function clone (obj) {
126688
+ if (obj === null || typeof obj !== 'object')
126689
+ return obj
126690
+
126691
+ if (obj instanceof Object)
126692
+ var copy = { __proto__: getPrototypeOf(obj) };
126693
+ else
126694
+ var copy = Object.create(null);
126695
+
126696
+ Object.getOwnPropertyNames(obj).forEach(function (key) {
126697
+ Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
126698
+ });
126699
+
126700
+ return copy
126701
+ }
126702
+ return clone_1;
126703
+ }
126704
+
126705
+ var gracefulFs;
126706
+ var hasRequiredGracefulFs;
126707
+
126708
+ function requireGracefulFs () {
126709
+ if (hasRequiredGracefulFs) return gracefulFs;
126710
+ hasRequiredGracefulFs = 1;
126711
+ var fs = fs__default;
126712
+ var polyfills = requirePolyfills();
126713
+ var legacy = requireLegacyStreams();
126714
+ var clone = requireClone();
126715
+
126716
+ var util = require$$0$4;
126717
+
126718
+ /* istanbul ignore next - node 0.x polyfill */
126719
+ var gracefulQueue;
126720
+ var previousSymbol;
126721
+
126722
+ /* istanbul ignore else - node 0.x polyfill */
126723
+ if (typeof Symbol === 'function' && typeof Symbol.for === 'function') {
126724
+ gracefulQueue = Symbol.for('graceful-fs.queue');
126725
+ // This is used in testing by future versions
126726
+ previousSymbol = Symbol.for('graceful-fs.previous');
126727
+ } else {
126728
+ gracefulQueue = '___graceful-fs.queue';
126729
+ previousSymbol = '___graceful-fs.previous';
126730
+ }
126731
+
126732
+ function noop () {}
126733
+
126734
+ function publishQueue(context, queue) {
126735
+ Object.defineProperty(context, gracefulQueue, {
126736
+ get: function() {
126737
+ return queue
126738
+ }
126739
+ });
126740
+ }
126741
+
126742
+ var debug = noop;
126743
+ if (util.debuglog)
126744
+ debug = util.debuglog('gfs4');
126745
+ else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))
126746
+ debug = function() {
126747
+ var m = util.format.apply(util, arguments);
126748
+ m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ');
126749
+ console.error(m);
126750
+ };
126751
+
126752
+ // Once time initialization
126753
+ if (!fs[gracefulQueue]) {
126754
+ // This queue can be shared by multiple loaded instances
126755
+ var queue = commonjsGlobal[gracefulQueue] || [];
126756
+ publishQueue(fs, queue);
126757
+
126758
+ // Patch fs.close/closeSync to shared queue version, because we need
126759
+ // to retry() whenever a close happens *anywhere* in the program.
126760
+ // This is essential when multiple graceful-fs instances are
126761
+ // in play at the same time.
126762
+ fs.close = (function (fs$close) {
126763
+ function close (fd, cb) {
126764
+ return fs$close.call(fs, fd, function (err) {
126765
+ // This function uses the graceful-fs shared queue
126766
+ if (!err) {
126767
+ resetQueue();
126768
+ }
126769
+
126770
+ if (typeof cb === 'function')
126771
+ cb.apply(this, arguments);
126772
+ })
126773
+ }
126774
+
126775
+ Object.defineProperty(close, previousSymbol, {
126776
+ value: fs$close
126777
+ });
126778
+ return close
126779
+ })(fs.close);
126780
+
126781
+ fs.closeSync = (function (fs$closeSync) {
126782
+ function closeSync (fd) {
126783
+ // This function uses the graceful-fs shared queue
126784
+ fs$closeSync.apply(fs, arguments);
126785
+ resetQueue();
126786
+ }
126787
+
126788
+ Object.defineProperty(closeSync, previousSymbol, {
126789
+ value: fs$closeSync
126790
+ });
126791
+ return closeSync
126792
+ })(fs.closeSync);
126793
+
126794
+ if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
126795
+ process.on('exit', function() {
126796
+ debug(fs[gracefulQueue]);
126797
+ require$$0$5.equal(fs[gracefulQueue].length, 0);
126798
+ });
126799
+ }
126800
+ }
126801
+
126802
+ if (!commonjsGlobal[gracefulQueue]) {
126803
+ publishQueue(commonjsGlobal, fs[gracefulQueue]);
126804
+ }
126805
+
126806
+ gracefulFs = patch(clone(fs));
126807
+ if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {
126808
+ gracefulFs = patch(fs);
126809
+ fs.__patched = true;
126810
+ }
126811
+
126812
+ function patch (fs) {
126813
+ // Everything that references the open() function needs to be in here
126814
+ polyfills(fs);
126815
+ fs.gracefulify = patch;
126816
+
126817
+ fs.createReadStream = createReadStream;
126818
+ fs.createWriteStream = createWriteStream;
126819
+ var fs$readFile = fs.readFile;
126820
+ fs.readFile = readFile;
126821
+ function readFile (path, options, cb) {
126822
+ if (typeof options === 'function')
126823
+ cb = options, options = null;
126824
+
126825
+ return go$readFile(path, options, cb)
126826
+
126827
+ function go$readFile (path, options, cb, startTime) {
126828
+ return fs$readFile(path, options, function (err) {
126829
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
126830
+ enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]);
126831
+ else {
126832
+ if (typeof cb === 'function')
126833
+ cb.apply(this, arguments);
126834
+ }
126835
+ })
126836
+ }
126837
+ }
126838
+
126839
+ var fs$writeFile = fs.writeFile;
126840
+ fs.writeFile = writeFile;
126841
+ function writeFile (path, data, options, cb) {
126842
+ if (typeof options === 'function')
126843
+ cb = options, options = null;
126844
+
126845
+ return go$writeFile(path, data, options, cb)
126846
+
126847
+ function go$writeFile (path, data, options, cb, startTime) {
126848
+ return fs$writeFile(path, data, options, function (err) {
126849
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
126850
+ enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]);
126851
+ else {
126852
+ if (typeof cb === 'function')
126853
+ cb.apply(this, arguments);
126854
+ }
126855
+ })
126856
+ }
126857
+ }
126858
+
126859
+ var fs$appendFile = fs.appendFile;
126860
+ if (fs$appendFile)
126861
+ fs.appendFile = appendFile;
126862
+ function appendFile (path, data, options, cb) {
126863
+ if (typeof options === 'function')
126864
+ cb = options, options = null;
126865
+
126866
+ return go$appendFile(path, data, options, cb)
126867
+
126868
+ function go$appendFile (path, data, options, cb, startTime) {
126869
+ return fs$appendFile(path, data, options, function (err) {
126870
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
126871
+ enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]);
126872
+ else {
126873
+ if (typeof cb === 'function')
126874
+ cb.apply(this, arguments);
126875
+ }
126876
+ })
126877
+ }
126878
+ }
126879
+
126880
+ var fs$copyFile = fs.copyFile;
126881
+ if (fs$copyFile)
126882
+ fs.copyFile = copyFile;
126883
+ function copyFile (src, dest, flags, cb) {
126884
+ if (typeof flags === 'function') {
126885
+ cb = flags;
126886
+ flags = 0;
126887
+ }
126888
+ return go$copyFile(src, dest, flags, cb)
126889
+
126890
+ function go$copyFile (src, dest, flags, cb, startTime) {
126891
+ return fs$copyFile(src, dest, flags, function (err) {
126892
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
126893
+ enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]);
126894
+ else {
126895
+ if (typeof cb === 'function')
126896
+ cb.apply(this, arguments);
126897
+ }
126898
+ })
126899
+ }
126900
+ }
126901
+
126902
+ var fs$readdir = fs.readdir;
126903
+ fs.readdir = readdir;
126904
+ var noReaddirOptionVersions = /^v[0-5]\./;
126905
+ function readdir (path, options, cb) {
126906
+ if (typeof options === 'function')
126907
+ cb = options, options = null;
126908
+
126909
+ var go$readdir = noReaddirOptionVersions.test(process.version)
126910
+ ? function go$readdir (path, options, cb, startTime) {
126911
+ return fs$readdir(path, fs$readdirCallback(
126912
+ path, options, cb, startTime
126913
+ ))
126914
+ }
126915
+ : function go$readdir (path, options, cb, startTime) {
126916
+ return fs$readdir(path, options, fs$readdirCallback(
126917
+ path, options, cb, startTime
126918
+ ))
126919
+ };
126920
+
126921
+ return go$readdir(path, options, cb)
126922
+
126923
+ function fs$readdirCallback (path, options, cb, startTime) {
126924
+ return function (err, files) {
126925
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
126926
+ enqueue([
126927
+ go$readdir,
126928
+ [path, options, cb],
126929
+ err,
126930
+ startTime || Date.now(),
126931
+ Date.now()
126932
+ ]);
126933
+ else {
126934
+ if (files && files.sort)
126935
+ files.sort();
126936
+
126937
+ if (typeof cb === 'function')
126938
+ cb.call(this, err, files);
126939
+ }
126940
+ }
126941
+ }
126942
+ }
126943
+
126944
+ if (process.version.substr(0, 4) === 'v0.8') {
126945
+ var legStreams = legacy(fs);
126946
+ ReadStream = legStreams.ReadStream;
126947
+ WriteStream = legStreams.WriteStream;
126948
+ }
126949
+
126950
+ var fs$ReadStream = fs.ReadStream;
126951
+ if (fs$ReadStream) {
126952
+ ReadStream.prototype = Object.create(fs$ReadStream.prototype);
126953
+ ReadStream.prototype.open = ReadStream$open;
126954
+ }
126955
+
126956
+ var fs$WriteStream = fs.WriteStream;
126957
+ if (fs$WriteStream) {
126958
+ WriteStream.prototype = Object.create(fs$WriteStream.prototype);
126959
+ WriteStream.prototype.open = WriteStream$open;
126960
+ }
126961
+
126962
+ Object.defineProperty(fs, 'ReadStream', {
126963
+ get: function () {
126964
+ return ReadStream
126965
+ },
126966
+ set: function (val) {
126967
+ ReadStream = val;
126968
+ },
126969
+ enumerable: true,
126970
+ configurable: true
126971
+ });
126972
+ Object.defineProperty(fs, 'WriteStream', {
126973
+ get: function () {
126974
+ return WriteStream
126975
+ },
126976
+ set: function (val) {
126977
+ WriteStream = val;
126978
+ },
126979
+ enumerable: true,
126980
+ configurable: true
126981
+ });
126982
+
126983
+ // legacy names
126984
+ var FileReadStream = ReadStream;
126985
+ Object.defineProperty(fs, 'FileReadStream', {
126986
+ get: function () {
126987
+ return FileReadStream
126988
+ },
126989
+ set: function (val) {
126990
+ FileReadStream = val;
126991
+ },
126992
+ enumerable: true,
126993
+ configurable: true
126994
+ });
126995
+ var FileWriteStream = WriteStream;
126996
+ Object.defineProperty(fs, 'FileWriteStream', {
126997
+ get: function () {
126998
+ return FileWriteStream
126999
+ },
127000
+ set: function (val) {
127001
+ FileWriteStream = val;
127002
+ },
127003
+ enumerable: true,
127004
+ configurable: true
127005
+ });
127006
+
127007
+ function ReadStream (path, options) {
127008
+ if (this instanceof ReadStream)
127009
+ return fs$ReadStream.apply(this, arguments), this
127010
+ else
127011
+ return ReadStream.apply(Object.create(ReadStream.prototype), arguments)
127012
+ }
127013
+
127014
+ function ReadStream$open () {
127015
+ var that = this;
127016
+ open(that.path, that.flags, that.mode, function (err, fd) {
127017
+ if (err) {
127018
+ if (that.autoClose)
127019
+ that.destroy();
127020
+
127021
+ that.emit('error', err);
127022
+ } else {
127023
+ that.fd = fd;
127024
+ that.emit('open', fd);
127025
+ that.read();
127026
+ }
127027
+ });
127028
+ }
127029
+
127030
+ function WriteStream (path, options) {
127031
+ if (this instanceof WriteStream)
127032
+ return fs$WriteStream.apply(this, arguments), this
127033
+ else
127034
+ return WriteStream.apply(Object.create(WriteStream.prototype), arguments)
127035
+ }
127036
+
127037
+ function WriteStream$open () {
127038
+ var that = this;
127039
+ open(that.path, that.flags, that.mode, function (err, fd) {
127040
+ if (err) {
127041
+ that.destroy();
127042
+ that.emit('error', err);
127043
+ } else {
127044
+ that.fd = fd;
127045
+ that.emit('open', fd);
127046
+ }
127047
+ });
127048
+ }
127049
+
127050
+ function createReadStream (path, options) {
127051
+ return new fs.ReadStream(path, options)
127052
+ }
127053
+
127054
+ function createWriteStream (path, options) {
127055
+ return new fs.WriteStream(path, options)
127056
+ }
127057
+
127058
+ var fs$open = fs.open;
127059
+ fs.open = open;
127060
+ function open (path, flags, mode, cb) {
127061
+ if (typeof mode === 'function')
127062
+ cb = mode, mode = null;
127063
+
127064
+ return go$open(path, flags, mode, cb)
127065
+
127066
+ function go$open (path, flags, mode, cb, startTime) {
127067
+ return fs$open(path, flags, mode, function (err, fd) {
127068
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
127069
+ enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]);
127070
+ else {
127071
+ if (typeof cb === 'function')
127072
+ cb.apply(this, arguments);
127073
+ }
127074
+ })
127075
+ }
127076
+ }
127077
+
127078
+ return fs
127079
+ }
127080
+
127081
+ function enqueue (elem) {
127082
+ debug('ENQUEUE', elem[0].name, elem[1]);
127083
+ fs[gracefulQueue].push(elem);
127084
+ retry();
127085
+ }
127086
+
127087
+ // keep track of the timeout between retry() calls
127088
+ var retryTimer;
127089
+
127090
+ // reset the startTime and lastTime to now
127091
+ // this resets the start of the 60 second overall timeout as well as the
127092
+ // delay between attempts so that we'll retry these jobs sooner
127093
+ function resetQueue () {
127094
+ var now = Date.now();
127095
+ for (var i = 0; i < fs[gracefulQueue].length; ++i) {
127096
+ // entries that are only a length of 2 are from an older version, don't
127097
+ // bother modifying those since they'll be retried anyway.
127098
+ if (fs[gracefulQueue][i].length > 2) {
127099
+ fs[gracefulQueue][i][3] = now; // startTime
127100
+ fs[gracefulQueue][i][4] = now; // lastTime
127101
+ }
127102
+ }
127103
+ // call retry to make sure we're actively processing the queue
127104
+ retry();
127105
+ }
127106
+
127107
+ function retry () {
127108
+ // clear the timer and remove it to help prevent unintended concurrency
127109
+ clearTimeout(retryTimer);
127110
+ retryTimer = undefined;
127111
+
127112
+ if (fs[gracefulQueue].length === 0)
127113
+ return
127114
+
127115
+ var elem = fs[gracefulQueue].shift();
127116
+ var fn = elem[0];
127117
+ var args = elem[1];
127118
+ // these items may be unset if they were added by an older graceful-fs
127119
+ var err = elem[2];
127120
+ var startTime = elem[3];
127121
+ var lastTime = elem[4];
127122
+
127123
+ // if we don't have a startTime we have no way of knowing if we've waited
127124
+ // long enough, so go ahead and retry this item now
127125
+ if (startTime === undefined) {
127126
+ debug('RETRY', fn.name, args);
127127
+ fn.apply(null, args);
127128
+ } else if (Date.now() - startTime >= 60000) {
127129
+ // it's been more than 60 seconds total, bail now
127130
+ debug('TIMEOUT', fn.name, args);
127131
+ var cb = args.pop();
127132
+ if (typeof cb === 'function')
127133
+ cb.call(null, err);
127134
+ } else {
127135
+ // the amount of time between the last attempt and right now
127136
+ var sinceAttempt = Date.now() - lastTime;
127137
+ // the amount of time between when we first tried, and when we last tried
127138
+ // rounded up to at least 1
127139
+ var sinceStart = Math.max(lastTime - startTime, 1);
127140
+ // backoff. wait longer than the total time we've been retrying, but only
127141
+ // up to a maximum of 100ms
127142
+ var desiredDelay = Math.min(sinceStart * 1.2, 100);
127143
+ // it's been long enough since the last retry, do it again
127144
+ if (sinceAttempt >= desiredDelay) {
127145
+ debug('RETRY', fn.name, args);
127146
+ fn.apply(null, args.concat([startTime]));
127147
+ } else {
127148
+ // if we can't do this job yet, push it to the end of the queue
127149
+ // and let the next iteration check again
127150
+ fs[gracefulQueue].push(elem);
127151
+ }
127152
+ }
127153
+
127154
+ // schedule our next run if one isn't already scheduled
127155
+ if (retryTimer === undefined) {
127156
+ retryTimer = setTimeout(retry, 0);
127157
+ }
127158
+ }
127159
+ return gracefulFs;
127160
+ }
127161
+
127162
+ var retry$1 = {};
127163
+
127164
+ var retry_operation;
127165
+ var hasRequiredRetry_operation;
127166
+
127167
+ function requireRetry_operation () {
127168
+ if (hasRequiredRetry_operation) return retry_operation;
127169
+ hasRequiredRetry_operation = 1;
127170
+ function RetryOperation(timeouts, options) {
127171
+ // Compatibility for the old (timeouts, retryForever) signature
127172
+ if (typeof options === 'boolean') {
127173
+ options = { forever: options };
127174
+ }
127175
+
127176
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
127177
+ this._timeouts = timeouts;
127178
+ this._options = options || {};
127179
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
127180
+ this._fn = null;
127181
+ this._errors = [];
127182
+ this._attempts = 1;
127183
+ this._operationTimeout = null;
127184
+ this._operationTimeoutCb = null;
127185
+ this._timeout = null;
127186
+ this._operationStart = null;
127187
+
127188
+ if (this._options.forever) {
127189
+ this._cachedTimeouts = this._timeouts.slice(0);
127190
+ }
127191
+ }
127192
+ retry_operation = RetryOperation;
127193
+
127194
+ RetryOperation.prototype.reset = function() {
127195
+ this._attempts = 1;
127196
+ this._timeouts = this._originalTimeouts;
127197
+ };
127198
+
127199
+ RetryOperation.prototype.stop = function() {
127200
+ if (this._timeout) {
127201
+ clearTimeout(this._timeout);
127202
+ }
127203
+
127204
+ this._timeouts = [];
127205
+ this._cachedTimeouts = null;
127206
+ };
127207
+
127208
+ RetryOperation.prototype.retry = function(err) {
127209
+ if (this._timeout) {
127210
+ clearTimeout(this._timeout);
127211
+ }
127212
+
127213
+ if (!err) {
127214
+ return false;
127215
+ }
127216
+ var currentTime = new Date().getTime();
127217
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
127218
+ this._errors.unshift(new Error('RetryOperation timeout occurred'));
127219
+ return false;
127220
+ }
127221
+
127222
+ this._errors.push(err);
127223
+
127224
+ var timeout = this._timeouts.shift();
127225
+ if (timeout === undefined) {
127226
+ if (this._cachedTimeouts) {
127227
+ // retry forever, only keep last error
127228
+ this._errors.splice(this._errors.length - 1, this._errors.length);
127229
+ this._timeouts = this._cachedTimeouts.slice(0);
127230
+ timeout = this._timeouts.shift();
127231
+ } else {
127232
+ return false;
127233
+ }
127234
+ }
127235
+
127236
+ var self = this;
127237
+ var timer = setTimeout(function() {
127238
+ self._attempts++;
127239
+
127240
+ if (self._operationTimeoutCb) {
127241
+ self._timeout = setTimeout(function() {
127242
+ self._operationTimeoutCb(self._attempts);
127243
+ }, self._operationTimeout);
127244
+
127245
+ if (self._options.unref) {
127246
+ self._timeout.unref();
127247
+ }
127248
+ }
127249
+
127250
+ self._fn(self._attempts);
127251
+ }, timeout);
127252
+
127253
+ if (this._options.unref) {
127254
+ timer.unref();
127255
+ }
127256
+
127257
+ return true;
127258
+ };
127259
+
127260
+ RetryOperation.prototype.attempt = function(fn, timeoutOps) {
127261
+ this._fn = fn;
127262
+
127263
+ if (timeoutOps) {
127264
+ if (timeoutOps.timeout) {
127265
+ this._operationTimeout = timeoutOps.timeout;
127266
+ }
127267
+ if (timeoutOps.cb) {
127268
+ this._operationTimeoutCb = timeoutOps.cb;
127269
+ }
127270
+ }
127271
+
127272
+ var self = this;
127273
+ if (this._operationTimeoutCb) {
127274
+ this._timeout = setTimeout(function() {
127275
+ self._operationTimeoutCb();
127276
+ }, self._operationTimeout);
127277
+ }
127278
+
127279
+ this._operationStart = new Date().getTime();
127280
+
127281
+ this._fn(this._attempts);
127282
+ };
127283
+
127284
+ RetryOperation.prototype.try = function(fn) {
127285
+ console.log('Using RetryOperation.try() is deprecated');
127286
+ this.attempt(fn);
127287
+ };
127288
+
127289
+ RetryOperation.prototype.start = function(fn) {
127290
+ console.log('Using RetryOperation.start() is deprecated');
127291
+ this.attempt(fn);
127292
+ };
127293
+
127294
+ RetryOperation.prototype.start = RetryOperation.prototype.try;
127295
+
127296
+ RetryOperation.prototype.errors = function() {
127297
+ return this._errors;
127298
+ };
127299
+
127300
+ RetryOperation.prototype.attempts = function() {
127301
+ return this._attempts;
127302
+ };
127303
+
127304
+ RetryOperation.prototype.mainError = function() {
127305
+ if (this._errors.length === 0) {
127306
+ return null;
127307
+ }
127308
+
127309
+ var counts = {};
127310
+ var mainError = null;
127311
+ var mainErrorCount = 0;
127312
+
127313
+ for (var i = 0; i < this._errors.length; i++) {
127314
+ var error = this._errors[i];
127315
+ var message = error.message;
127316
+ var count = (counts[message] || 0) + 1;
127317
+
127318
+ counts[message] = count;
127319
+
127320
+ if (count >= mainErrorCount) {
127321
+ mainError = error;
127322
+ mainErrorCount = count;
127323
+ }
127324
+ }
127325
+
127326
+ return mainError;
127327
+ };
127328
+ return retry_operation;
127329
+ }
127330
+
127331
+ var hasRequiredRetry$1;
127332
+
127333
+ function requireRetry$1 () {
127334
+ if (hasRequiredRetry$1) return retry$1;
127335
+ hasRequiredRetry$1 = 1;
127336
+ (function (exports$1) {
127337
+ var RetryOperation = requireRetry_operation();
127338
+
127339
+ exports$1.operation = function(options) {
127340
+ var timeouts = exports$1.timeouts(options);
127341
+ return new RetryOperation(timeouts, {
127342
+ forever: options && options.forever,
127343
+ unref: options && options.unref,
127344
+ maxRetryTime: options && options.maxRetryTime
127345
+ });
127346
+ };
127347
+
127348
+ exports$1.timeouts = function(options) {
127349
+ if (options instanceof Array) {
127350
+ return [].concat(options);
127351
+ }
127352
+
127353
+ var opts = {
127354
+ retries: 10,
127355
+ factor: 2,
127356
+ minTimeout: 1 * 1000,
127357
+ maxTimeout: Infinity,
127358
+ randomize: false
127359
+ };
127360
+ for (var key in options) {
127361
+ opts[key] = options[key];
127362
+ }
127363
+
127364
+ if (opts.minTimeout > opts.maxTimeout) {
127365
+ throw new Error('minTimeout is greater than maxTimeout');
127366
+ }
127367
+
127368
+ var timeouts = [];
127369
+ for (var i = 0; i < opts.retries; i++) {
127370
+ timeouts.push(this.createTimeout(i, opts));
127371
+ }
127372
+
127373
+ if (options && options.forever && !timeouts.length) {
127374
+ timeouts.push(this.createTimeout(i, opts));
127375
+ }
127376
+
127377
+ // sort the array numerically ascending
127378
+ timeouts.sort(function(a,b) {
127379
+ return a - b;
127380
+ });
127381
+
127382
+ return timeouts;
127383
+ };
127384
+
127385
+ exports$1.createTimeout = function(attempt, opts) {
127386
+ var random = (opts.randomize)
127387
+ ? (Math.random() + 1)
127388
+ : 1;
127389
+
127390
+ var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
127391
+ timeout = Math.min(timeout, opts.maxTimeout);
127392
+
127393
+ return timeout;
127394
+ };
127395
+
127396
+ exports$1.wrap = function(obj, options, methods) {
127397
+ if (options instanceof Array) {
127398
+ methods = options;
127399
+ options = null;
127400
+ }
127401
+
127402
+ if (!methods) {
127403
+ methods = [];
127404
+ for (var key in obj) {
127405
+ if (typeof obj[key] === 'function') {
127406
+ methods.push(key);
127407
+ }
127408
+ }
127409
+ }
127410
+
127411
+ for (var i = 0; i < methods.length; i++) {
127412
+ var method = methods[i];
127413
+ var original = obj[method];
127414
+
127415
+ obj[method] = function retryWrapper(original) {
127416
+ var op = exports$1.operation(options);
127417
+ var args = Array.prototype.slice.call(arguments, 1);
127418
+ var callback = args.pop();
127419
+
127420
+ args.push(function(err) {
127421
+ if (op.retry(err)) {
127422
+ return;
127423
+ }
127424
+ if (err) {
127425
+ arguments[0] = op.mainError();
127426
+ }
127427
+ callback.apply(this, arguments);
127428
+ });
127429
+
127430
+ op.attempt(function() {
127431
+ original.apply(obj, args);
127432
+ });
127433
+ }.bind(obj, original);
127434
+ obj[method].options = options;
127435
+ }
127436
+ };
127437
+ } (retry$1));
127438
+ return retry$1;
127439
+ }
127440
+
127441
+ var retry;
127442
+ var hasRequiredRetry;
127443
+
127444
+ function requireRetry () {
127445
+ if (hasRequiredRetry) return retry;
127446
+ hasRequiredRetry = 1;
127447
+ retry = requireRetry$1();
127448
+ return retry;
127449
+ }
127450
+
127451
+ var signalExit = {exports: {}};
127452
+
127453
+ var signals = {exports: {}};
127454
+
127455
+ var hasRequiredSignals;
127456
+
127457
+ function requireSignals () {
127458
+ if (hasRequiredSignals) return signals.exports;
127459
+ hasRequiredSignals = 1;
127460
+ (function (module) {
127461
+ // This is not the set of all possible signals.
127462
+ //
127463
+ // It IS, however, the set of all signals that trigger
127464
+ // an exit on either Linux or BSD systems. Linux is a
127465
+ // superset of the signal names supported on BSD, and
127466
+ // the unknown signals just fail to register, so we can
127467
+ // catch that easily enough.
127468
+ //
127469
+ // Don't bother with SIGKILL. It's uncatchable, which
127470
+ // means that we can't fire any callbacks anyway.
127471
+ //
127472
+ // If a user does happen to register a handler on a non-
127473
+ // fatal signal like SIGWINCH or something, and then
127474
+ // exit, it'll end up firing `process.emit('exit')`, so
127475
+ // the handler will be fired anyway.
127476
+ //
127477
+ // SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised
127478
+ // artificially, inherently leave the process in a
127479
+ // state from which it is not safe to try and enter JS
127480
+ // listeners.
127481
+ module.exports = [
127482
+ 'SIGABRT',
127483
+ 'SIGALRM',
127484
+ 'SIGHUP',
127485
+ 'SIGINT',
127486
+ 'SIGTERM'
127487
+ ];
127488
+
127489
+ if (process.platform !== 'win32') {
127490
+ module.exports.push(
127491
+ 'SIGVTALRM',
127492
+ 'SIGXCPU',
127493
+ 'SIGXFSZ',
127494
+ 'SIGUSR2',
127495
+ 'SIGTRAP',
127496
+ 'SIGSYS',
127497
+ 'SIGQUIT',
127498
+ 'SIGIOT'
127499
+ // should detect profiler and enable/disable accordingly.
127500
+ // see #21
127501
+ // 'SIGPROF'
127502
+ );
127503
+ }
127504
+
127505
+ if (process.platform === 'linux') {
127506
+ module.exports.push(
127507
+ 'SIGIO',
127508
+ 'SIGPOLL',
127509
+ 'SIGPWR',
127510
+ 'SIGSTKFLT',
127511
+ 'SIGUNUSED'
127512
+ );
127513
+ }
127514
+ } (signals));
127515
+ return signals.exports;
127516
+ }
127517
+
127518
+ var hasRequiredSignalExit;
127519
+
127520
+ function requireSignalExit () {
127521
+ if (hasRequiredSignalExit) return signalExit.exports;
127522
+ hasRequiredSignalExit = 1;
127523
+ // Note: since nyc uses this module to output coverage, any lines
127524
+ // that are in the direct sync flow of nyc's outputCoverage are
127525
+ // ignored, since we can never get coverage for them.
127526
+ // grab a reference to node's real process object right away
127527
+ var process = commonjsGlobal.process;
127528
+
127529
+ const processOk = function (process) {
127530
+ return process &&
127531
+ typeof process === 'object' &&
127532
+ typeof process.removeListener === 'function' &&
127533
+ typeof process.emit === 'function' &&
127534
+ typeof process.reallyExit === 'function' &&
127535
+ typeof process.listeners === 'function' &&
127536
+ typeof process.kill === 'function' &&
127537
+ typeof process.pid === 'number' &&
127538
+ typeof process.on === 'function'
127539
+ };
127540
+
127541
+ // some kind of non-node environment, just no-op
127542
+ /* istanbul ignore if */
127543
+ if (!processOk(process)) {
127544
+ signalExit.exports = function () {
127545
+ return function () {}
127546
+ };
127547
+ } else {
127548
+ var assert = require$$0$5;
127549
+ var signals = requireSignals();
127550
+ var isWin = /^win/i.test(process.platform);
127551
+
127552
+ var EE = require$$1$3;
127553
+ /* istanbul ignore if */
127554
+ if (typeof EE !== 'function') {
127555
+ EE = EE.EventEmitter;
127556
+ }
127557
+
127558
+ var emitter;
127559
+ if (process.__signal_exit_emitter__) {
127560
+ emitter = process.__signal_exit_emitter__;
127561
+ } else {
127562
+ emitter = process.__signal_exit_emitter__ = new EE();
127563
+ emitter.count = 0;
127564
+ emitter.emitted = {};
127565
+ }
127566
+
127567
+ // Because this emitter is a global, we have to check to see if a
127568
+ // previous version of this library failed to enable infinite listeners.
127569
+ // I know what you're about to say. But literally everything about
127570
+ // signal-exit is a compromise with evil. Get used to it.
127571
+ if (!emitter.infinite) {
127572
+ emitter.setMaxListeners(Infinity);
127573
+ emitter.infinite = true;
127574
+ }
127575
+
127576
+ signalExit.exports = function (cb, opts) {
127577
+ /* istanbul ignore if */
127578
+ if (!processOk(commonjsGlobal.process)) {
127579
+ return function () {}
127580
+ }
127581
+ assert.equal(typeof cb, 'function', 'a callback must be provided for exit handler');
127582
+
127583
+ if (loaded === false) {
127584
+ load();
127585
+ }
127586
+
127587
+ var ev = 'exit';
127588
+ if (opts && opts.alwaysLast) {
127589
+ ev = 'afterexit';
127590
+ }
127591
+
127592
+ var remove = function () {
127593
+ emitter.removeListener(ev, cb);
127594
+ if (emitter.listeners('exit').length === 0 &&
127595
+ emitter.listeners('afterexit').length === 0) {
127596
+ unload();
127597
+ }
127598
+ };
127599
+ emitter.on(ev, cb);
127600
+
127601
+ return remove
127602
+ };
127603
+
127604
+ var unload = function unload () {
127605
+ if (!loaded || !processOk(commonjsGlobal.process)) {
127606
+ return
127607
+ }
127608
+ loaded = false;
127609
+
127610
+ signals.forEach(function (sig) {
127611
+ try {
127612
+ process.removeListener(sig, sigListeners[sig]);
127613
+ } catch (er) {}
127614
+ });
127615
+ process.emit = originalProcessEmit;
127616
+ process.reallyExit = originalProcessReallyExit;
127617
+ emitter.count -= 1;
127618
+ };
127619
+ signalExit.exports.unload = unload;
127620
+
127621
+ var emit = function emit (event, code, signal) {
127622
+ /* istanbul ignore if */
127623
+ if (emitter.emitted[event]) {
127624
+ return
127625
+ }
127626
+ emitter.emitted[event] = true;
127627
+ emitter.emit(event, code, signal);
127628
+ };
127629
+
127630
+ // { <signal>: <listener fn>, ... }
127631
+ var sigListeners = {};
127632
+ signals.forEach(function (sig) {
127633
+ sigListeners[sig] = function listener () {
127634
+ /* istanbul ignore if */
127635
+ if (!processOk(commonjsGlobal.process)) {
127636
+ return
127637
+ }
127638
+ // If there are no other listeners, an exit is coming!
127639
+ // Simplest way: remove us and then re-send the signal.
127640
+ // We know that this will kill the process, so we can
127641
+ // safely emit now.
127642
+ var listeners = process.listeners(sig);
127643
+ if (listeners.length === emitter.count) {
127644
+ unload();
127645
+ emit('exit', null, sig);
127646
+ /* istanbul ignore next */
127647
+ emit('afterexit', null, sig);
127648
+ /* istanbul ignore next */
127649
+ if (isWin && sig === 'SIGHUP') {
127650
+ // "SIGHUP" throws an `ENOSYS` error on Windows,
127651
+ // so use a supported signal instead
127652
+ sig = 'SIGINT';
127653
+ }
127654
+ /* istanbul ignore next */
127655
+ process.kill(process.pid, sig);
127656
+ }
127657
+ };
127658
+ });
127659
+
127660
+ signalExit.exports.signals = function () {
127661
+ return signals
127662
+ };
127663
+
127664
+ var loaded = false;
127665
+
127666
+ var load = function load () {
127667
+ if (loaded || !processOk(commonjsGlobal.process)) {
127668
+ return
127669
+ }
127670
+ loaded = true;
127671
+
127672
+ // This is the number of onSignalExit's that are in play.
127673
+ // It's important so that we can count the correct number of
127674
+ // listeners on signals, and don't wait for the other one to
127675
+ // handle it instead of us.
127676
+ emitter.count += 1;
127677
+
127678
+ signals = signals.filter(function (sig) {
127679
+ try {
127680
+ process.on(sig, sigListeners[sig]);
127681
+ return true
127682
+ } catch (er) {
127683
+ return false
127684
+ }
127685
+ });
127686
+
127687
+ process.emit = processEmit;
127688
+ process.reallyExit = processReallyExit;
127689
+ };
127690
+ signalExit.exports.load = load;
127691
+
127692
+ var originalProcessReallyExit = process.reallyExit;
127693
+ var processReallyExit = function processReallyExit (code) {
127694
+ /* istanbul ignore if */
127695
+ if (!processOk(commonjsGlobal.process)) {
127696
+ return
127697
+ }
127698
+ process.exitCode = code || /* istanbul ignore next */ 0;
127699
+ emit('exit', process.exitCode, null);
127700
+ /* istanbul ignore next */
127701
+ emit('afterexit', process.exitCode, null);
127702
+ /* istanbul ignore next */
127703
+ originalProcessReallyExit.call(process, process.exitCode);
127704
+ };
127705
+
127706
+ var originalProcessEmit = process.emit;
127707
+ var processEmit = function processEmit (ev, arg) {
127708
+ if (ev === 'exit' && processOk(commonjsGlobal.process)) {
127709
+ /* istanbul ignore else */
127710
+ if (arg !== undefined) {
127711
+ process.exitCode = arg;
127712
+ }
127713
+ var ret = originalProcessEmit.apply(this, arguments);
127714
+ /* istanbul ignore next */
127715
+ emit('exit', process.exitCode, null);
127716
+ /* istanbul ignore next */
127717
+ emit('afterexit', process.exitCode, null);
127718
+ /* istanbul ignore next */
127719
+ return ret
127720
+ } else {
127721
+ return originalProcessEmit.apply(this, arguments)
127722
+ }
127723
+ };
127724
+ }
127725
+ return signalExit.exports;
127726
+ }
127727
+
127728
+ var mtimePrecision = {};
127729
+
127730
+ var hasRequiredMtimePrecision;
127731
+
127732
+ function requireMtimePrecision () {
127733
+ if (hasRequiredMtimePrecision) return mtimePrecision;
127734
+ hasRequiredMtimePrecision = 1;
127735
+
127736
+ const cacheSymbol = Symbol();
127737
+
127738
+ function probe(file, fs, callback) {
127739
+ const cachedPrecision = fs[cacheSymbol];
127740
+
127741
+ if (cachedPrecision) {
127742
+ return fs.stat(file, (err, stat) => {
127743
+ /* istanbul ignore if */
127744
+ if (err) {
127745
+ return callback(err);
127746
+ }
127747
+
127748
+ callback(null, stat.mtime, cachedPrecision);
127749
+ });
127750
+ }
127751
+
127752
+ // Set mtime by ceiling Date.now() to seconds + 5ms so that it's "not on the second"
127753
+ const mtime = new Date((Math.ceil(Date.now() / 1000) * 1000) + 5);
127754
+
127755
+ fs.utimes(file, mtime, mtime, (err) => {
127756
+ /* istanbul ignore if */
127757
+ if (err) {
127758
+ return callback(err);
127759
+ }
127760
+
127761
+ fs.stat(file, (err, stat) => {
127762
+ /* istanbul ignore if */
127763
+ if (err) {
127764
+ return callback(err);
127765
+ }
127766
+
127767
+ const precision = stat.mtime.getTime() % 1000 === 0 ? 's' : 'ms';
127768
+
127769
+ // Cache the precision in a non-enumerable way
127770
+ Object.defineProperty(fs, cacheSymbol, { value: precision });
127771
+
127772
+ callback(null, stat.mtime, precision);
127773
+ });
127774
+ });
127775
+ }
127776
+
127777
+ function getMtime(precision) {
127778
+ let now = Date.now();
127779
+
127780
+ if (precision === 's') {
127781
+ now = Math.ceil(now / 1000) * 1000;
127782
+ }
127783
+
127784
+ return new Date(now);
127785
+ }
127786
+
127787
+ mtimePrecision.probe = probe;
127788
+ mtimePrecision.getMtime = getMtime;
127789
+ return mtimePrecision;
127790
+ }
127791
+
127792
+ var hasRequiredLockfile;
127793
+
127794
+ function requireLockfile () {
127795
+ if (hasRequiredLockfile) return lockfile;
127796
+ hasRequiredLockfile = 1;
127797
+
127798
+ const path = path__default;
127799
+ const fs = requireGracefulFs();
127800
+ const retry = requireRetry();
127801
+ const onExit = requireSignalExit();
127802
+ const mtimePrecision = requireMtimePrecision();
127803
+
127804
+ const locks = {};
127805
+
127806
+ function getLockFile(file, options) {
127807
+ return options.lockfilePath || `${file}.lock`;
127808
+ }
127809
+
127810
+ function resolveCanonicalPath(file, options, callback) {
127811
+ if (!options.realpath) {
127812
+ return callback(null, path.resolve(file));
127813
+ }
127814
+
127815
+ // Use realpath to resolve symlinks
127816
+ // It also resolves relative paths
127817
+ options.fs.realpath(file, callback);
127818
+ }
127819
+
127820
+ function acquireLock(file, options, callback) {
127821
+ const lockfilePath = getLockFile(file, options);
127822
+
127823
+ // Use mkdir to create the lockfile (atomic operation)
127824
+ options.fs.mkdir(lockfilePath, (err) => {
127825
+ if (!err) {
127826
+ // At this point, we acquired the lock!
127827
+ // Probe the mtime precision
127828
+ return mtimePrecision.probe(lockfilePath, options.fs, (err, mtime, mtimePrecision) => {
127829
+ // If it failed, try to remove the lock..
127830
+ /* istanbul ignore if */
127831
+ if (err) {
127832
+ options.fs.rmdir(lockfilePath, () => {});
127833
+
127834
+ return callback(err);
127835
+ }
127836
+
127837
+ callback(null, mtime, mtimePrecision);
127838
+ });
127839
+ }
127840
+
127841
+ // If error is not EEXIST then some other error occurred while locking
127842
+ if (err.code !== 'EEXIST') {
127843
+ return callback(err);
127844
+ }
127845
+
127846
+ // Otherwise, check if lock is stale by analyzing the file mtime
127847
+ if (options.stale <= 0) {
127848
+ return callback(Object.assign(new Error('Lock file is already being held'), { code: 'ELOCKED', file }));
127849
+ }
127850
+
127851
+ options.fs.stat(lockfilePath, (err, stat) => {
127852
+ if (err) {
127853
+ // Retry if the lockfile has been removed (meanwhile)
127854
+ // Skip stale check to avoid recursiveness
127855
+ if (err.code === 'ENOENT') {
127856
+ return acquireLock(file, { ...options, stale: 0 }, callback);
127857
+ }
127858
+
127859
+ return callback(err);
127860
+ }
127861
+
127862
+ if (!isLockStale(stat, options)) {
127863
+ return callback(Object.assign(new Error('Lock file is already being held'), { code: 'ELOCKED', file }));
127864
+ }
127865
+
127866
+ // If it's stale, remove it and try again!
127867
+ // Skip stale check to avoid recursiveness
127868
+ removeLock(file, options, (err) => {
127869
+ if (err) {
127870
+ return callback(err);
127871
+ }
127872
+
127873
+ acquireLock(file, { ...options, stale: 0 }, callback);
127874
+ });
127875
+ });
127876
+ });
127877
+ }
127878
+
127879
+ function isLockStale(stat, options) {
127880
+ return stat.mtime.getTime() < Date.now() - options.stale;
127881
+ }
127882
+
127883
+ function removeLock(file, options, callback) {
127884
+ // Remove lockfile, ignoring ENOENT errors
127885
+ options.fs.rmdir(getLockFile(file, options), (err) => {
127886
+ if (err && err.code !== 'ENOENT') {
127887
+ return callback(err);
127888
+ }
127889
+
127890
+ callback();
127891
+ });
127892
+ }
127893
+
127894
+ function updateLock(file, options) {
127895
+ const lock = locks[file];
127896
+
127897
+ // Just for safety, should never happen
127898
+ /* istanbul ignore if */
127899
+ if (lock.updateTimeout) {
127900
+ return;
127901
+ }
127902
+
127903
+ lock.updateDelay = lock.updateDelay || options.update;
127904
+ lock.updateTimeout = setTimeout(() => {
127905
+ lock.updateTimeout = null;
127906
+
127907
+ // Stat the file to check if mtime is still ours
127908
+ // If it is, we can still recover from a system sleep or a busy event loop
127909
+ options.fs.stat(lock.lockfilePath, (err, stat) => {
127910
+ const isOverThreshold = lock.lastUpdate + options.stale < Date.now();
127911
+
127912
+ // If it failed to update the lockfile, keep trying unless
127913
+ // the lockfile was deleted or we are over the threshold
127914
+ if (err) {
127915
+ if (err.code === 'ENOENT' || isOverThreshold) {
127916
+ return setLockAsCompromised(file, lock, Object.assign(err, { code: 'ECOMPROMISED' }));
127917
+ }
127918
+
127919
+ lock.updateDelay = 1000;
127920
+
127921
+ return updateLock(file, options);
127922
+ }
127923
+
127924
+ const isMtimeOurs = lock.mtime.getTime() === stat.mtime.getTime();
127925
+
127926
+ if (!isMtimeOurs) {
127927
+ return setLockAsCompromised(
127928
+ file,
127929
+ lock,
127930
+ Object.assign(
127931
+ new Error('Unable to update lock within the stale threshold'),
127932
+ { code: 'ECOMPROMISED' }
127933
+ ));
127934
+ }
127935
+
127936
+ const mtime = mtimePrecision.getMtime(lock.mtimePrecision);
127937
+
127938
+ options.fs.utimes(lock.lockfilePath, mtime, mtime, (err) => {
127939
+ const isOverThreshold = lock.lastUpdate + options.stale < Date.now();
127940
+
127941
+ // Ignore if the lock was released
127942
+ if (lock.released) {
127943
+ return;
127944
+ }
127945
+
127946
+ // If it failed to update the lockfile, keep trying unless
127947
+ // the lockfile was deleted or we are over the threshold
127948
+ if (err) {
127949
+ if (err.code === 'ENOENT' || isOverThreshold) {
127950
+ return setLockAsCompromised(file, lock, Object.assign(err, { code: 'ECOMPROMISED' }));
127951
+ }
127952
+
127953
+ lock.updateDelay = 1000;
127954
+
127955
+ return updateLock(file, options);
127956
+ }
127957
+
127958
+ // All ok, keep updating..
127959
+ lock.mtime = mtime;
127960
+ lock.lastUpdate = Date.now();
127961
+ lock.updateDelay = null;
127962
+ updateLock(file, options);
127963
+ });
127964
+ });
127965
+ }, lock.updateDelay);
127966
+
127967
+ // Unref the timer so that the nodejs process can exit freely
127968
+ // This is safe because all acquired locks will be automatically released
127969
+ // on process exit
127970
+
127971
+ // We first check that `lock.updateTimeout.unref` exists because some users
127972
+ // may be using this module outside of NodeJS (e.g., in an electron app),
127973
+ // and in those cases `setTimeout` return an integer.
127974
+ /* istanbul ignore else */
127975
+ if (lock.updateTimeout.unref) {
127976
+ lock.updateTimeout.unref();
127977
+ }
127978
+ }
127979
+
127980
+ function setLockAsCompromised(file, lock, err) {
127981
+ // Signal the lock has been released
127982
+ lock.released = true;
127983
+
127984
+ // Cancel lock mtime update
127985
+ // Just for safety, at this point updateTimeout should be null
127986
+ /* istanbul ignore if */
127987
+ if (lock.updateTimeout) {
127988
+ clearTimeout(lock.updateTimeout);
127989
+ }
127990
+
127991
+ if (locks[file] === lock) {
127992
+ delete locks[file];
127993
+ }
127994
+
127995
+ lock.options.onCompromised(err);
127996
+ }
127997
+
127998
+ // ----------------------------------------------------------
127999
+
128000
+ function lock(file, options, callback) {
128001
+ /* istanbul ignore next */
128002
+ options = {
128003
+ stale: 10000,
128004
+ update: null,
128005
+ realpath: true,
128006
+ retries: 0,
128007
+ fs,
128008
+ onCompromised: (err) => { throw err; },
128009
+ ...options,
128010
+ };
128011
+
128012
+ options.retries = options.retries || 0;
128013
+ options.retries = typeof options.retries === 'number' ? { retries: options.retries } : options.retries;
128014
+ options.stale = Math.max(options.stale || 0, 2000);
128015
+ options.update = options.update == null ? options.stale / 2 : options.update || 0;
128016
+ options.update = Math.max(Math.min(options.update, options.stale / 2), 1000);
128017
+
128018
+ // Resolve to a canonical file path
128019
+ resolveCanonicalPath(file, options, (err, file) => {
128020
+ if (err) {
128021
+ return callback(err);
128022
+ }
128023
+
128024
+ // Attempt to acquire the lock
128025
+ const operation = retry.operation(options.retries);
128026
+
128027
+ operation.attempt(() => {
128028
+ acquireLock(file, options, (err, mtime, mtimePrecision) => {
128029
+ if (operation.retry(err)) {
128030
+ return;
128031
+ }
128032
+
128033
+ if (err) {
128034
+ return callback(operation.mainError());
128035
+ }
128036
+
128037
+ // We now own the lock
128038
+ const lock = locks[file] = {
128039
+ lockfilePath: getLockFile(file, options),
128040
+ mtime,
128041
+ mtimePrecision,
128042
+ options,
128043
+ lastUpdate: Date.now(),
128044
+ };
128045
+
128046
+ // We must keep the lock fresh to avoid staleness
128047
+ updateLock(file, options);
128048
+
128049
+ callback(null, (releasedCallback) => {
128050
+ if (lock.released) {
128051
+ return releasedCallback &&
128052
+ releasedCallback(Object.assign(new Error('Lock is already released'), { code: 'ERELEASED' }));
128053
+ }
128054
+
128055
+ // Not necessary to use realpath twice when unlocking
128056
+ unlock(file, { ...options, realpath: false }, releasedCallback);
128057
+ });
128058
+ });
128059
+ });
128060
+ });
128061
+ }
128062
+
128063
+ function unlock(file, options, callback) {
128064
+ options = {
128065
+ fs,
128066
+ realpath: true,
128067
+ ...options,
128068
+ };
128069
+
128070
+ // Resolve to a canonical file path
128071
+ resolveCanonicalPath(file, options, (err, file) => {
128072
+ if (err) {
128073
+ return callback(err);
128074
+ }
128075
+
128076
+ // Skip if the lock is not acquired
128077
+ const lock = locks[file];
128078
+
128079
+ if (!lock) {
128080
+ return callback(Object.assign(new Error('Lock is not acquired/owned by you'), { code: 'ENOTACQUIRED' }));
128081
+ }
128082
+
128083
+ lock.updateTimeout && clearTimeout(lock.updateTimeout); // Cancel lock mtime update
128084
+ lock.released = true; // Signal the lock has been released
128085
+ delete locks[file]; // Delete from locks
128086
+
128087
+ removeLock(file, options, callback);
128088
+ });
128089
+ }
128090
+
128091
+ function check(file, options, callback) {
128092
+ options = {
128093
+ stale: 10000,
128094
+ realpath: true,
128095
+ fs,
128096
+ ...options,
128097
+ };
128098
+
128099
+ options.stale = Math.max(options.stale || 0, 2000);
128100
+
128101
+ // Resolve to a canonical file path
128102
+ resolveCanonicalPath(file, options, (err, file) => {
128103
+ if (err) {
128104
+ return callback(err);
128105
+ }
128106
+
128107
+ // Check if lockfile exists
128108
+ options.fs.stat(getLockFile(file, options), (err, stat) => {
128109
+ if (err) {
128110
+ // If does not exist, file is not locked. Otherwise, callback with error
128111
+ return err.code === 'ENOENT' ? callback(null, false) : callback(err);
128112
+ }
128113
+
128114
+ // Otherwise, check if lock is stale by analyzing the file mtime
128115
+ return callback(null, !isLockStale(stat, options));
128116
+ });
128117
+ });
128118
+ }
128119
+
128120
+ function getLocks() {
128121
+ return locks;
128122
+ }
128123
+
128124
+ // Remove acquired locks on exit
128125
+ /* istanbul ignore next */
128126
+ onExit(() => {
128127
+ for (const file in locks) {
128128
+ const options = locks[file].options;
128129
+
128130
+ try { options.fs.rmdirSync(getLockFile(file, options)); } catch (e) { /* Empty */ }
128131
+ }
128132
+ });
128133
+
128134
+ lockfile.lock = lock;
128135
+ lockfile.unlock = unlock;
128136
+ lockfile.check = check;
128137
+ lockfile.getLocks = getLocks;
128138
+ return lockfile;
128139
+ }
128140
+
128141
+ var adapter;
128142
+ var hasRequiredAdapter;
128143
+
128144
+ function requireAdapter () {
128145
+ if (hasRequiredAdapter) return adapter;
128146
+ hasRequiredAdapter = 1;
128147
+
128148
+ const fs = requireGracefulFs();
128149
+
128150
+ function createSyncFs(fs) {
128151
+ const methods = ['mkdir', 'realpath', 'stat', 'rmdir', 'utimes'];
128152
+ const newFs = { ...fs };
128153
+
128154
+ methods.forEach((method) => {
128155
+ newFs[method] = (...args) => {
128156
+ const callback = args.pop();
128157
+ let ret;
128158
+
128159
+ try {
128160
+ ret = fs[`${method}Sync`](...args);
128161
+ } catch (err) {
128162
+ return callback(err);
128163
+ }
128164
+
128165
+ callback(null, ret);
128166
+ };
128167
+ });
128168
+
128169
+ return newFs;
128170
+ }
128171
+
128172
+ // ----------------------------------------------------------
128173
+
128174
+ function toPromise(method) {
128175
+ return (...args) => new Promise((resolve, reject) => {
128176
+ args.push((err, result) => {
128177
+ if (err) {
128178
+ reject(err);
128179
+ } else {
128180
+ resolve(result);
128181
+ }
128182
+ });
128183
+
128184
+ method(...args);
128185
+ });
128186
+ }
128187
+
128188
+ function toSync(method) {
128189
+ return (...args) => {
128190
+ let err;
128191
+ let result;
128192
+
128193
+ args.push((_err, _result) => {
128194
+ err = _err;
128195
+ result = _result;
128196
+ });
128197
+
128198
+ method(...args);
128199
+
128200
+ if (err) {
128201
+ throw err;
128202
+ }
128203
+
128204
+ return result;
128205
+ };
128206
+ }
128207
+
128208
+ function toSyncOptions(options) {
128209
+ // Shallow clone options because we are oging to mutate them
128210
+ options = { ...options };
128211
+
128212
+ // Transform fs to use the sync methods instead
128213
+ options.fs = createSyncFs(options.fs || fs);
128214
+
128215
+ // Retries are not allowed because it requires the flow to be sync
128216
+ if (
128217
+ (typeof options.retries === 'number' && options.retries > 0) ||
128218
+ (options.retries && typeof options.retries.retries === 'number' && options.retries.retries > 0)
128219
+ ) {
128220
+ throw Object.assign(new Error('Cannot use retries with the sync api'), { code: 'ESYNC' });
128221
+ }
128222
+
128223
+ return options;
128224
+ }
128225
+
128226
+ adapter = {
128227
+ toPromise,
128228
+ toSync,
128229
+ toSyncOptions,
128230
+ };
128231
+ return adapter;
128232
+ }
128233
+
128234
+ var hasRequiredProperLockfile;
128235
+
128236
+ function requireProperLockfile () {
128237
+ if (hasRequiredProperLockfile) return properLockfile.exports;
128238
+ hasRequiredProperLockfile = 1;
128239
+
128240
+ const lockfile = requireLockfile();
128241
+ const { toPromise, toSync, toSyncOptions } = requireAdapter();
128242
+
128243
+ async function lock(file, options) {
128244
+ const release = await toPromise(lockfile.lock)(file, options);
128245
+
128246
+ return toPromise(release);
128247
+ }
128248
+
128249
+ function lockSync(file, options) {
128250
+ const release = toSync(lockfile.lock)(file, toSyncOptions(options));
128251
+
128252
+ return toSync(release);
128253
+ }
128254
+
128255
+ function unlock(file, options) {
128256
+ return toPromise(lockfile.unlock)(file, options);
128257
+ }
128258
+
128259
+ function unlockSync(file, options) {
128260
+ return toSync(lockfile.unlock)(file, toSyncOptions(options));
128261
+ }
128262
+
128263
+ function check(file, options) {
128264
+ return toPromise(lockfile.check)(file, options);
128265
+ }
128266
+
128267
+ function checkSync(file, options) {
128268
+ return toSync(lockfile.check)(file, toSyncOptions(options));
128269
+ }
128270
+
128271
+ properLockfile.exports = lock;
128272
+ properLockfile.exports.lock = lock;
128273
+ properLockfile.exports.unlock = unlock;
128274
+ properLockfile.exports.lockSync = lockSync;
128275
+ properLockfile.exports.unlockSync = unlockSync;
128276
+ properLockfile.exports.check = check;
128277
+ properLockfile.exports.checkSync = checkSync;
128278
+ return properLockfile.exports;
128279
+ }
128280
+
128281
+ var properLockfileExports = requireProperLockfile();
128282
+
128283
+ const DIR = "/tmp/neeto-auth-web";
126178
128284
  const CONFIG$1 = {
126179
- DIR: "/tmp/neeto-auth-web",
128285
+ DIR,
126180
128286
  LOG: "/tmp/neeto-auth-server.log",
126181
128287
  PORT: 9000,
126182
128288
  MAX_WAIT_MS: 120_000,
126183
- EMAIL_INIT: "/tmp/neeto-auth-web/config/initializers/playwright_email_capture.rb",
128289
+ WAIT_FOR_SERVER_POLL_MS: 3000,
128290
+ EMAIL_INIT: path.join(DIR, "config", "initializers", "playwright_email_capture.rb"),
128291
+ SETUP_COMPLETE_MARKER: path.join(DIR, ".playwright_setup_complete"),
128292
+ SETUP_LOCK: "/tmp/neeto-auth-web-setup.lock",
128293
+ SETUP_LOCK_STALE_MS: 30_000,
128294
+ SETUP_LOCK_UPDATE_MS: 10_000,
128295
+ SETUP_LOCK_RETRIES: 480,
128296
+ SETUP_LOCK_RETRY_INTERVAL_MS: 1000,
128297
+ SERVER_PID_FILE: path.join(DIR, "tmp", "pids", "server.pid"),
128298
+ DIR_RELEASE_TIMEOUT_MS: 5000,
128299
+ DIR_RELEASE_POLL_MS: 200,
128300
+ PROCESS_EXIT_TIMEOUT_MS: 10_000,
128301
+ PROCESS_EXIT_POLL_MS: 500,
128302
+ USERS_DIR: "/tmp/neeto-auth-web-users",
128303
+ USERS_LOCK: "/tmp/neeto-auth-web-users.lock",
128304
+ USERS_LOCK_STALE_MS: 30_000,
128305
+ USERS_LOCK_RETRIES: 400,
128306
+ USERS_LOCK_RETRY_INTERVAL_MS: 100,
126184
128307
  };
126185
128308
  const __dirname$2 = getDirname(import.meta.url);
126186
128309
  const SCRIPTS_DIR$1 = path.join(__dirname$2, "scripts", "neeto-auth");
@@ -126199,6 +128322,33 @@ const httpCheck$1 = (port, timeout = 3000) => new Promise(resolve => {
126199
128322
  resolve(false);
126200
128323
  });
126201
128324
  });
128325
+ const pollUntil = async (check, timeoutMs, intervalMs) => {
128326
+ const deadline = Date.now() + timeoutMs;
128327
+ while (Date.now() < deadline) {
128328
+ if (await check())
128329
+ return true;
128330
+ await sleep$1(intervalMs);
128331
+ }
128332
+ return false;
128333
+ };
128334
+ const isProcessAlive = (pid) => {
128335
+ try {
128336
+ process.kill(pid, 0);
128337
+ return true;
128338
+ }
128339
+ catch {
128340
+ return false;
128341
+ }
128342
+ };
128343
+ const listPids = (lsofArgs) => (spawnSync("lsof", ["-t", ...lsofArgs], { encoding: "utf-8" }).stdout ?? "")
128344
+ .split("\n")
128345
+ .map(Number)
128346
+ .filter(pid => Number.isInteger(pid) && pid > 0);
128347
+ // "-i" reads the argument as a port, "-sTCP:LISTEN" drops httpCheck's client sockets.
128348
+ const listServerPids = (port) => listPids(["-i", `tcp:${port}`, "-sTCP:LISTEN"]).filter(pid => pid !== process.pid);
128349
+ const readServerLog = () => fs.existsSync(CONFIG$1.LOG)
128350
+ ? fs.readFileSync(CONFIG$1.LOG, "utf-8")
128351
+ : "<no log file>";
126202
128352
  class NeetoAuthServer {
126203
128353
  process = null;
126204
128354
  targetApp;
@@ -126213,90 +128363,144 @@ class NeetoAuthServer {
126213
128363
  POSTGRES_USER: process.env.POSTGRES_USER ?? process.env.USER ?? "postgres",
126214
128364
  };
126215
128365
  }
126216
- waitForProcessExit = async (pid) => {
126217
- const deadline = Date.now() + 10_000;
126218
- while (Date.now() < deadline) {
126219
- try {
126220
- process.kill(pid, 0);
126221
- await sleep$1(500);
126222
- }
126223
- catch {
126224
- return;
126225
- }
126226
- }
128366
+ get userMarkerPath() {
128367
+ return path.join(CONFIG$1.USERS_DIR, String(process.pid));
128368
+ }
128369
+ registerAsUser = () => {
128370
+ fs.mkdirSync(CONFIG$1.USERS_DIR, { recursive: true });
128371
+ fs.writeFileSync(this.userMarkerPath, "");
128372
+ };
128373
+ // Deletes dead markers instead of skipping them: a reused pid would read as alive.
128374
+ listLiveUsers = () => {
128375
+ if (!fs.existsSync(CONFIG$1.USERS_DIR))
128376
+ return [];
128377
+ return fs.readdirSync(CONFIG$1.USERS_DIR).filter(pid => {
128378
+ if (isProcessAlive(Number(pid)))
128379
+ return true;
128380
+ fs.rmSync(path.join(CONFIG$1.USERS_DIR, pid), { force: true });
128381
+ return false;
128382
+ });
126227
128383
  };
128384
+ killPids = (pids, signal) => pids.forEach(pid => {
128385
+ try {
128386
+ process.kill(pid, signal);
128387
+ }
128388
+ catch {
128389
+ // Already gone.
128390
+ }
128391
+ });
128392
+ waitUntilDirIsFree = () => pollUntil(() => listPids(["+D", CONFIG$1.DIR]).length === 0, CONFIG$1.DIR_RELEASE_TIMEOUT_MS, CONFIG$1.DIR_RELEASE_POLL_MS);
126228
128393
  killServerOnPort = async () => {
128394
+ this.killPids(listServerPids(CONFIG$1.PORT), "SIGKILL");
128395
+ await sleep$1(1000);
128396
+ };
128397
+ acquireSetupLock = async () => {
126229
128398
  try {
126230
- execSync(`lsof -ti tcp:${CONFIG$1.PORT} | xargs kill -9`, {
126231
- stdio: "ignore",
128399
+ return await properLockfileExports.lock(CONFIG$1.DIR, {
128400
+ lockfilePath: CONFIG$1.SETUP_LOCK,
128401
+ realpath: false,
128402
+ stale: CONFIG$1.SETUP_LOCK_STALE_MS,
128403
+ update: CONFIG$1.SETUP_LOCK_UPDATE_MS,
128404
+ retries: {
128405
+ retries: CONFIG$1.SETUP_LOCK_RETRIES,
128406
+ minTimeout: CONFIG$1.SETUP_LOCK_RETRY_INTERVAL_MS,
128407
+ maxTimeout: CONFIG$1.SETUP_LOCK_RETRY_INTERVAL_MS,
128408
+ },
128409
+ onCompromised: error => log$1(`Setup lock was compromised: ${error.message}`),
126232
128410
  });
126233
- await sleep$1(1000);
126234
128411
  }
126235
- catch {
126236
- // No process on that port — nothing to kill.
128412
+ catch (error) {
128413
+ if (error.code !== "ELOCKED")
128414
+ throw error;
128415
+ throw new Error(`[NeetoAuth] Waited ${(CONFIG$1.SETUP_LOCK_RETRIES * CONFIG$1.SETUP_LOCK_RETRY_INTERVAL_MS) /
128416
+ 60_000} minutes for another worker to finish the neeto-auth-web setup, and it ` +
128417
+ `still holds ${CONFIG$1.SETUP_LOCK}. Delete that file if no setup is running.`);
126237
128418
  }
126238
128419
  };
126239
- ensureSetup = () => {
126240
- if (fs.existsSync(`${CONFIG$1.DIR}/Gemfile`)) {
128420
+ withSetupLock = async (fn) => {
128421
+ const release = await this.acquireSetupLock();
128422
+ try {
128423
+ await fn();
128424
+ }
128425
+ finally {
128426
+ // A compromised lock is already released; rethrowing here would mask fn()'s error.
128427
+ await release().catch(() => { });
128428
+ }
128429
+ };
128430
+ // Separate from the setup lock: the fast path must not queue behind a setup.
128431
+ withUsersLock = async (fn) => {
128432
+ const release = await properLockfileExports.lock(CONFIG$1.USERS_DIR, {
128433
+ lockfilePath: CONFIG$1.USERS_LOCK,
128434
+ realpath: false,
128435
+ stale: CONFIG$1.USERS_LOCK_STALE_MS,
128436
+ retries: {
128437
+ retries: CONFIG$1.USERS_LOCK_RETRIES,
128438
+ minTimeout: CONFIG$1.USERS_LOCK_RETRY_INTERVAL_MS,
128439
+ maxTimeout: CONFIG$1.USERS_LOCK_RETRY_INTERVAL_MS,
128440
+ },
128441
+ onCompromised: error => log$1(`Users lock was compromised: ${error.message}`),
128442
+ });
128443
+ try {
128444
+ return await fn();
128445
+ }
128446
+ finally {
128447
+ await release().catch(() => { });
128448
+ }
128449
+ };
128450
+ ensureSetup = async () => {
128451
+ if (fs.existsSync(CONFIG$1.SETUP_COMPLETE_MARKER)) {
126241
128452
  log$1("Already set up, skipping.");
126242
128453
  return;
126243
128454
  }
126244
128455
  if (!process.env.GITHUB_TOKEN) {
126245
128456
  throw new Error("[NeetoAuth] GITHUB_TOKEN is not set. Cannot clone neeto-auth-web.");
126246
128457
  }
128458
+ if (fs.existsSync(CONFIG$1.DIR)) {
128459
+ // We hold the setup lock and the port is free, so anything using this directory is an orphan.
128460
+ log$1("Found an incomplete previous setup — killing any lingering " +
128461
+ "process using it and cleaning up before retrying.");
128462
+ this.killPids(listPids(["+D", CONFIG$1.DIR]), "SIGKILL");
128463
+ await this.waitUntilDirIsFree();
128464
+ fs.rmSync(CONFIG$1.DIR, { recursive: true, force: true });
128465
+ }
126247
128466
  log$1("Running first-time setup...");
126248
- const setupScript = path.join(SCRIPTS_DIR$1, "setup.sh");
126249
128467
  try {
126250
- execSync(`bash "${setupScript}" "${CONFIG$1.DIR}"`, {
126251
- stdio: "inherit",
126252
- env: this.serverEnv,
126253
- });
128468
+ await this.runSetupScript();
128469
+ fs.writeFileSync(CONFIG$1.SETUP_COMPLETE_MARKER, "");
126254
128470
  }
126255
128471
  catch {
126256
128472
  throw new Error("[NeetoAuth] First-time setup failed. Check the output above for details.");
126257
128473
  }
126258
128474
  log$1("Setup complete.");
126259
128475
  };
128476
+ // Async, not execSync: a blocked event loop stops proper-lockfile refreshing the lock.
128477
+ runSetupScript = () => new Promise((resolve, reject) => {
128478
+ const setupScript = path.join(SCRIPTS_DIR$1, "setup.sh");
128479
+ const child = spawn("bash", [setupScript, CONFIG$1.DIR], {
128480
+ stdio: "inherit",
128481
+ env: this.serverEnv,
128482
+ });
128483
+ child.on("error", reject);
128484
+ child.on("exit", code => code === 0
128485
+ ? resolve()
128486
+ : reject(new Error(`setup.sh exited with code ${code}`)));
128487
+ });
126260
128488
  waitForServer = async (timeoutMs = CONFIG$1.MAX_WAIT_MS) => {
126261
- const startTime = Date.now();
126262
- while (Date.now() - startTime < timeoutMs) {
128489
+ const started = await pollUntil(() => {
126263
128490
  if (this.process !== null && this.process.exitCode !== null) {
126264
- const logContent = fs.existsSync(CONFIG$1.LOG)
126265
- ? fs.readFileSync(CONFIG$1.LOG, "utf-8")
126266
- : "<no log file>";
126267
- throw new Error(`[NeetoAuth] Server process exited unexpectedly with code ${this.process.exitCode}.\nLog:\n${logContent}`);
128491
+ throw new Error(`[NeetoAuth] Server process exited unexpectedly with code ${this.process.exitCode}.\nLog:\n${readServerLog()}`);
126268
128492
  }
126269
- if (await httpCheck$1(CONFIG$1.PORT))
126270
- return;
126271
- await sleep$1(3000);
126272
- }
126273
- const logContent = fs.existsSync(CONFIG$1.LOG)
126274
- ? fs.readFileSync(CONFIG$1.LOG, "utf-8")
126275
- : "<no log file>";
126276
- throw new Error(`[NeetoAuth] Server did not start within ${timeoutMs / 1000}s.\nLog:\n${logContent}`);
126277
- };
126278
- injectEmailCaptureInitializer = () => {
126279
- fs.writeFileSync(CONFIG$1.EMAIL_INIT, buildEmailCaptureInitializer(this.targetApp));
126280
- };
126281
- isRunningForCurrentApp = () => {
126282
- if (!fs.existsSync(CONFIG$1.EMAIL_INIT))
126283
- return false;
126284
- const currentContent = fs.readFileSync(CONFIG$1.EMAIL_INIT, "utf-8");
126285
- return currentContent === buildEmailCaptureInitializer(this.targetApp);
126286
- };
126287
- start = async () => {
126288
- if (IS_STAGING_ENV)
128493
+ return httpCheck$1(CONFIG$1.PORT);
128494
+ }, timeoutMs, CONFIG$1.WAIT_FOR_SERVER_POLL_MS);
128495
+ if (started)
126289
128496
  return;
126290
- if (await httpCheck$1(CONFIG$1.PORT)) {
126291
- if (this.isRunningForCurrentApp()) {
126292
- log$1("Server already running for this app.");
126293
- return;
126294
- }
126295
- log$1("Server running for a different app restarting...");
126296
- await this.killServerOnPort();
126297
- }
126298
- this.ensureSetup();
126299
- this.injectEmailCaptureInitializer();
128497
+ throw new Error(`[NeetoAuth] Server did not start within ${timeoutMs / 1000}s.\nLog:\n${readServerLog()}`);
128498
+ };
128499
+ spawnServer = async () => {
128500
+ // Nothing can be using a server that does not exist yet, so these are from a previous run.
128501
+ fs.rmSync(CONFIG$1.USERS_DIR, { recursive: true, force: true });
128502
+ // Puma refuses to start over a pidfile it thinks is alive; the port is already confirmed free, so this one is stale.
128503
+ fs.rmSync(CONFIG$1.SERVER_PID_FILE, { force: true });
126300
128504
  log$1("Starting server...");
126301
128505
  const logStream = fs.createWriteStream(CONFIG$1.LOG);
126302
128506
  this.process = spawn("bundle", [
@@ -126317,16 +128521,70 @@ class NeetoAuthServer {
126317
128521
  await this.waitForServer();
126318
128522
  log$1("Server ready.");
126319
128523
  };
126320
- stop = async () => {
126321
- if (IS_STAGING_ENV || !this.process)
128524
+ injectEmailCaptureInitializer = () => {
128525
+ fs.writeFileSync(CONFIG$1.EMAIL_INIT, buildEmailCaptureInitializer(this.targetApp));
128526
+ };
128527
+ isRunningForCurrentApp = () => {
128528
+ if (!fs.existsSync(CONFIG$1.EMAIL_INIT))
128529
+ return false;
128530
+ const currentContent = fs.readFileSync(CONFIG$1.EMAIL_INIT, "utf-8");
128531
+ return currentContent === buildEmailCaptureInitializer(this.targetApp);
128532
+ };
128533
+ isServingCurrentApp = async () => (await httpCheck$1(CONFIG$1.PORT)) && this.isRunningForCurrentApp();
128534
+ start = async () => {
128535
+ if (IS_STAGING_ENV)
128536
+ return;
128537
+ // Checking and registering under one lock stops us adopting a doomed server.
128538
+ const adopted = await this.withUsersLock(async () => {
128539
+ if (!(await this.isServingCurrentApp()))
128540
+ return false;
128541
+ this.registerAsUser();
128542
+ return true;
128543
+ });
128544
+ if (adopted) {
128545
+ log$1("Server already running for this app.");
126322
128546
  return;
126323
- const pid = this.process.pid;
126324
- log$1("Stopping server...");
126325
- this.process.kill("SIGTERM");
126326
- this.process = null;
126327
- if (pid) {
126328
- await this.waitForProcessExit(pid);
126329
128547
  }
128548
+ await this.withSetupLock(async () => {
128549
+ // Re-check: another worker may have finished setup while we waited for the lock.
128550
+ if (await this.isServingCurrentApp()) {
128551
+ log$1("Server already running for this app.");
128552
+ return;
128553
+ }
128554
+ if (await httpCheck$1(CONFIG$1.PORT)) {
128555
+ log$1("Server running for a different app — restarting...");
128556
+ await this.killServerOnPort();
128557
+ }
128558
+ await this.ensureSetup();
128559
+ this.injectEmailCaptureInitializer();
128560
+ await this.spawnServer();
128561
+ });
128562
+ await this.withUsersLock(async () => this.registerAsUser());
128563
+ };
128564
+ stop = async () => {
128565
+ if (IS_STAGING_ENV)
128566
+ return;
128567
+ // The kill stays inside the lock, or a worker could adopt the server in between.
128568
+ await this.withUsersLock(async () => {
128569
+ fs.rmSync(this.userMarkerPath, { force: true });
128570
+ if (this.listLiveUsers().length > 0) {
128571
+ log$1("Other workers still using the server — leaving it running.");
128572
+ return;
128573
+ }
128574
+ if (!this.isRunningForCurrentApp()) {
128575
+ log$1("Server on the port is serving another app — leaving it running.");
128576
+ this.process = null;
128577
+ return;
128578
+ }
128579
+ log$1("Stopping server...");
128580
+ const pids = listServerPids(CONFIG$1.PORT);
128581
+ this.killPids(pids, "SIGTERM");
128582
+ await Promise.all(pids.map(pid => pollUntil(() => !isProcessAlive(pid), CONFIG$1.PROCESS_EXIT_TIMEOUT_MS, CONFIG$1.PROCESS_EXIT_POLL_MS)));
128583
+ this.killPids(listServerPids(CONFIG$1.PORT), "SIGKILL"); // Any stragglers.
128584
+ // A start() that failed before binding leaves a child the sweep cannot see.
128585
+ this.process?.kill("SIGKILL");
128586
+ this.process = null;
128587
+ });
126330
128588
  };
126331
128589
  }
126332
128590