UNPKG

vitepress

Version:

Vite & Vue powered static site generator

1,703 lines (1,464 loc) 1.59 MB
import { createHash } from 'crypto'; import { createRequire } from 'module'; import path$q, { resolve as resolve$1, parse as parse$b, basename, join, dirname, normalize as normalize$3 } from 'path'; import path$r, { win32, posix as posix$1 } from 'node:path'; import process$2, { stdin, stdout } from 'node:process'; import { lstat as lstat$4, readdir as readdir$5, readlink, realpath } from 'node:fs/promises'; import { fileURLToPath } from 'node:url'; import * as fs$t from 'node:fs'; import fs__default$1 from 'node:fs'; import * as fs$u from 'fs'; import fs__default, { realpathSync as realpathSync$1, lstatSync, readdir as readdir$4, readdirSync as readdirSync$1, readlinkSync, unlinkSync, rmdirSync, chmodSync, statSync as statSync$1, renameSync, rmSync } from 'fs'; import { EventEmitter } from 'node:events'; import Stream$2 from 'node:stream'; import { StringDecoder } from 'node:string_decoder'; import require$$0$3, { inspect } from 'util'; import require$$0$5, { tmpdir } from 'os'; import require$$3, { fileURLToPath as fileURLToPath$1, URL as URL$1, pathToFileURL } from 'url'; import require$$5 from 'assert'; import require$$0$6 from 'events'; import { normalizePath, loadConfigFromFile, createLogger, mergeConfig as mergeConfig$1, searchForWorkspaceRoot, build as build$1, transformWithEsbuild, createServer as createServer$1 } from 'vite'; import require$$0$2 from 'stream'; import require$$2$1 from 'readline'; import require$$0$7 from 'child_process'; import require$$1 from 'string_decoder'; import zlib from 'zlib'; import { isBooleanAttr } from '@vue/shared'; import f$1 from 'node:readline'; import { WriteStream } from 'node:tty'; import http from 'http'; import * as qs from 'querystring'; import require$$0$4 from 'tty'; import require$$0$1 from 'constants'; import { webcrypto } from 'node:crypto'; import { createHighlighter, bundledLanguages, isSpecialLang } from 'shiki'; import { transformerNotationDiff, transformerNotationFocus, transformerNotationHighlight, transformerNotationErrorLevel, transformerCompactLineOptions } from '@shikijs/transformers'; import MiniSearch from 'minisearch'; var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function getDefaultExportFromCjs (x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; } function getAugmentedNamespace(n) { if (n.__esModule) return n; var f = n.default; if (typeof f == "function") { var a = function a () { if (this instanceof a) { return Reflect.construct(f, arguments, this.constructor); } return f.apply(this, arguments); }; a.prototype = f.prototype; } else a = {}; Object.defineProperty(a, '__esModule', {value: true}); Object.keys(n).forEach(function (k) { var d = Object.getOwnPropertyDescriptor(n, k); Object.defineProperty(a, k, d.get ? d : { enumerable: true, get: function () { return n[k]; } }); }); return a; } var fs$s = {}; var universalify$1 = {}; universalify$1.fromCallback = function (fn) { return Object.defineProperty(function (...args) { if (typeof args[args.length - 1] === 'function') fn.apply(this, args); else { return new Promise((resolve, reject) => { args.push((err, res) => (err != null) ? reject(err) : resolve(res)); fn.apply(this, args); }) } }, 'name', { value: fn.name }) }; universalify$1.fromPromise = function (fn) { return Object.defineProperty(function (...args) { const cb = args[args.length - 1]; if (typeof cb !== 'function') return fn.apply(this, args) else { args.pop(); fn.apply(this, args).then(r => cb(null, r), cb); } }, 'name', { value: fn.name }) }; var constants$5 = require$$0$1; var origCwd = process.cwd; var cwd = null; var platform$1 = process.env.GRACEFUL_FS_PLATFORM || process.platform; process.cwd = function() { if (!cwd) cwd = origCwd.call(process); return cwd }; try { process.cwd(); } catch (er) {} // This check is needed until node.js 12 is required if (typeof process.chdir === 'function') { var chdir = process.chdir; process.chdir = function (d) { cwd = null; chdir.call(process, d); }; if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir); } var polyfills$1 = patch$1; function patch$1 (fs) { // (re-)implement some things that are known busted or missing. // lchmod, broken prior to 0.6.2 // back-port the fix here. if (constants$5.hasOwnProperty('O_SYMLINK') && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { patchLchmod(fs); } // lutimes implementation, or no-op if (!fs.lutimes) { patchLutimes(fs); } // https://github.com/isaacs/node-graceful-fs/issues/4 // Chown should not fail on einval or eperm if non-root. // It should not fail on enosys ever, as this just indicates // that a fs doesn't support the intended operation. fs.chown = chownFix(fs.chown); fs.fchown = chownFix(fs.fchown); fs.lchown = chownFix(fs.lchown); fs.chmod = chmodFix(fs.chmod); fs.fchmod = chmodFix(fs.fchmod); fs.lchmod = chmodFix(fs.lchmod); fs.chownSync = chownFixSync(fs.chownSync); fs.fchownSync = chownFixSync(fs.fchownSync); fs.lchownSync = chownFixSync(fs.lchownSync); fs.chmodSync = chmodFixSync(fs.chmodSync); fs.fchmodSync = chmodFixSync(fs.fchmodSync); fs.lchmodSync = chmodFixSync(fs.lchmodSync); fs.stat = statFix(fs.stat); fs.fstat = statFix(fs.fstat); fs.lstat = statFix(fs.lstat); fs.statSync = statFixSync(fs.statSync); fs.fstatSync = statFixSync(fs.fstatSync); fs.lstatSync = statFixSync(fs.lstatSync); // if lchmod/lchown do not exist, then make them no-ops if (fs.chmod && !fs.lchmod) { fs.lchmod = function (path, mode, cb) { if (cb) process.nextTick(cb); }; fs.lchmodSync = function () {}; } if (fs.chown && !fs.lchown) { fs.lchown = function (path, uid, gid, cb) { if (cb) process.nextTick(cb); }; fs.lchownSync = function () {}; } // on Windows, A/V software can lock the directory, causing this // to fail with an EACCES or EPERM if the directory contains newly // created files. Try again on failure, for up to 60 seconds. // Set the timeout this long because some Windows Anti-Virus, such as Parity // bit9, may lock files for up to a minute, causing npm package install // failures. Also, take care to yield the scheduler. Windows scheduling gives // CPU to a busy looping process, which can cause the program causing the lock // contention to be starved of CPU by node, so the contention doesn't resolve. if (platform$1 === "win32") { fs.rename = typeof fs.rename !== 'function' ? fs.rename : (function (fs$rename) { function rename (from, to, cb) { var start = Date.now(); var backoff = 0; fs$rename(from, to, function CB (er) { if (er && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") && Date.now() - start < 60000) { setTimeout(function() { fs.stat(to, function (stater, st) { if (stater && stater.code === "ENOENT") fs$rename(from, to, CB); else cb(er); }); }, backoff); if (backoff < 100) backoff += 10; return; } if (cb) cb(er); }); } if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename); return rename })(fs.rename); } // if read() returns EAGAIN, then just try it again. fs.read = typeof fs.read !== 'function' ? fs.read : (function (fs$read) { function read (fd, buffer, offset, length, position, callback_) { var callback; if (callback_ && typeof callback_ === 'function') { var eagCounter = 0; callback = function (er, _, __) { if (er && er.code === 'EAGAIN' && eagCounter < 10) { eagCounter ++; return fs$read.call(fs, fd, buffer, offset, length, position, callback) } callback_.apply(this, arguments); }; } return fs$read.call(fs, fd, buffer, offset, length, position, callback) } // This ensures `util.promisify` works as it does for native `fs.read`. if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read); return read })(fs.read); fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync : (function (fs$readSync) { return function (fd, buffer, offset, length, position) { var eagCounter = 0; while (true) { try { return fs$readSync.call(fs, fd, buffer, offset, length, position) } catch (er) { if (er.code === 'EAGAIN' && eagCounter < 10) { eagCounter ++; continue } throw er } } }})(fs.readSync); function patchLchmod (fs) { fs.lchmod = function (path, mode, callback) { fs.open( path , constants$5.O_WRONLY | constants$5.O_SYMLINK , mode , function (err, fd) { if (err) { if (callback) callback(err); return } // prefer to return the chmod error, if one occurs, // but still try to close, and report closing errors if they occur. fs.fchmod(fd, mode, function (err) { fs.close(fd, function(err2) { if (callback) callback(err || err2); }); }); }); }; fs.lchmodSync = function (path, mode) { var fd = fs.openSync(path, constants$5.O_WRONLY | constants$5.O_SYMLINK, mode); // prefer to return the chmod error, if one occurs, // but still try to close, and report closing errors if they occur. var threw = true; var ret; try { ret = fs.fchmodSync(fd, mode); threw = false; } finally { if (threw) { try { fs.closeSync(fd); } catch (er) {} } else { fs.closeSync(fd); } } return ret }; } function patchLutimes (fs) { if (constants$5.hasOwnProperty("O_SYMLINK") && fs.futimes) { fs.lutimes = function (path, at, mt, cb) { fs.open(path, constants$5.O_SYMLINK, function (er, fd) { if (er) { if (cb) cb(er); return } fs.futimes(fd, at, mt, function (er) { fs.close(fd, function (er2) { if (cb) cb(er || er2); }); }); }); }; fs.lutimesSync = function (path, at, mt) { var fd = fs.openSync(path, constants$5.O_SYMLINK); var ret; var threw = true; try { ret = fs.futimesSync(fd, at, mt); threw = false; } finally { if (threw) { try { fs.closeSync(fd); } catch (er) {} } else { fs.closeSync(fd); } } return ret }; } else if (fs.futimes) { fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb); }; fs.lutimesSync = function () {}; } } function chmodFix (orig) { if (!orig) return orig return function (target, mode, cb) { return orig.call(fs, target, mode, function (er) { if (chownErOk(er)) er = null; if (cb) cb.apply(this, arguments); }) } } function chmodFixSync (orig) { if (!orig) return orig return function (target, mode) { try { return orig.call(fs, target, mode) } catch (er) { if (!chownErOk(er)) throw er } } } function chownFix (orig) { if (!orig) return orig return function (target, uid, gid, cb) { return orig.call(fs, target, uid, gid, function (er) { if (chownErOk(er)) er = null; if (cb) cb.apply(this, arguments); }) } } function chownFixSync (orig) { if (!orig) return orig return function (target, uid, gid) { try { return orig.call(fs, target, uid, gid) } catch (er) { if (!chownErOk(er)) throw er } } } function statFix (orig) { if (!orig) return orig // Older versions of Node erroneously returned signed integers for // uid + gid. return function (target, options, cb) { if (typeof options === 'function') { cb = options; options = null; } function callback (er, stats) { if (stats) { if (stats.uid < 0) stats.uid += 0x100000000; if (stats.gid < 0) stats.gid += 0x100000000; } if (cb) cb.apply(this, arguments); } return options ? orig.call(fs, target, options, callback) : orig.call(fs, target, callback) } } function statFixSync (orig) { if (!orig) return orig // Older versions of Node erroneously returned signed integers for // uid + gid. return function (target, options) { var stats = options ? orig.call(fs, target, options) : orig.call(fs, target); if (stats) { if (stats.uid < 0) stats.uid += 0x100000000; if (stats.gid < 0) stats.gid += 0x100000000; } return stats; } } // ENOSYS means that the fs doesn't support the op. Just ignore // that, because it doesn't matter. // // if there's no getuid, or if getuid() is something other // than 0, and the error is EINVAL or EPERM, then just ignore // it. // // This specific case is a silent failure in cp, install, tar, // and most other unix tools that manage permissions. // // When running as root, or if other types of errors are // encountered, then it's strict. function chownErOk (er) { if (!er) return true if (er.code === "ENOSYS") return true var nonroot = !process.getuid || process.getuid() !== 0; if (nonroot) { if (er.code === "EINVAL" || er.code === "EPERM") return true } return false } } var Stream$1 = require$$0$2.Stream; var legacyStreams = legacy$1; function legacy$1 (fs) { return { ReadStream: ReadStream, WriteStream: WriteStream } function ReadStream (path, options) { if (!(this instanceof ReadStream)) return new ReadStream(path, options); Stream$1.call(this); var self = this; this.path = path; this.fd = null; this.readable = true; this.paused = false; this.flags = 'r'; this.mode = 438; /*=0666*/ this.bufferSize = 64 * 1024; options = options || {}; // Mixin options into this var keys = Object.keys(options); for (var index = 0, length = keys.length; index < length; index++) { var key = keys[index]; this[key] = options[key]; } if (this.encoding) this.setEncoding(this.encoding); if (this.start !== undefined) { if ('number' !== typeof this.start) { throw TypeError('start must be a Number'); } if (this.end === undefined) { this.end = Infinity; } else if ('number' !== typeof this.end) { throw TypeError('end must be a Number'); } if (this.start > this.end) { throw new Error('start must be <= end'); } this.pos = this.start; } if (this.fd !== null) { process.nextTick(function() { self._read(); }); return; } fs.open(this.path, this.flags, this.mode, function (err, fd) { if (err) { self.emit('error', err); self.readable = false; return; } self.fd = fd; self.emit('open', fd); self._read(); }); } function WriteStream (path, options) { if (!(this instanceof WriteStream)) return new WriteStream(path, options); Stream$1.call(this); this.path = path; this.fd = null; this.writable = true; this.flags = 'w'; this.encoding = 'binary'; this.mode = 438; /*=0666*/ this.bytesWritten = 0; options = options || {}; // Mixin options into this var keys = Object.keys(options); for (var index = 0, length = keys.length; index < length; index++) { var key = keys[index]; this[key] = options[key]; } if (this.start !== undefined) { if ('number' !== typeof this.start) { throw TypeError('start must be a Number'); } if (this.start < 0) { throw new Error('start must be >= zero'); } this.pos = this.start; } this.busy = false; this._queue = []; if (this.fd === null) { this._open = fs.open; this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); this.flush(); } } } var clone_1 = clone$1; var getPrototypeOf = Object.getPrototypeOf || function (obj) { return obj.__proto__ }; function clone$1 (obj) { if (obj === null || typeof obj !== 'object') return obj if (obj instanceof Object) var copy = { __proto__: getPrototypeOf(obj) }; else var copy = Object.create(null); Object.getOwnPropertyNames(obj).forEach(function (key) { Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)); }); return copy } var fs$r = fs__default; var polyfills = polyfills$1; var legacy = legacyStreams; var clone = clone_1; var util$2 = require$$0$3; /* istanbul ignore next - node 0.x polyfill */ var gracefulQueue; var previousSymbol; /* istanbul ignore else - node 0.x polyfill */ if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { gracefulQueue = Symbol.for('graceful-fs.queue'); // This is used in testing by future versions previousSymbol = Symbol.for('graceful-fs.previous'); } else { gracefulQueue = '___graceful-fs.queue'; previousSymbol = '___graceful-fs.previous'; } function noop$2 () {} function publishQueue(context, queue) { Object.defineProperty(context, gracefulQueue, { get: function() { return queue } }); } var debug$3 = noop$2; if (util$2.debuglog) debug$3 = util$2.debuglog('gfs4'); else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) debug$3 = function() { var m = util$2.format.apply(util$2, arguments); m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: '); console.error(m); }; // Once time initialization if (!fs$r[gracefulQueue]) { // This queue can be shared by multiple loaded instances var queue$1 = commonjsGlobal[gracefulQueue] || []; publishQueue(fs$r, queue$1); // Patch fs.close/closeSync to shared queue version, because we need // to retry() whenever a close happens *anywhere* in the program. // This is essential when multiple graceful-fs instances are // in play at the same time. fs$r.close = (function (fs$close) { function close (fd, cb) { return fs$close.call(fs$r, fd, function (err) { // This function uses the graceful-fs shared queue if (!err) { resetQueue(); } if (typeof cb === 'function') cb.apply(this, arguments); }) } Object.defineProperty(close, previousSymbol, { value: fs$close }); return close })(fs$r.close); fs$r.closeSync = (function (fs$closeSync) { function closeSync (fd) { // This function uses the graceful-fs shared queue fs$closeSync.apply(fs$r, arguments); resetQueue(); } Object.defineProperty(closeSync, previousSymbol, { value: fs$closeSync }); return closeSync })(fs$r.closeSync); if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { process.on('exit', function() { debug$3(fs$r[gracefulQueue]); require$$5.equal(fs$r[gracefulQueue].length, 0); }); } } if (!commonjsGlobal[gracefulQueue]) { publishQueue(commonjsGlobal, fs$r[gracefulQueue]); } var gracefulFs = patch(clone(fs$r)); if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs$r.__patched) { gracefulFs = patch(fs$r); fs$r.__patched = true; } function patch (fs) { // Everything that references the open() function needs to be in here polyfills(fs); fs.gracefulify = patch; fs.createReadStream = createReadStream; fs.createWriteStream = createWriteStream; var fs$readFile = fs.readFile; fs.readFile = readFile; function readFile (path, options, cb) { if (typeof options === 'function') cb = options, options = null; return go$readFile(path, options, cb) function go$readFile (path, options, cb, startTime) { return fs$readFile(path, options, function (err) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]); else { if (typeof cb === 'function') cb.apply(this, arguments); } }) } } var fs$writeFile = fs.writeFile; fs.writeFile = writeFile; function writeFile (path, data, options, cb) { if (typeof options === 'function') cb = options, options = null; return go$writeFile(path, data, options, cb) function go$writeFile (path, data, options, cb, startTime) { return fs$writeFile(path, data, options, function (err) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]); else { if (typeof cb === 'function') cb.apply(this, arguments); } }) } } var fs$appendFile = fs.appendFile; if (fs$appendFile) fs.appendFile = appendFile; function appendFile (path, data, options, cb) { if (typeof options === 'function') cb = options, options = null; return go$appendFile(path, data, options, cb) function go$appendFile (path, data, options, cb, startTime) { return fs$appendFile(path, data, options, function (err) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]); else { if (typeof cb === 'function') cb.apply(this, arguments); } }) } } var fs$copyFile = fs.copyFile; if (fs$copyFile) fs.copyFile = copyFile; function copyFile (src, dest, flags, cb) { if (typeof flags === 'function') { cb = flags; flags = 0; } return go$copyFile(src, dest, flags, cb) function go$copyFile (src, dest, flags, cb, startTime) { return fs$copyFile(src, dest, flags, function (err) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]); else { if (typeof cb === 'function') cb.apply(this, arguments); } }) } } var fs$readdir = fs.readdir; fs.readdir = readdir; var noReaddirOptionVersions = /^v[0-5]\./; function readdir (path, options, cb) { if (typeof options === 'function') cb = options, options = null; var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir (path, options, cb, startTime) { return fs$readdir(path, fs$readdirCallback( path, options, cb, startTime )) } : function go$readdir (path, options, cb, startTime) { return fs$readdir(path, options, fs$readdirCallback( path, options, cb, startTime )) }; return go$readdir(path, options, cb) function fs$readdirCallback (path, options, cb, startTime) { return function (err, files) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([ go$readdir, [path, options, cb], err, startTime || Date.now(), Date.now() ]); else { if (files && files.sort) files.sort(); if (typeof cb === 'function') cb.call(this, err, files); } } } } if (process.version.substr(0, 4) === 'v0.8') { var legStreams = legacy(fs); ReadStream = legStreams.ReadStream; WriteStream = legStreams.WriteStream; } var fs$ReadStream = fs.ReadStream; if (fs$ReadStream) { ReadStream.prototype = Object.create(fs$ReadStream.prototype); ReadStream.prototype.open = ReadStream$open; } var fs$WriteStream = fs.WriteStream; if (fs$WriteStream) { WriteStream.prototype = Object.create(fs$WriteStream.prototype); WriteStream.prototype.open = WriteStream$open; } Object.defineProperty(fs, 'ReadStream', { get: function () { return ReadStream }, set: function (val) { ReadStream = val; }, enumerable: true, configurable: true }); Object.defineProperty(fs, 'WriteStream', { get: function () { return WriteStream }, set: function (val) { WriteStream = val; }, enumerable: true, configurable: true }); // legacy names var FileReadStream = ReadStream; Object.defineProperty(fs, 'FileReadStream', { get: function () { return FileReadStream }, set: function (val) { FileReadStream = val; }, enumerable: true, configurable: true }); var FileWriteStream = WriteStream; Object.defineProperty(fs, 'FileWriteStream', { get: function () { return FileWriteStream }, set: function (val) { FileWriteStream = val; }, enumerable: true, configurable: true }); function ReadStream (path, options) { if (this instanceof ReadStream) return fs$ReadStream.apply(this, arguments), this else return ReadStream.apply(Object.create(ReadStream.prototype), arguments) } function ReadStream$open () { var that = this; open(that.path, that.flags, that.mode, function (err, fd) { if (err) { if (that.autoClose) that.destroy(); that.emit('error', err); } else { that.fd = fd; that.emit('open', fd); that.read(); } }); } function WriteStream (path, options) { if (this instanceof WriteStream) return fs$WriteStream.apply(this, arguments), this else return WriteStream.apply(Object.create(WriteStream.prototype), arguments) } function WriteStream$open () { var that = this; open(that.path, that.flags, that.mode, function (err, fd) { if (err) { that.destroy(); that.emit('error', err); } else { that.fd = fd; that.emit('open', fd); } }); } function createReadStream (path, options) { return new fs.ReadStream(path, options) } function createWriteStream (path, options) { return new fs.WriteStream(path, options) } var fs$open = fs.open; fs.open = open; function open (path, flags, mode, cb) { if (typeof mode === 'function') cb = mode, mode = null; return go$open(path, flags, mode, cb) function go$open (path, flags, mode, cb, startTime) { return fs$open(path, flags, mode, function (err, fd) { if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]); else { if (typeof cb === 'function') cb.apply(this, arguments); } }) } } return fs } function enqueue (elem) { debug$3('ENQUEUE', elem[0].name, elem[1]); fs$r[gracefulQueue].push(elem); retry(); } // keep track of the timeout between retry() calls var retryTimer; // reset the startTime and lastTime to now // this resets the start of the 60 second overall timeout as well as the // delay between attempts so that we'll retry these jobs sooner function resetQueue () { var now = Date.now(); for (var i = 0; i < fs$r[gracefulQueue].length; ++i) { // entries that are only a length of 2 are from an older version, don't // bother modifying those since they'll be retried anyway. if (fs$r[gracefulQueue][i].length > 2) { fs$r[gracefulQueue][i][3] = now; // startTime fs$r[gracefulQueue][i][4] = now; // lastTime } } // call retry to make sure we're actively processing the queue retry(); } function retry () { // clear the timer and remove it to help prevent unintended concurrency clearTimeout(retryTimer); retryTimer = undefined; if (fs$r[gracefulQueue].length === 0) return var elem = fs$r[gracefulQueue].shift(); var fn = elem[0]; var args = elem[1]; // these items may be unset if they were added by an older graceful-fs var err = elem[2]; var startTime = elem[3]; var lastTime = elem[4]; // if we don't have a startTime we have no way of knowing if we've waited // long enough, so go ahead and retry this item now if (startTime === undefined) { debug$3('RETRY', fn.name, args); fn.apply(null, args); } else if (Date.now() - startTime >= 60000) { // it's been more than 60 seconds total, bail now debug$3('TIMEOUT', fn.name, args); var cb = args.pop(); if (typeof cb === 'function') cb.call(null, err); } else { // the amount of time between the last attempt and right now var sinceAttempt = Date.now() - lastTime; // the amount of time between when we first tried, and when we last tried // rounded up to at least 1 var sinceStart = Math.max(lastTime - startTime, 1); // backoff. wait longer than the total time we've been retrying, but only // up to a maximum of 100ms var desiredDelay = Math.min(sinceStart * 1.2, 100); // it's been long enough since the last retry, do it again if (sinceAttempt >= desiredDelay) { debug$3('RETRY', fn.name, args); fn.apply(null, args.concat([startTime])); } else { // if we can't do this job yet, push it to the end of the queue // and let the next iteration check again fs$r[gracefulQueue].push(elem); } } // schedule our next run if one isn't already scheduled if (retryTimer === undefined) { retryTimer = setTimeout(retry, 0); } } (function (exports) { // This is adapted from https://github.com/normalize/mz // Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors const u = universalify$1.fromCallback; const fs = gracefulFs; const api = [ 'access', 'appendFile', 'chmod', 'chown', 'close', 'copyFile', 'fchmod', 'fchown', 'fdatasync', 'fstat', 'fsync', 'ftruncate', 'futimes', 'lchmod', 'lchown', 'link', 'lstat', 'mkdir', 'mkdtemp', 'open', 'opendir', 'readdir', 'readFile', 'readlink', 'realpath', 'rename', 'rm', 'rmdir', 'stat', 'symlink', 'truncate', 'unlink', 'utimes', 'writeFile' ].filter(key => { // Some commands are not available on some systems. Ex: // fs.cp was added in Node.js v16.7.0 // fs.lchown is not available on at least some Linux return typeof fs[key] === 'function' }); // Export cloned fs: Object.assign(exports, fs); // Universalify async methods: api.forEach(method => { exports[method] = u(fs[method]); }); // We differ from mz/fs in that we still ship the old, broken, fs.exists() // since we are a drop-in replacement for the native module exports.exists = function (filename, callback) { if (typeof callback === 'function') { return fs.exists(filename, callback) } return new Promise(resolve => { return fs.exists(filename, resolve) }) }; // fs.read(), fs.write(), fs.readv(), & fs.writev() need special treatment due to multiple callback args exports.read = function (fd, buffer, offset, length, position, callback) { if (typeof callback === 'function') { return fs.read(fd, buffer, offset, length, position, callback) } return new Promise((resolve, reject) => { fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => { if (err) return reject(err) resolve({ bytesRead, buffer }); }); }) }; // Function signature can be // fs.write(fd, buffer[, offset[, length[, position]]], callback) // OR // fs.write(fd, string[, position[, encoding]], callback) // We need to handle both cases, so we use ...args exports.write = function (fd, buffer, ...args) { if (typeof args[args.length - 1] === 'function') { return fs.write(fd, buffer, ...args) } return new Promise((resolve, reject) => { fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => { if (err) return reject(err) resolve({ bytesWritten, buffer }); }); }) }; // Function signature is // s.readv(fd, buffers[, position], callback) // We need to handle the optional arg, so we use ...args exports.readv = function (fd, buffers, ...args) { if (typeof args[args.length - 1] === 'function') { return fs.readv(fd, buffers, ...args) } return new Promise((resolve, reject) => { fs.readv(fd, buffers, ...args, (err, bytesRead, buffers) => { if (err) return reject(err) resolve({ bytesRead, buffers }); }); }) }; // Function signature is // s.writev(fd, buffers[, position], callback) // We need to handle the optional arg, so we use ...args exports.writev = function (fd, buffers, ...args) { if (typeof args[args.length - 1] === 'function') { return fs.writev(fd, buffers, ...args) } return new Promise((resolve, reject) => { fs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => { if (err) return reject(err) resolve({ bytesWritten, buffers }); }); }) }; // fs.realpath.native sometimes not available if fs is monkey-patched if (typeof fs.realpath.native === 'function') { exports.realpath.native = u(fs.realpath.native); } else { process.emitWarning( 'fs.realpath.native is not a function. Is fs being monkey-patched?', 'Warning', 'fs-extra-WARN0003' ); } } (fs$s)); var makeDir$1 = {}; var utils$u = {}; const path$p = path$q; // https://github.com/nodejs/node/issues/8987 // https://github.com/libuv/libuv/pull/1088 utils$u.checkPath = function checkPath (pth) { if (process.platform === 'win32') { const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path$p.parse(pth).root, '')); if (pathHasInvalidWinCharacters) { const error = new Error(`Path contains invalid characters: ${pth}`); error.code = 'EINVAL'; throw error } } }; const fs$q = fs$s; const { checkPath } = utils$u; const getMode = options => { const defaults = { mode: 0o777 }; if (typeof options === 'number') return options return ({ ...defaults, ...options }).mode }; makeDir$1.makeDir = async (dir, options) => { checkPath(dir); return fs$q.mkdir(dir, { mode: getMode(options), recursive: true }) }; makeDir$1.makeDirSync = (dir, options) => { checkPath(dir); return fs$q.mkdirSync(dir, { mode: getMode(options), recursive: true }) }; const u$f = universalify$1.fromPromise; const { makeDir: _makeDir, makeDirSync } = makeDir$1; const makeDir = u$f(_makeDir); var mkdirs$2 = { mkdirs: makeDir, mkdirsSync: makeDirSync, // alias mkdirp: makeDir, mkdirpSync: makeDirSync, ensureDir: makeDir, ensureDirSync: makeDirSync }; const u$e = universalify$1.fromPromise; const fs$p = fs$s; function pathExists$6 (path) { return fs$p.access(path).then(() => true).catch(() => false) } var pathExists_1 = { pathExists: u$e(pathExists$6), pathExistsSync: fs$p.existsSync }; const fs$o = fs$s; const u$d = universalify$1.fromPromise; async function utimesMillis$1 (path, atime, mtime) { // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback) const fd = await fs$o.open(path, 'r+'); let closeErr = null; try { await fs$o.futimes(fd, atime, mtime); } finally { try { await fs$o.close(fd); } catch (e) { closeErr = e; } } if (closeErr) { throw closeErr } } function utimesMillisSync$1 (path, atime, mtime) { const fd = fs$o.openSync(path, 'r+'); fs$o.futimesSync(fd, atime, mtime); return fs$o.closeSync(fd) } var utimes = { utimesMillis: u$d(utimesMillis$1), utimesMillisSync: utimesMillisSync$1 }; const fs$n = fs$s; const path$o = path$q; const u$c = universalify$1.fromPromise; function getStats$1 (src, dest, opts) { const statFunc = opts.dereference ? (file) => fs$n.stat(file, { bigint: true }) : (file) => fs$n.lstat(file, { bigint: true }); return Promise.all([ statFunc(src), statFunc(dest).catch(err => { if (err.code === 'ENOENT') return null throw err }) ]).then(([srcStat, destStat]) => ({ srcStat, destStat })) } function getStatsSync (src, dest, opts) { let destStat; const statFunc = opts.dereference ? (file) => fs$n.statSync(file, { bigint: true }) : (file) => fs$n.lstatSync(file, { bigint: true }); const srcStat = statFunc(src); try { destStat = statFunc(dest); } catch (err) { if (err.code === 'ENOENT') return { srcStat, destStat: null } throw err } return { srcStat, destStat } } async function checkPaths (src, dest, funcName, opts) { const { srcStat, destStat } = await getStats$1(src, dest, opts); if (destStat) { if (areIdentical$2(srcStat, destStat)) { const srcBaseName = path$o.basename(src); const destBaseName = path$o.basename(dest); if (funcName === 'move' && srcBaseName !== destBaseName && srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { return { srcStat, destStat, isChangingCase: true } } throw new Error('Source and destination must not be the same.') } if (srcStat.isDirectory() && !destStat.isDirectory()) { throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) } if (!srcStat.isDirectory() && destStat.isDirectory()) { throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`) } } if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { throw new Error(errMsg(src, dest, funcName)) } return { srcStat, destStat } } function checkPathsSync (src, dest, funcName, opts) { const { srcStat, destStat } = getStatsSync(src, dest, opts); if (destStat) { if (areIdentical$2(srcStat, destStat)) { const srcBaseName = path$o.basename(src); const destBaseName = path$o.basename(dest); if (funcName === 'move' && srcBaseName !== destBaseName && srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { return { srcStat, destStat, isChangingCase: true } } throw new Error('Source and destination must not be the same.') } if (srcStat.isDirectory() && !destStat.isDirectory()) { throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) } if (!srcStat.isDirectory() && destStat.isDirectory()) { throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`) } } if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { throw new Error(errMsg(src, dest, funcName)) } return { srcStat, destStat } } // recursively check if dest parent is a subdirectory of src. // It works for all file types including symlinks since it // checks the src and dest inodes. It starts from the deepest // parent and stops once it reaches the src parent or the root path. async function checkParentPaths (src, srcStat, dest, funcName) { const srcParent = path$o.resolve(path$o.dirname(src)); const destParent = path$o.resolve(path$o.dirname(dest)); if (destParent === srcParent || destParent === path$o.parse(destParent).root) return let destStat; try { destStat = await fs$n.stat(destParent, { bigint: true }); } catch (err) { if (err.code === 'ENOENT') return throw err } if (areIdentical$2(srcStat, destStat)) { throw new Error(errMsg(src, dest, funcName)) } return checkParentPaths(src, srcStat, destParent, funcName) } function checkParentPathsSync (src, srcStat, dest, funcName) { const srcParent = path$o.resolve(path$o.dirname(src)); const destParent = path$o.resolve(path$o.dirname(dest)); if (destParent === srcParent || destParent === path$o.parse(destParent).root) return let destStat; try { destStat = fs$n.statSync(destParent, { bigint: true }); } catch (err) { if (err.code === 'ENOENT') return throw err } if (areIdentical$2(srcStat, destStat)) { throw new Error(errMsg(src, dest, funcName)) } return checkParentPathsSync(src, srcStat, destParent, funcName) } function areIdentical$2 (srcStat, destStat) { return destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev } // return true if dest is a subdir of src, otherwise false. // It only checks the path strings. function isSrcSubdir (src, dest) { const srcArr = path$o.resolve(src).split(path$o.sep).filter(i => i); const destArr = path$o.resolve(dest).split(path$o.sep).filter(i => i); return srcArr.every((cur, i) => destArr[i] === cur) } function errMsg (src, dest, funcName) { return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.` } var stat$7 = { // checkPaths checkPaths: u$c(checkPaths), checkPathsSync, // checkParent checkParentPaths: u$c(checkParentPaths), checkParentPathsSync, // Misc isSrcSubdir, areIdentical: areIdentical$2 }; const fs$m = fs$s; const path$n = path$q; const { mkdirs: mkdirs$1 } = mkdirs$2; const { pathExists: pathExists$5 } = pathExists_1; const { utimesMillis } = utimes; const stat$6 = stat$7; async function copy$2 (src, dest, opts = {}) { if (typeof opts === 'function') { opts = { filter: opts }; } opts.clobber = 'clobber' in opts ? !!opts.clobber : true; // default to true for now opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber; // overwrite falls back to clobber // Warn about using preserveTimestamps on 32-bit node if (opts.preserveTimestamps && process.arch === 'ia32') { process.emitWarning( 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' + '\tsee https://github.com/jprichardson/node-fs-extra/issues/269', 'Warning', 'fs-extra-WARN0001' ); } const { srcStat, destStat } = await stat$6.checkPaths(src, dest, 'copy', opts); await stat$6.checkParentPaths(src, srcStat, dest, 'copy'); const include = await runFilter(src, dest, opts); if (!include) return // check if the parent of dest exists, and create it if it doesn't exist const destParent = path$n.dirname(dest); const dirExists = await pathExists$5(destParent); if (!dirExists) { await mkdirs$1(destParent); } await getStatsAndPerformCopy(destStat, src, dest, opts); } async function runFilter (src, dest, opts) { if (!opts.filter) return true return opts.filter(src, dest) } async function getStatsAndPerformCopy (destStat, src, dest, opts) { const statFn = opts.dereference ? fs$m.stat : fs$m.lstat; const srcStat = await statFn(src); if (srcStat.isDirectory()) return onDir$1(srcStat, destStat, src, dest, opts) if ( srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice() ) return onFile$1(srcStat, destStat, src, dest, opts) if (srcStat.isSymbolicLink()) return onLink$1(destStat, src, dest, opts) if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`) if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`) throw new Error(`Unknown file: ${src}`) } async function onFile$1 (srcStat, destStat, src, dest, opts) { if (!destStat) return copyFile$1(srcStat, src, dest, opts) if (opts.overwrite) { await fs$m.unlink(dest); return copyFile$1(srcStat, src, dest, opts) } if (opts.errorOnExist) { throw new Error(`'${dest}' already exists`) } } async function copyFile$1 (srcStat, src, dest, opts) { await fs$m.copyFile(src, dest); if (opts.preserveTimestamps) { // Make sure the file is writable before setting the timestamp // otherwise open fails with EPERM when invoked with 'r+' // (through utimes call) if (fileIsNotWritable$1(srcStat.mode)) { await makeFileWritable$1(dest, srcStat.mode); } // Set timestamps and mode correspondingly // Note that The initial srcStat.atime cannot be trusted // because it is modified by the read(2) system call // (See https://nodejs.org/api/fs.html#fs_stat_time_values) const updatedSrcStat = await fs$m.stat(src); await utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime); } return fs$m.chmod(dest, srcStat.mode) } function fileIsNotWritable$1 (srcMode) { return (srcMode & 0o200) === 0 } function makeFileWritable$1 (dest, srcMode) { return fs$m.chmod(dest, srcMode | 0o200) } async function onDir$1 (srcStat, destStat, src, dest, opts) { // the dest directory might not exist, create it if (!destStat) { await fs$m.mkdir(dest); } const items = await fs$m.readdir(src); // loop through the files in the current directory to copy everything await Promise.all(items.map(async item => { const srcItem = path$n.join(src, item); const destItem = path$n.join(dest, item); // skip the item if it is matches by the filter function const include = await runFilter(srcItem, destItem, opts); if (!include) return const { destStat } = await stat$6.checkPaths(srcItem, destItem, 'copy', opts); // If the item is a copyable file, `getStatsAndPerformCopy` will copy it // If the item is a directory, `getStatsAndPerformCopy` will call `onDir` recursively return getStatsAndPerformCopy(destStat, srcItem, destItem, opts) })); if (!destStat) { await fs$m.chmod(dest, srcStat.mode); } } async function onLink$1 (destStat, src, dest, opts) { let resolvedSrc = await fs$m.readlink(src); if (opts.dereference) { resolvedSrc = path$n.resolve(process.cwd(), resolvedSrc); } if (!destStat) { return fs$m.symlink(resolvedSrc, dest) } let resolvedDest = null; try { resolvedDest = await fs$m.readlink(dest); } catch (e) { // dest exists and is a regular file or directory, // Windows may throw UNKNOWN error. If dest already exists, // fs throws error anyway, so no need to guard against it here. if (e.code === 'EINVAL' || e.code === 'UNKNOWN') return fs$m.symlink(resolvedSrc, dest) throw e } if (opts.dereference) { resolvedDest = path$n.resolve(process.cwd(), resolvedDest); } if (stat$6.isSrcSubdir(resolvedSrc, resolvedDest)) { throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`) } // do not copy if src is a subdir of dest since unlinking // dest in this case would result in removing src contents // and therefore a broken symlink would be created. if (stat$6.isSrcSubdir(resolvedDest, resolvedSrc)) { throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`) } // copy the link await fs$m.unlink(dest); return fs$m.symlink(resolvedSrc, dest) } var copy_1 = copy$2; const fs$l = gracefulFs; const path$m = path$q; const mkdirsSync$1 = mkdirs$2.mkdirsSync; const utimesMillisSync = utimes.utimesMillisSync; const stat$5 = stat$7; function copySync$1 (src, dest, opts) { if (typeof opts === 'function') { opts = { filter: opts }; } opts = opts || {}; opts.clobber = 'clobber' in opts ? !!opts.clobber : true; // default to true for now opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber; // overwrite falls back to clobber // Warn about using preserveTimestamps on 32-bit node if (opts.preserveTimestamps && process.arch === 'ia32') { process.emitWarning( 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' + '\tsee https://github.com/jprichardson/node-fs-extra/issues/269', 'Warning', 'fs-extra-WARN0002' ); } const { srcStat, destStat } = stat$5.checkPathsSync(src, dest, 'copy', opts); stat$5.checkParentPathsSync(src, srcStat, dest, 'copy'); if (opts.filter && !opts.filter(src, dest)) return const destParent = path$m.dirname(dest); if (!fs$l.existsSync(destParent)) mkdirsSync$1(destParent); return getStats(destStat, src, dest, opts) } function getStats (destStat, src, dest, opts) { const statSync = opts.dereference ? fs$l.statSync : fs$l.lstatSync; const srcStat = statSync(src); if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts) else if (srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts) else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts) else if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`) else if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`) throw new Error(`Unknown file: ${src}`) } function onFile (srcStat, destStat, src, dest, opts) { if (!destStat) return copyFile(srcStat, src, dest, opts) return mayCopyFile(srcStat, src, dest, opts) } function mayCopyFile (srcStat, src, dest, opts) { if (opts.overwrite) { fs$l.unlinkSync(dest); return copyFile(srcStat, src, dest, opts) } else if (opts.errorOnExist) { throw new Error(`'${dest}' already exists`) } } function copyFile (srcStat, src, dest, opts) { fs$l.copyFileSync(src, dest); if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest); return setDestMode(dest, srcStat.mode) } function handleTimestamps (srcMode, src, dest) { // Make sure the file is writable before setting the timestamp // otherwise open fails with EPERM when invoked with 'r+' // (through utimes call) if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode); return setDestTimestamps(src, dest) } function fileIsNotWritable (srcMode) { return (srcMode & 0o200) === 0 } function makeFileWritabl