@andersbakken/fisk 5.0.13 → 5.0.16

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