Commit 4e362378 authored by Rosanny Sihombing's avatar Rosanny Sihombing
Browse files

Merge branch 'MLAB-671' into 'testing'

Mlab 671

See merge request !158
parents 3d0c87b0 bde9ccfd
Pipeline #6646 passed with stage
in 11 seconds
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformFileSync = exports.transformFileAsync = exports.transformFile = void 0;
function _gensync() {
const data = require("gensync");
_gensync = function () {
return data;
};
return data;
}
var _config = require("./config");
var _transformation = require("./transformation");
var fs = require("./gensync-utils/fs");
({});
const transformFileRunner = _gensync()(function* (filename, opts) {
const options = Object.assign({}, opts, {
filename
});
const config = yield* (0, _config.default)(options);
if (config === null) return null;
const code = yield* fs.readFile(filename, "utf8");
return yield* (0, _transformation.run)(config, code);
});
const transformFile = transformFileRunner.errback;
exports.transformFile = transformFile;
const transformFileSync = transformFileRunner.sync;
exports.transformFileSync = transformFileSync;
const transformFileAsync = transformFileRunner.async;
exports.transformFileAsync = transformFileAsync;
0 && 0;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transformSync = exports.transformAsync = exports.transform = void 0;
function _gensync() {
const data = require("gensync");
_gensync = function () {
return data;
};
return data;
}
var _config = require("./config");
var _transformation = require("./transformation");
const transformRunner = _gensync()(function* transform(code, opts) {
const config = yield* (0, _config.default)(opts);
if (config === null) return null;
return yield* (0, _transformation.run)(config, code);
});
const transform = function transform(code, optsOrCallback, maybeCallback) {
let opts;
let callback;
if (typeof optsOrCallback === "function") {
callback = optsOrCallback;
opts = undefined;
} else {
opts = optsOrCallback;
callback = maybeCallback;
}
if (callback === undefined) {
{
return transformRunner.sync(code, opts);
}
}
transformRunner.errback(code, opts, callback);
};
exports.transform = transform;
const transformSync = transformRunner.sync;
exports.transformSync = transformSync;
const transformAsync = transformRunner.async;
exports.transformAsync = transformAsync;
0 && 0;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = loadBlockHoistPlugin;
function _traverse() {
const data = require("@babel/traverse");
_traverse = function () {
return data;
};
return data;
}
var _plugin = require("../config/plugin");
let LOADED_PLUGIN;
function loadBlockHoistPlugin() {
if (!LOADED_PLUGIN) {
LOADED_PLUGIN = new _plugin.default(Object.assign({}, blockHoistPlugin, {
visitor: _traverse().default.explode(blockHoistPlugin.visitor)
}), {});
}
return LOADED_PLUGIN;
}
function priority(bodyNode) {
const priority = bodyNode == null ? void 0 : bodyNode._blockHoist;
if (priority == null) return 1;
if (priority === true) return 2;
return priority;
}
function stableSort(body) {
const buckets = Object.create(null);
for (let i = 0; i < body.length; i++) {
const n = body[i];
const p = priority(n);
const bucket = buckets[p] || (buckets[p] = []);
bucket.push(n);
}
const keys = Object.keys(buckets).map(k => +k).sort((a, b) => b - a);
let index = 0;
for (const key of keys) {
const bucket = buckets[key];
for (const n of bucket) {
body[index++] = n;
}
}
return body;
}
const blockHoistPlugin = {
name: "internal.blockHoist",
visitor: {
Block: {
exit({
node
}) {
const {
body
} = node;
let max = Math.pow(2, 30) - 1;
let hasChange = false;
for (let i = 0; i < body.length; i++) {
const n = body[i];
const p = priority(n);
if (p > max) {
hasChange = true;
break;
}
max = p;
}
if (!hasChange) return;
node.body = stableSort(body.slice());
}
}
}
};
0 && 0;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function helpers() {
const data = require("@babel/helpers");
helpers = function () {
return data;
};
return data;
}
function _traverse() {
const data = require("@babel/traverse");
_traverse = function () {
return data;
};
return data;
}
function _codeFrame() {
const data = require("@babel/code-frame");
_codeFrame = function () {
return data;
};
return data;
}
function _t() {
const data = require("@babel/types");
_t = function () {
return data;
};
return data;
}
function _helperModuleTransforms() {
const data = require("@babel/helper-module-transforms");
_helperModuleTransforms = function () {
return data;
};
return data;
}
function _semver() {
const data = require("semver");
_semver = function () {
return data;
};
return data;
}
const {
cloneNode,
interpreterDirective
} = _t();
const errorVisitor = {
enter(path, state) {
const loc = path.node.loc;
if (loc) {
state.loc = loc;
path.stop();
}
}
};
class File {
constructor(options, {
code,
ast,
inputMap
}) {
this._map = new Map();
this.opts = void 0;
this.declarations = {};
this.path = void 0;
this.ast = void 0;
this.scope = void 0;
this.metadata = {};
this.code = "";
this.inputMap = void 0;
this.hub = {
file: this,
getCode: () => this.code,
getScope: () => this.scope,
addHelper: this.addHelper.bind(this),
buildError: this.buildCodeFrameError.bind(this)
};
this.opts = options;
this.code = code;
this.ast = ast;
this.inputMap = inputMap;
this.path = _traverse().NodePath.get({
hub: this.hub,
parentPath: null,
parent: this.ast,
container: this.ast,
key: "program"
}).setContext();
this.scope = this.path.scope;
}
get shebang() {
const {
interpreter
} = this.path.node;
return interpreter ? interpreter.value : "";
}
set shebang(value) {
if (value) {
this.path.get("interpreter").replaceWith(interpreterDirective(value));
} else {
this.path.get("interpreter").remove();
}
}
set(key, val) {
if (key === "helpersNamespace") {
throw new Error("Babel 7.0.0-beta.56 has dropped support for the 'helpersNamespace' utility." + "If you are using @babel/plugin-external-helpers you will need to use a newer " + "version than the one you currently have installed. " + "If you have your own implementation, you'll want to explore using 'helperGenerator' " + "alongside 'file.availableHelper()'.");
}
this._map.set(key, val);
}
get(key) {
return this._map.get(key);
}
has(key) {
return this._map.has(key);
}
getModuleName() {
return (0, _helperModuleTransforms().getModuleName)(this.opts, this.opts);
}
addImport() {
throw new Error("This API has been removed. If you're looking for this " + "functionality in Babel 7, you should import the " + "'@babel/helper-module-imports' module and use the functions exposed " + " from that module, such as 'addNamed' or 'addDefault'.");
}
availableHelper(name, versionRange) {
let minVersion;
try {
minVersion = helpers().minVersion(name);
} catch (err) {
if (err.code !== "BABEL_HELPER_UNKNOWN") throw err;
return false;
}
if (typeof versionRange !== "string") return true;
if (_semver().valid(versionRange)) versionRange = `^${versionRange}`;
return !_semver().intersects(`<${minVersion}`, versionRange) && !_semver().intersects(`>=8.0.0`, versionRange);
}
addHelper(name) {
const declar = this.declarations[name];
if (declar) return cloneNode(declar);
const generator = this.get("helperGenerator");
if (generator) {
const res = generator(name);
if (res) return res;
}
helpers().ensure(name, File);
const uid = this.declarations[name] = this.scope.generateUidIdentifier(name);
const dependencies = {};
for (const dep of helpers().getDependencies(name)) {
dependencies[dep] = this.addHelper(dep);
}
const {
nodes,
globals
} = helpers().get(name, dep => dependencies[dep], uid, Object.keys(this.scope.getAllBindings()));
globals.forEach(name => {
if (this.path.scope.hasBinding(name, true)) {
this.path.scope.rename(name);
}
});
nodes.forEach(node => {
node._compact = true;
});
this.path.unshiftContainer("body", nodes);
this.path.get("body").forEach(path => {
if (nodes.indexOf(path.node) === -1) return;
if (path.isVariableDeclaration()) this.scope.registerDeclaration(path);
});
return uid;
}
addTemplateObject() {
throw new Error("This function has been moved into the template literal transform itself.");
}
buildCodeFrameError(node, msg, _Error = SyntaxError) {
let loc = node && (node.loc || node._loc);
if (!loc && node) {
const state = {
loc: null
};
(0, _traverse().default)(node, errorVisitor, this.scope, state);
loc = state.loc;
let txt = "This is an error on an internal node. Probably an internal error.";
if (loc) txt += " Location has been estimated.";
msg += ` (${txt})`;
}
if (loc) {
const {
highlightCode = true
} = this.opts;
msg += "\n" + (0, _codeFrame().codeFrameColumns)(this.code, {
start: {
line: loc.start.line,
column: loc.start.column + 1
},
end: loc.end && loc.start.line === loc.end.line ? {
line: loc.end.line,
column: loc.end.column + 1
} : undefined
}, {
highlightCode
});
}
return new _Error(msg);
}
}
exports.default = File;
0 && 0;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = generateCode;
function _convertSourceMap() {
const data = require("convert-source-map");
_convertSourceMap = function () {
return data;
};
return data;
}
function _generator() {
const data = require("@babel/generator");
_generator = function () {
return data;
};
return data;
}
var _mergeMap = require("./merge-map");
function generateCode(pluginPasses, file) {
const {
opts,
ast,
code,
inputMap
} = file;
const {
generatorOpts
} = opts;
const results = [];
for (const plugins of pluginPasses) {
for (const plugin of plugins) {
const {
generatorOverride
} = plugin;
if (generatorOverride) {
const result = generatorOverride(ast, generatorOpts, code, _generator().default);
if (result !== undefined) results.push(result);
}
}
}
let result;
if (results.length === 0) {
result = (0, _generator().default)(ast, generatorOpts, code);
} else if (results.length === 1) {
result = results[0];
if (typeof result.then === "function") {
throw new Error(`You appear to be using an async codegen plugin, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, ` + `you may need to upgrade your @babel/core version.`);
}
} else {
throw new Error("More than one plugin attempted to override codegen.");
}
let {
code: outputCode,
decodedMap: outputMap = result.map
} = result;
if (outputMap) {
if (inputMap) {
outputMap = (0, _mergeMap.default)(inputMap.toObject(), outputMap, generatorOpts.sourceFileName);
} else {
outputMap = result.map;
}
}
if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") {
outputCode += "\n" + _convertSourceMap().fromObject(outputMap).toComment();
}
if (opts.sourceMaps === "inline") {
outputMap = null;
}
return {
outputCode,
outputMap
};
}
0 && 0;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = mergeSourceMap;
function _remapping() {
const data = require("@ampproject/remapping");
_remapping = function () {
return data;
};
return data;
}
function mergeSourceMap(inputMap, map, sourceFileName) {
const source = sourceFileName.replace(/\\/g, "/");
let found = false;
const result = _remapping()(rootless(map), (s, ctx) => {
if (s === source && !found) {
found = true;
ctx.source = "";
return rootless(inputMap);
}
return null;
});
if (typeof inputMap.sourceRoot === "string") {
result.sourceRoot = inputMap.sourceRoot;
}
return Object.assign({}, result);
}
function rootless(map) {
return Object.assign({}, map, {
sourceRoot: null
});
}
0 && 0;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = run;
function _traverse() {
const data = require("@babel/traverse");
_traverse = function () {
return data;
};
return data;
}
var _pluginPass = require("./plugin-pass");
var _blockHoistPlugin = require("./block-hoist-plugin");
var _normalizeOpts = require("./normalize-opts");
var _normalizeFile = require("./normalize-file");
var _generate = require("./file/generate");
var _deepArray = require("../config/helpers/deep-array");
function* run(config, code, ast) {
const file = yield* (0, _normalizeFile.default)(config.passes, (0, _normalizeOpts.default)(config), code, ast);
const opts = file.opts;
try {
yield* transformFile(file, config.passes);
} catch (e) {
var _opts$filename;
e.message = `${(_opts$filename = opts.filename) != null ? _opts$filename : "unknown"}: ${e.message}`;
if (!e.code) {
e.code = "BABEL_TRANSFORM_ERROR";
}
throw e;
}
let outputCode, outputMap;
try {
if (opts.code !== false) {
({
outputCode,
outputMap
} = (0, _generate.default)(config.passes, file));
}
} catch (e) {
var _opts$filename2;
e.message = `${(_opts$filename2 = opts.filename) != null ? _opts$filename2 : "unknown"}: ${e.message}`;
if (!e.code) {
e.code = "BABEL_GENERATE_ERROR";
}
throw e;
}
return {
metadata: file.metadata,
options: opts,
ast: opts.ast === true ? file.ast : null,
code: outputCode === undefined ? null : outputCode,
map: outputMap === undefined ? null : outputMap,
sourceType: file.ast.program.sourceType,
externalDependencies: (0, _deepArray.flattenToSet)(config.externalDependencies)
};
}
function* transformFile(file, pluginPasses) {
for (const pluginPairs of pluginPasses) {
const passPairs = [];
const passes = [];
const visitors = [];
for (const plugin of pluginPairs.concat([(0, _blockHoistPlugin.default)()])) {
const pass = new _pluginPass.default(file, plugin.key, plugin.options);
passPairs.push([plugin, pass]);
passes.push(pass);
visitors.push(plugin.visitor);
}
for (const [plugin, pass] of passPairs) {
const fn = plugin.pre;
if (fn) {
const result = fn.call(pass, file);
yield* [];
if (isThenable(result)) {
throw new Error(`You appear to be using an plugin with an async .pre, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`);
}
}
}
const visitor = _traverse().default.visitors.merge(visitors, passes, file.opts.wrapPluginVisitorMethod);
(0, _traverse().default)(file.ast, visitor, file.scope);
for (const [plugin, pass] of passPairs) {
const fn = plugin.post;
if (fn) {
const result = fn.call(pass, file);
yield* [];
if (isThenable(result)) {
throw new Error(`You appear to be using an plugin with an async .post, ` + `which your current version of Babel does not support. ` + `If you're using a published plugin, you may need to upgrade ` + `your @babel/core version.`);
}
}
}
}
}
function isThenable(val) {
return !!val && (typeof val === "object" || typeof val === "function") && !!val.then && typeof val.then === "function";
}
0 && 0;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = normalizeFile;
function _fs() {
const data = require("fs");
_fs = function () {
return data;
};
return data;
}
function _path() {
const data = require("path");
_path = function () {
return data;
};
return data;
}
function _debug() {
const data = require("debug");
_debug = function () {
return data;
};
return data;
}
function _t() {
const data = require("@babel/types");
_t = function () {
return data;
};
return data;
}
function _convertSourceMap() {
const data = require("convert-source-map");
_convertSourceMap = function () {
return data;
};
return data;
}
var _file = require("./file/file");
var _parser = require("../parser");
var _cloneDeep = require("./util/clone-deep");
const {
file,
traverseFast
} = _t();
const debug = _debug()("babel:transform:file");
const LARGE_INPUT_SOURCEMAP_THRESHOLD = 3000000;
function* normalizeFile(pluginPasses, options, code, ast) {
code = `${code || ""}`;
if (ast) {
if (ast.type === "Program") {
ast = file(ast, [], []);
} else if (ast.type !== "File") {
throw new Error("AST root must be a Program or File node");
}
if (options.cloneInputAst) {
ast = (0, _cloneDeep.default)(ast);
}
} else {
ast = yield* (0, _parser.default)(pluginPasses, options, code);
}
let inputMap = null;
if (options.inputSourceMap !== false) {
if (typeof options.inputSourceMap === "object") {
inputMap = _convertSourceMap().fromObject(options.inputSourceMap);
}
if (!inputMap) {
const lastComment = extractComments(INLINE_SOURCEMAP_REGEX, ast);
if (lastComment) {
try {
inputMap = _convertSourceMap().fromComment(lastComment);
} catch (err) {
debug("discarding unknown inline input sourcemap", err);
}
}
}
if (!inputMap) {
const lastComment = extractComments(EXTERNAL_SOURCEMAP_REGEX, ast);
if (typeof options.filename === "string" && lastComment) {
try {
const match = EXTERNAL_SOURCEMAP_REGEX.exec(lastComment);
const inputMapContent = _fs().readFileSync(_path().resolve(_path().dirname(options.filename), match[1]));
if (inputMapContent.length > LARGE_INPUT_SOURCEMAP_THRESHOLD) {
debug("skip merging input map > 1 MB");
} else {
inputMap = _convertSourceMap().fromJSON(inputMapContent);
}
} catch (err) {
debug("discarding unknown file input sourcemap", err);
}
} else if (lastComment) {
debug("discarding un-loadable file input sourcemap");
}
}
}
return new _file.default(options, {
code,
ast,
inputMap
});
}
const INLINE_SOURCEMAP_REGEX = /^[@#]\s+sourceMappingURL=data:(?:application|text)\/json;(?:charset[:=]\S+?;)?base64,(?:.*)$/;
const EXTERNAL_SOURCEMAP_REGEX = /^[@#][ \t]+sourceMappingURL=([^\s'"`]+)[ \t]*$/;
function extractCommentsFromList(regex, comments, lastComment) {
if (comments) {
comments = comments.filter(({
value
}) => {
if (regex.test(value)) {
lastComment = value;
return false;
}
return true;
});
}
return [comments, lastComment];
}
function extractComments(regex, ast) {
let lastComment = null;
traverseFast(ast, node => {
[node.leadingComments, lastComment] = extractCommentsFromList(regex, node.leadingComments, lastComment);
[node.innerComments, lastComment] = extractCommentsFromList(regex, node.innerComments, lastComment);
[node.trailingComments, lastComment] = extractCommentsFromList(regex, node.trailingComments, lastComment);
});
return lastComment;
}
0 && 0;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = normalizeOptions;
function _path() {
const data = require("path");
_path = function () {
return data;
};
return data;
}
function normalizeOptions(config) {
const {
filename,
cwd,
filenameRelative = typeof filename === "string" ? _path().relative(cwd, filename) : "unknown",
sourceType = "module",
inputSourceMap,
sourceMaps = !!inputSourceMap,
sourceRoot = config.options.moduleRoot,
sourceFileName = _path().basename(filenameRelative),
comments = true,
compact = "auto"
} = config.options;
const opts = config.options;
const options = Object.assign({}, opts, {
parserOpts: Object.assign({
sourceType: _path().extname(filenameRelative) === ".mjs" ? "module" : sourceType,
sourceFileName: filename,
plugins: []
}, opts.parserOpts),
generatorOpts: Object.assign({
filename,
auxiliaryCommentBefore: opts.auxiliaryCommentBefore,
auxiliaryCommentAfter: opts.auxiliaryCommentAfter,
retainLines: opts.retainLines,
comments,
shouldPrintComment: opts.shouldPrintComment,
compact,
minified: opts.minified,
sourceMaps,
sourceRoot,
sourceFileName
}, opts.generatorOpts)
});
for (const plugins of config.passes) {
for (const plugin of plugins) {
if (plugin.manipulateOptions) {
plugin.manipulateOptions(options, options.parserOpts);
}
}
}
return options;
}
0 && 0;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
class PluginPass {
constructor(file, key, options) {
this._map = new Map();
this.key = void 0;
this.file = void 0;
this.opts = void 0;
this.cwd = void 0;
this.filename = void 0;
this.key = key;
this.file = file;
this.opts = options || {};
this.cwd = file.opts.cwd;
this.filename = file.opts.filename;
}
set(key, val) {
this._map.set(key, val);
}
get(key) {
return this._map.get(key);
}
availableHelper(name, versionRange) {
return this.file.availableHelper(name, versionRange);
}
addHelper(name) {
return this.file.addHelper(name);
}
addImport() {
return this.file.addImport();
}
buildCodeFrameError(node, msg, _Error) {
return this.file.buildCodeFrameError(node, msg, _Error);
}
}
exports.default = PluginPass;
{
PluginPass.prototype.getModuleName = function getModuleName() {
return this.file.getModuleName();
};
}
0 && 0;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _default;
function deepClone(value, cache) {
if (value !== null) {
if (cache.has(value)) return cache.get(value);
let cloned;
if (Array.isArray(value)) {
cloned = new Array(value.length);
for (let i = 0; i < value.length; i++) {
cloned[i] = typeof value[i] !== "object" ? value[i] : deepClone(value[i], cache);
}
} else {
cloned = {};
const keys = Object.keys(value);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
cloned[key] = typeof value[key] !== "object" ? value[key] : deepClone(value[key], cache);
}
}
cache.set(value, cloned);
return cloned;
}
return value;
}
function _default(value) {
if (typeof value !== "object") return value;
return deepClone(value, new Map());
}
0 && 0;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.moduleResolve = moduleResolve;
exports.resolve = resolve;
function _url() {
const data = require("url");
_url = function () {
return data;
};
return data;
}
function _fs() {
const data = _interopRequireWildcard(require("fs"), true);
_fs = function () {
return data;
};
return data;
}
function _path() {
const data = require("path");
_path = function () {
return data;
};
return data;
}
function _assert() {
const data = require("assert");
_assert = function () {
return data;
};
return data;
}
function _util() {
const data = require("util");
_util = function () {
return data;
};
return data;
}
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
var re$3 = {
exports: {}
};
const SEMVER_SPEC_VERSION = '2.0.0';
const MAX_LENGTH$2 = 256;
const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER || 9007199254740991;
const MAX_SAFE_COMPONENT_LENGTH = 16;
var constants = {
SEMVER_SPEC_VERSION,
MAX_LENGTH: MAX_LENGTH$2,
MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1,
MAX_SAFE_COMPONENT_LENGTH
};
const debug$1 = typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error('SEMVER', ...args) : () => {};
var debug_1 = debug$1;
(function (module, exports) {
const {
MAX_SAFE_COMPONENT_LENGTH
} = constants;
const debug = debug_1;
exports = module.exports = {};
const re = exports.re = [];
const src = exports.src = [];
const t = exports.t = {};
let R = 0;
const createToken = (name, value, isGlobal) => {
const index = R++;
debug(index, value);
t[name] = index;
src[index] = value;
re[index] = new RegExp(value, isGlobal ? 'g' : undefined);
};
createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*');
createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+');
createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*');
createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`);
createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`);
createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]}|${src[t.NONNUMERICIDENTIFIER]})`);
createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]}|${src[t.NONNUMERICIDENTIFIER]})`);
createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);
createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`);
createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+');
createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`);
createToken('FULLPLAIN', `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);
createToken('FULL', `^${src[t.FULLPLAIN]}$`);
createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);
createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`);
createToken('GTLT', '((?:<|>)?=?)');
createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);
createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?` + `)?)?`);
createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?` + `)?)?`);
createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`);
createToken('COERCE', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:$|[^\\d])`);
createToken('COERCERTL', src[t.COERCE], true);
createToken('LONETILDE', '(?:~>?)');
createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true);
exports.tildeTrimReplace = '$1~';
createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`);
createToken('LONECARET', '(?:\\^)');
createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true);
exports.caretTrimReplace = '$1^';
createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`);
createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`);
createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
exports.comparatorTrimReplace = '$1$2$3';
createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`);
createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`);
createToken('STAR', '(<|>)?=?\\s*\\*');
createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$');
createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$');
})(re$3, re$3.exports);
const opts = ['includePrerelease', 'loose', 'rtl'];
const parseOptions$2 = options => !options ? {} : typeof options !== 'object' ? {
loose: true
} : opts.filter(k => options[k]).reduce((options, k) => {
options[k] = true;
return options;
}, {});
var parseOptions_1 = parseOptions$2;
const numeric = /^[0-9]+$/;
const compareIdentifiers$1 = (a, b) => {
const anum = numeric.test(a);
const bnum = numeric.test(b);
if (anum && bnum) {
a = +a;
b = +b;
}
return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
};
const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a);
var identifiers = {
compareIdentifiers: compareIdentifiers$1,
rcompareIdentifiers
};
const debug = debug_1;
const {
MAX_LENGTH: MAX_LENGTH$1,
MAX_SAFE_INTEGER
} = constants;
const {
re: re$2,
t: t$2
} = re$3.exports;
const parseOptions$1 = parseOptions_1;
const {
compareIdentifiers
} = identifiers;
class SemVer$c {
constructor(version, options) {
options = parseOptions$1(options);
if (version instanceof SemVer$c) {
if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) {
return version;
} else {
version = version.version;
}
} else if (typeof version !== 'string') {
throw new TypeError(`Invalid Version: ${version}`);
}
if (version.length > MAX_LENGTH$1) {
throw new TypeError(`version is longer than ${MAX_LENGTH$1} characters`);
}
debug('SemVer', version, options);
this.options = options;
this.loose = !!options.loose;
this.includePrerelease = !!options.includePrerelease;
const m = version.trim().match(options.loose ? re$2[t$2.LOOSE] : re$2[t$2.FULL]);
if (!m) {
throw new TypeError(`Invalid Version: ${version}`);
}
this.raw = version;
this.major = +m[1];
this.minor = +m[2];
this.patch = +m[3];
if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
throw new TypeError('Invalid major version');
}
if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
throw new TypeError('Invalid minor version');
}
if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
throw new TypeError('Invalid patch version');
}
if (!m[4]) {
this.prerelease = [];
} else {
this.prerelease = m[4].split('.').map(id => {
if (/^[0-9]+$/.test(id)) {
const num = +id;
if (num >= 0 && num < MAX_SAFE_INTEGER) {
return num;
}
}
return id;
});
}
this.build = m[5] ? m[5].split('.') : [];
this.format();
}
format() {
this.version = `${this.major}.${this.minor}.${this.patch}`;
if (this.prerelease.length) {
this.version += `-${this.prerelease.join('.')}`;
}
return this.version;
}
toString() {
return this.version;
}
compare(other) {
debug('SemVer.compare', this.version, this.options, other);
if (!(other instanceof SemVer$c)) {
if (typeof other === 'string' && other === this.version) {
return 0;
}
other = new SemVer$c(other, this.options);
}
if (other.version === this.version) {
return 0;
}
return this.compareMain(other) || this.comparePre(other);
}
compareMain(other) {
if (!(other instanceof SemVer$c)) {
other = new SemVer$c(other, this.options);
}
return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
}
comparePre(other) {
if (!(other instanceof SemVer$c)) {
other = new SemVer$c(other, this.options);
}
if (this.prerelease.length && !other.prerelease.length) {
return -1;
} else if (!this.prerelease.length && other.prerelease.length) {
return 1;
} else if (!this.prerelease.length && !other.prerelease.length) {
return 0;
}
let i = 0;
do {
const a = this.prerelease[i];
const b = other.prerelease[i];
debug('prerelease compare', i, a, b);
if (a === undefined && b === undefined) {
return 0;
} else if (b === undefined) {
return 1;
} else if (a === undefined) {
return -1;
} else if (a === b) {
continue;
} else {
return compareIdentifiers(a, b);
}
} while (++i);
}
compareBuild(other) {
if (!(other instanceof SemVer$c)) {
other = new SemVer$c(other, this.options);
}
let i = 0;
do {
const a = this.build[i];
const b = other.build[i];
debug('prerelease compare', i, a, b);
if (a === undefined && b === undefined) {
return 0;
} else if (b === undefined) {
return 1;
} else if (a === undefined) {
return -1;
} else if (a === b) {
continue;
} else {
return compareIdentifiers(a, b);
}
} while (++i);
}
inc(release, identifier) {
switch (release) {
case 'premajor':
this.prerelease.length = 0;
this.patch = 0;
this.minor = 0;
this.major++;
this.inc('pre', identifier);
break;
case 'preminor':
this.prerelease.length = 0;
this.patch = 0;
this.minor++;
this.inc('pre', identifier);
break;
case 'prepatch':
this.prerelease.length = 0;
this.inc('patch', identifier);
this.inc('pre', identifier);
break;
case 'prerelease':
if (this.prerelease.length === 0) {
this.inc('patch', identifier);
}
this.inc('pre', identifier);
break;
case 'major':
if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
this.major++;
}
this.minor = 0;
this.patch = 0;
this.prerelease = [];
break;
case 'minor':
if (this.patch !== 0 || this.prerelease.length === 0) {
this.minor++;
}
this.patch = 0;
this.prerelease = [];
break;
case 'patch':
if (this.prerelease.length === 0) {
this.patch++;
}
this.prerelease = [];
break;
case 'pre':
if (this.prerelease.length === 0) {
this.prerelease = [0];
} else {
let i = this.prerelease.length;
while (--i >= 0) {
if (typeof this.prerelease[i] === 'number') {
this.prerelease[i]++;
i = -2;
}
}
if (i === -1) {
this.prerelease.push(0);
}
}
if (identifier) {
if (this.prerelease[0] === identifier) {
if (isNaN(this.prerelease[1])) {
this.prerelease = [identifier, 0];
}
} else {
this.prerelease = [identifier, 0];
}
}
break;
default:
throw new Error(`invalid increment argument: ${release}`);
}
this.format();
this.raw = this.version;
return this;
}
}
var semver$2 = SemVer$c;
const {
MAX_LENGTH
} = constants;
const {
re: re$1,
t: t$1
} = re$3.exports;
const SemVer$b = semver$2;
const parseOptions = parseOptions_1;
const parse$5 = (version, options) => {
options = parseOptions(options);
if (version instanceof SemVer$b) {
return version;
}
if (typeof version !== 'string') {
return null;
}
if (version.length > MAX_LENGTH) {
return null;
}
const r = options.loose ? re$1[t$1.LOOSE] : re$1[t$1.FULL];
if (!r.test(version)) {
return null;
}
try {
return new SemVer$b(version, options);
} catch (er) {
return null;
}
};
var parse_1 = parse$5;
const parse$4 = parse_1;
const valid$1 = (version, options) => {
const v = parse$4(version, options);
return v ? v.version : null;
};
var valid_1 = valid$1;
const parse$3 = parse_1;
const clean = (version, options) => {
const s = parse$3(version.trim().replace(/^[=v]+/, ''), options);
return s ? s.version : null;
};
var clean_1 = clean;
const SemVer$a = semver$2;
const inc = (version, release, options, identifier) => {
if (typeof options === 'string') {
identifier = options;
options = undefined;
}
try {
return new SemVer$a(version, options).inc(release, identifier).version;
} catch (er) {
return null;
}
};
var inc_1 = inc;
const SemVer$9 = semver$2;
const compare$a = (a, b, loose) => new SemVer$9(a, loose).compare(new SemVer$9(b, loose));
var compare_1 = compare$a;
const compare$9 = compare_1;
const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0;
var eq_1 = eq$2;
const parse$2 = parse_1;
const eq$1 = eq_1;
const diff = (version1, version2) => {
if (eq$1(version1, version2)) {
return null;
} else {
const v1 = parse$2(version1);
const v2 = parse$2(version2);
const hasPre = v1.prerelease.length || v2.prerelease.length;
const prefix = hasPre ? 'pre' : '';
const defaultResult = hasPre ? 'prerelease' : '';
for (const key in v1) {
if (key === 'major' || key === 'minor' || key === 'patch') {
if (v1[key] !== v2[key]) {
return prefix + key;
}
}
}
return defaultResult;
}
};
var diff_1 = diff;
const SemVer$8 = semver$2;
const major = (a, loose) => new SemVer$8(a, loose).major;
var major_1 = major;
const SemVer$7 = semver$2;
const minor = (a, loose) => new SemVer$7(a, loose).minor;
var minor_1 = minor;
const SemVer$6 = semver$2;
const patch = (a, loose) => new SemVer$6(a, loose).patch;
var patch_1 = patch;
const parse$1 = parse_1;
const prerelease = (version, options) => {
const parsed = parse$1(version, options);
return parsed && parsed.prerelease.length ? parsed.prerelease : null;
};
var prerelease_1 = prerelease;
const compare$8 = compare_1;
const rcompare = (a, b, loose) => compare$8(b, a, loose);
var rcompare_1 = rcompare;
const compare$7 = compare_1;
const compareLoose = (a, b) => compare$7(a, b, true);
var compareLoose_1 = compareLoose;
const SemVer$5 = semver$2;
const compareBuild$2 = (a, b, loose) => {
const versionA = new SemVer$5(a, loose);
const versionB = new SemVer$5(b, loose);
return versionA.compare(versionB) || versionA.compareBuild(versionB);
};
var compareBuild_1 = compareBuild$2;
const compareBuild$1 = compareBuild_1;
const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose));
var sort_1 = sort;
const compareBuild = compareBuild_1;
const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose));
var rsort_1 = rsort;
const compare$6 = compare_1;
const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0;
var gt_1 = gt$3;
const compare$5 = compare_1;
const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0;
var lt_1 = lt$2;
const compare$4 = compare_1;
const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0;
var neq_1 = neq$1;
const compare$3 = compare_1;
const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0;
var gte_1 = gte$2;
const compare$2 = compare_1;
const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0;
var lte_1 = lte$2;
const eq = eq_1;
const neq = neq_1;
const gt$2 = gt_1;
const gte$1 = gte_1;
const lt$1 = lt_1;
const lte$1 = lte_1;
const cmp = (a, op, b, loose) => {
switch (op) {
case '===':
if (typeof a === 'object') a = a.version;
if (typeof b === 'object') b = b.version;
return a === b;
case '!==':
if (typeof a === 'object') a = a.version;
if (typeof b === 'object') b = b.version;
return a !== b;
case '':
case '=':
case '==':
return eq(a, b, loose);
case '!=':
return neq(a, b, loose);
case '>':
return gt$2(a, b, loose);
case '>=':
return gte$1(a, b, loose);
case '<':
return lt$1(a, b, loose);
case '<=':
return lte$1(a, b, loose);
default:
throw new TypeError(`Invalid operator: ${op}`);
}
};
var cmp_1 = cmp;
const SemVer$4 = semver$2;
const parse = parse_1;
const {
re,
t
} = re$3.exports;
const coerce = (version, options) => {
if (version instanceof SemVer$4) {
return version;
}
if (typeof version === 'number') {
version = String(version);
}
if (typeof version !== 'string') {
return null;
}
options = options || {};
let match = null;
if (!options.rtl) {
match = version.match(re[t.COERCE]);
} else {
let next;
while ((next = re[t.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length)) {
if (!match || next.index + next[0].length !== match.index + match[0].length) {
match = next;
}
re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length;
}
re[t.COERCERTL].lastIndex = -1;
}
if (match === null) return null;
return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options);
};
var coerce_1 = coerce;
var iterator;
var hasRequiredIterator;
function requireIterator() {
if (hasRequiredIterator) return iterator;
hasRequiredIterator = 1;
iterator = function (Yallist) {
Yallist.prototype[Symbol.iterator] = function* () {
for (let walker = this.head; walker; walker = walker.next) {
yield walker.value;
}
};
};
return iterator;
}
var yallist;
var hasRequiredYallist;
function requireYallist() {
if (hasRequiredYallist) return yallist;
hasRequiredYallist = 1;
yallist = Yallist;
Yallist.Node = Node;
Yallist.create = Yallist;
function Yallist(list) {
var self = this;
if (!(self instanceof Yallist)) {
self = new Yallist();
}
self.tail = null;
self.head = null;
self.length = 0;
if (list && typeof list.forEach === 'function') {
list.forEach(function (item) {
self.push(item);
});
} else if (arguments.length > 0) {
for (var i = 0, l = arguments.length; i < l; i++) {
self.push(arguments[i]);
}
}
return self;
}
Yallist.prototype.removeNode = function (node) {
if (node.list !== this) {
throw new Error('removing node which does not belong to this list');
}
var next = node.next;
var prev = node.prev;
if (next) {
next.prev = prev;
}
if (prev) {
prev.next = next;
}
if (node === this.head) {
this.head = next;
}
if (node === this.tail) {
this.tail = prev;
}
node.list.length--;
node.next = null;
node.prev = null;
node.list = null;
return next;
};
Yallist.prototype.unshiftNode = function (node) {
if (node === this.head) {
return;
}
if (node.list) {
node.list.removeNode(node);
}
var head = this.head;
node.list = this;
node.next = head;
if (head) {
head.prev = node;
}
this.head = node;
if (!this.tail) {
this.tail = node;
}
this.length++;
};
Yallist.prototype.pushNode = function (node) {
if (node === this.tail) {
return;
}
if (node.list) {
node.list.removeNode(node);
}
var tail = this.tail;
node.list = this;
node.prev = tail;
if (tail) {
tail.next = node;
}
this.tail = node;
if (!this.head) {
this.head = node;
}
this.length++;
};
Yallist.prototype.push = function () {
for (var i = 0, l = arguments.length; i < l; i++) {
push(this, arguments[i]);
}
return this.length;
};
Yallist.prototype.unshift = function () {
for (var i = 0, l = arguments.length; i < l; i++) {
unshift(this, arguments[i]);
}
return this.length;
};
Yallist.prototype.pop = function () {
if (!this.tail) {
return undefined;
}
var res = this.tail.value;
this.tail = this.tail.prev;
if (this.tail) {
this.tail.next = null;
} else {
this.head = null;
}
this.length--;
return res;
};
Yallist.prototype.shift = function () {
if (!this.head) {
return undefined;
}
var res = this.head.value;
this.head = this.head.next;
if (this.head) {
this.head.prev = null;
} else {
this.tail = null;
}
this.length--;
return res;
};
Yallist.prototype.forEach = function (fn, thisp) {
thisp = thisp || this;
for (var walker = this.head, i = 0; walker !== null; i++) {
fn.call(thisp, walker.value, i, this);
walker = walker.next;
}
};
Yallist.prototype.forEachReverse = function (fn, thisp) {
thisp = thisp || this;
for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
fn.call(thisp, walker.value, i, this);
walker = walker.prev;
}
};
Yallist.prototype.get = function (n) {
for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
walker = walker.next;
}
if (i === n && walker !== null) {
return walker.value;
}
};
Yallist.prototype.getReverse = function (n) {
for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
walker = walker.prev;
}
if (i === n && walker !== null) {
return walker.value;
}
};
Yallist.prototype.map = function (fn, thisp) {
thisp = thisp || this;
var res = new Yallist();
for (var walker = this.head; walker !== null;) {
res.push(fn.call(thisp, walker.value, this));
walker = walker.next;
}
return res;
};
Yallist.prototype.mapReverse = function (fn, thisp) {
thisp = thisp || this;
var res = new Yallist();
for (var walker = this.tail; walker !== null;) {
res.push(fn.call(thisp, walker.value, this));
walker = walker.prev;
}
return res;
};
Yallist.prototype.reduce = function (fn, initial) {
var acc;
var walker = this.head;
if (arguments.length > 1) {
acc = initial;
} else if (this.head) {
walker = this.head.next;
acc = this.head.value;
} else {
throw new TypeError('Reduce of empty list with no initial value');
}
for (var i = 0; walker !== null; i++) {
acc = fn(acc, walker.value, i);
walker = walker.next;
}
return acc;
};
Yallist.prototype.reduceReverse = function (fn, initial) {
var acc;
var walker = this.tail;
if (arguments.length > 1) {
acc = initial;
} else if (this.tail) {
walker = this.tail.prev;
acc = this.tail.value;
} else {
throw new TypeError('Reduce of empty list with no initial value');
}
for (var i = this.length - 1; walker !== null; i--) {
acc = fn(acc, walker.value, i);
walker = walker.prev;
}
return acc;
};
Yallist.prototype.toArray = function () {
var arr = new Array(this.length);
for (var i = 0, walker = this.head; walker !== null; i++) {
arr[i] = walker.value;
walker = walker.next;
}
return arr;
};
Yallist.prototype.toArrayReverse = function () {
var arr = new Array(this.length);
for (var i = 0, walker = this.tail; walker !== null; i++) {
arr[i] = walker.value;
walker = walker.prev;
}
return arr;
};
Yallist.prototype.slice = function (from, to) {
to = to || this.length;
if (to < 0) {
to += this.length;
}
from = from || 0;
if (from < 0) {
from += this.length;
}
var ret = new Yallist();
if (to < from || to < 0) {
return ret;
}
if (from < 0) {
from = 0;
}
if (to > this.length) {
to = this.length;
}
for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
walker = walker.next;
}
for (; walker !== null && i < to; i++, walker = walker.next) {
ret.push(walker.value);
}
return ret;
};
Yallist.prototype.sliceReverse = function (from, to) {
to = to || this.length;
if (to < 0) {
to += this.length;
}
from = from || 0;
if (from < 0) {
from += this.length;
}
var ret = new Yallist();
if (to < from || to < 0) {
return ret;
}
if (from < 0) {
from = 0;
}
if (to > this.length) {
to = this.length;
}
for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
walker = walker.prev;
}
for (; walker !== null && i > from; i--, walker = walker.prev) {
ret.push(walker.value);
}
return ret;
};
Yallist.prototype.splice = function (start, deleteCount, ...nodes) {
if (start > this.length) {
start = this.length - 1;
}
if (start < 0) {
start = this.length + start;
}
for (var i = 0, walker = this.head; walker !== null && i < start; i++) {
walker = walker.next;
}
var ret = [];
for (var i = 0; walker && i < deleteCount; i++) {
ret.push(walker.value);
walker = this.removeNode(walker);
}
if (walker === null) {
walker = this.tail;
}
if (walker !== this.head && walker !== this.tail) {
walker = walker.prev;
}
for (var i = 0; i < nodes.length; i++) {
walker = insert(this, walker, nodes[i]);
}
return ret;
};
Yallist.prototype.reverse = function () {
var head = this.head;
var tail = this.tail;
for (var walker = head; walker !== null; walker = walker.prev) {
var p = walker.prev;
walker.prev = walker.next;
walker.next = p;
}
this.head = tail;
this.tail = head;
return this;
};
function insert(self, node, value) {
var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self);
if (inserted.next === null) {
self.tail = inserted;
}
if (inserted.prev === null) {
self.head = inserted;
}
self.length++;
return inserted;
}
function push(self, item) {
self.tail = new Node(item, self.tail, null, self);
if (!self.head) {
self.head = self.tail;
}
self.length++;
}
function unshift(self, item) {
self.head = new Node(item, null, self.head, self);
if (!self.tail) {
self.tail = self.head;
}
self.length++;
}
function Node(value, prev, next, list) {
if (!(this instanceof Node)) {
return new Node(value, prev, next, list);
}
this.list = list;
this.value = value;
if (prev) {
prev.next = this;
this.prev = prev;
} else {
this.prev = null;
}
if (next) {
next.prev = this;
this.next = next;
} else {
this.next = null;
}
}
try {
requireIterator()(Yallist);
} catch (er) {}
return yallist;
}
var lruCache;
var hasRequiredLruCache;
function requireLruCache() {
if (hasRequiredLruCache) return lruCache;
hasRequiredLruCache = 1;
const Yallist = requireYallist();
const MAX = Symbol('max');
const LENGTH = Symbol('length');
const LENGTH_CALCULATOR = Symbol('lengthCalculator');
const ALLOW_STALE = Symbol('allowStale');
const MAX_AGE = Symbol('maxAge');
const DISPOSE = Symbol('dispose');
const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet');
const LRU_LIST = Symbol('lruList');
const CACHE = Symbol('cache');
const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet');
const naiveLength = () => 1;
class LRUCache {
constructor(options) {
if (typeof options === 'number') options = {
max: options
};
if (!options) options = {};
if (options.max && (typeof options.max !== 'number' || options.max < 0)) throw new TypeError('max must be a non-negative number');
this[MAX] = options.max || Infinity;
const lc = options.length || naiveLength;
this[LENGTH_CALCULATOR] = typeof lc !== 'function' ? naiveLength : lc;
this[ALLOW_STALE] = options.stale || false;
if (options.maxAge && typeof options.maxAge !== 'number') throw new TypeError('maxAge must be a number');
this[MAX_AGE] = options.maxAge || 0;
this[DISPOSE] = options.dispose;
this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false;
this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false;
this.reset();
}
set max(mL) {
if (typeof mL !== 'number' || mL < 0) throw new TypeError('max must be a non-negative number');
this[MAX] = mL || Infinity;
trim(this);
}
get max() {
return this[MAX];
}
set allowStale(allowStale) {
this[ALLOW_STALE] = !!allowStale;
}
get allowStale() {
return this[ALLOW_STALE];
}
set maxAge(mA) {
if (typeof mA !== 'number') throw new TypeError('maxAge must be a non-negative number');
this[MAX_AGE] = mA;
trim(this);
}
get maxAge() {
return this[MAX_AGE];
}
set lengthCalculator(lC) {
if (typeof lC !== 'function') lC = naiveLength;
if (lC !== this[LENGTH_CALCULATOR]) {
this[LENGTH_CALCULATOR] = lC;
this[LENGTH] = 0;
this[LRU_LIST].forEach(hit => {
hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key);
this[LENGTH] += hit.length;
});
}
trim(this);
}
get lengthCalculator() {
return this[LENGTH_CALCULATOR];
}
get length() {
return this[LENGTH];
}
get itemCount() {
return this[LRU_LIST].length;
}
rforEach(fn, thisp) {
thisp = thisp || this;
for (let walker = this[LRU_LIST].tail; walker !== null;) {
const prev = walker.prev;
forEachStep(this, fn, walker, thisp);
walker = prev;
}
}
forEach(fn, thisp) {
thisp = thisp || this;
for (let walker = this[LRU_LIST].head; walker !== null;) {
const next = walker.next;
forEachStep(this, fn, walker, thisp);
walker = next;
}
}
keys() {
return this[LRU_LIST].toArray().map(k => k.key);
}
values() {
return this[LRU_LIST].toArray().map(k => k.value);
}
reset() {
if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) {
this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value));
}
this[CACHE] = new Map();
this[LRU_LIST] = new Yallist();
this[LENGTH] = 0;
}
dump() {
return this[LRU_LIST].map(hit => isStale(this, hit) ? false : {
k: hit.key,
v: hit.value,
e: hit.now + (hit.maxAge || 0)
}).toArray().filter(h => h);
}
dumpLru() {
return this[LRU_LIST];
}
set(key, value, maxAge) {
maxAge = maxAge || this[MAX_AGE];
if (maxAge && typeof maxAge !== 'number') throw new TypeError('maxAge must be a number');
const now = maxAge ? Date.now() : 0;
const len = this[LENGTH_CALCULATOR](value, key);
if (this[CACHE].has(key)) {
if (len > this[MAX]) {
del(this, this[CACHE].get(key));
return false;
}
const node = this[CACHE].get(key);
const item = node.value;
if (this[DISPOSE]) {
if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value);
}
item.now = now;
item.maxAge = maxAge;
item.value = value;
this[LENGTH] += len - item.length;
item.length = len;
this.get(key);
trim(this);
return true;
}
const hit = new Entry(key, value, len, now, maxAge);
if (hit.length > this[MAX]) {
if (this[DISPOSE]) this[DISPOSE](key, value);
return false;
}
this[LENGTH] += hit.length;
this[LRU_LIST].unshift(hit);
this[CACHE].set(key, this[LRU_LIST].head);
trim(this);
return true;
}
has(key) {
if (!this[CACHE].has(key)) return false;
const hit = this[CACHE].get(key).value;
return !isStale(this, hit);
}
get(key) {
return get(this, key, true);
}
peek(key) {
return get(this, key, false);
}
pop() {
const node = this[LRU_LIST].tail;
if (!node) return null;
del(this, node);
return node.value;
}
del(key) {
del(this, this[CACHE].get(key));
}
load(arr) {
this.reset();
const now = Date.now();
for (let l = arr.length - 1; l >= 0; l--) {
const hit = arr[l];
const expiresAt = hit.e || 0;
if (expiresAt === 0) this.set(hit.k, hit.v);else {
const maxAge = expiresAt - now;
if (maxAge > 0) {
this.set(hit.k, hit.v, maxAge);
}
}
}
}
prune() {
this[CACHE].forEach((value, key) => get(this, key, false));
}
}
const get = (self, key, doUse) => {
const node = self[CACHE].get(key);
if (node) {
const hit = node.value;
if (isStale(self, hit)) {
del(self, node);
if (!self[ALLOW_STALE]) return undefined;
} else {
if (doUse) {
if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now();
self[LRU_LIST].unshiftNode(node);
}
}
return hit.value;
}
};
const isStale = (self, hit) => {
if (!hit || !hit.maxAge && !self[MAX_AGE]) return false;
const diff = Date.now() - hit.now;
return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && diff > self[MAX_AGE];
};
const trim = self => {
if (self[LENGTH] > self[MAX]) {
for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) {
const prev = walker.prev;
del(self, walker);
walker = prev;
}
}
};
const del = (self, node) => {
if (node) {
const hit = node.value;
if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value);
self[LENGTH] -= hit.length;
self[CACHE].delete(hit.key);
self[LRU_LIST].removeNode(node);
}
};
class Entry {
constructor(key, value, length, now, maxAge) {
this.key = key;
this.value = value;
this.length = length;
this.now = now;
this.maxAge = maxAge || 0;
}
}
const forEachStep = (self, fn, node, thisp) => {
let hit = node.value;
if (isStale(self, hit)) {
del(self, node);
if (!self[ALLOW_STALE]) hit = undefined;
}
if (hit) fn.call(thisp, hit.value, hit.key, self);
};
lruCache = LRUCache;
return lruCache;
}
var range;
var hasRequiredRange;
function requireRange() {
if (hasRequiredRange) return range;
hasRequiredRange = 1;
class Range {
constructor(range, options) {
options = parseOptions(options);
if (range instanceof Range) {
if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
return range;
} else {
return new Range(range.raw, options);
}
}
if (range instanceof Comparator) {
this.raw = range.value;
this.set = [[range]];
this.format();
return this;
}
this.options = options;
this.loose = !!options.loose;
this.includePrerelease = !!options.includePrerelease;
this.raw = range;
this.set = range.split(/\s*\|\|\s*/).map(range => this.parseRange(range.trim())).filter(c => c.length);
if (!this.set.length) {
throw new TypeError(`Invalid SemVer Range: ${range}`);
}
if (this.set.length > 1) {
const first = this.set[0];
this.set = this.set.filter(c => !isNullSet(c[0]));
if (this.set.length === 0) this.set = [first];else if (this.set.length > 1) {
for (const c of this.set) {
if (c.length === 1 && isAny(c[0])) {
this.set = [c];
break;
}
}
}
}
this.format();
}
format() {
this.range = this.set.map(comps => {
return comps.join(' ').trim();
}).join('||').trim();
return this.range;
}
toString() {
return this.range;
}
parseRange(range) {
range = range.trim();
const memoOpts = Object.keys(this.options).join(',');
const memoKey = `parseRange:${memoOpts}:${range}`;
const cached = cache.get(memoKey);
if (cached) return cached;
const loose = this.options.loose;
const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE];
range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
debug('hyphen replace', range);
range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace);
debug('comparator trim', range, re[t.COMPARATORTRIM]);
range = range.replace(re[t.TILDETRIM], tildeTrimReplace);
range = range.replace(re[t.CARETTRIM], caretTrimReplace);
range = range.split(/\s+/).join(' ');
const compRe = loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
const rangeList = range.split(' ').map(comp => parseComparator(comp, this.options)).join(' ').split(/\s+/).map(comp => replaceGTE0(comp, this.options)).filter(this.options.loose ? comp => !!comp.match(compRe) : () => true).map(comp => new Comparator(comp, this.options));
rangeList.length;
const rangeMap = new Map();
for (const comp of rangeList) {
if (isNullSet(comp)) return [comp];
rangeMap.set(comp.value, comp);
}
if (rangeMap.size > 1 && rangeMap.has('')) rangeMap.delete('');
const result = [...rangeMap.values()];
cache.set(memoKey, result);
return result;
}
intersects(range, options) {
if (!(range instanceof Range)) {
throw new TypeError('a Range is required');
}
return this.set.some(thisComparators => {
return isSatisfiable(thisComparators, options) && range.set.some(rangeComparators => {
return isSatisfiable(rangeComparators, options) && thisComparators.every(thisComparator => {
return rangeComparators.every(rangeComparator => {
return thisComparator.intersects(rangeComparator, options);
});
});
});
});
}
test(version) {
if (!version) {
return false;
}
if (typeof version === 'string') {
try {
version = new SemVer(version, this.options);
} catch (er) {
return false;
}
}
for (let i = 0; i < this.set.length; i++) {
if (testSet(this.set[i], version, this.options)) {
return true;
}
}
return false;
}
}
range = Range;
const LRU = requireLruCache();
const cache = new LRU({
max: 1000
});
const parseOptions = parseOptions_1;
const Comparator = requireComparator();
const debug = debug_1;
const SemVer = semver$2;
const {
re,
t,
comparatorTrimReplace,
tildeTrimReplace,
caretTrimReplace
} = re$3.exports;
const isNullSet = c => c.value === '<0.0.0-0';
const isAny = c => c.value === '';
const isSatisfiable = (comparators, options) => {
let result = true;
const remainingComparators = comparators.slice();
let testComparator = remainingComparators.pop();
while (result && remainingComparators.length) {
result = remainingComparators.every(otherComparator => {
return testComparator.intersects(otherComparator, options);
});
testComparator = remainingComparators.pop();
}
return result;
};
const parseComparator = (comp, options) => {
debug('comp', comp, options);
comp = replaceCarets(comp, options);
debug('caret', comp);
comp = replaceTildes(comp, options);
debug('tildes', comp);
comp = replaceXRanges(comp, options);
debug('xrange', comp);
comp = replaceStars(comp, options);
debug('stars', comp);
return comp;
};
const isX = id => !id || id.toLowerCase() === 'x' || id === '*';
const replaceTildes = (comp, options) => comp.trim().split(/\s+/).map(comp => {
return replaceTilde(comp, options);
}).join(' ');
const replaceTilde = (comp, options) => {
const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
return comp.replace(r, (_, M, m, p, pr) => {
debug('tilde', comp, _, M, m, p, pr);
let ret;
if (isX(M)) {
ret = '';
} else if (isX(m)) {
ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
} else if (isX(p)) {
ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;
} else if (pr) {
debug('replaceTilde pr', pr);
ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
} else {
ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;
}
debug('tilde return', ret);
return ret;
});
};
const replaceCarets = (comp, options) => comp.trim().split(/\s+/).map(comp => {
return replaceCaret(comp, options);
}).join(' ');
const replaceCaret = (comp, options) => {
debug('caret', comp, options);
const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
const z = options.includePrerelease ? '-0' : '';
return comp.replace(r, (_, M, m, p, pr) => {
debug('caret', comp, _, M, m, p, pr);
let ret;
if (isX(M)) {
ret = '';
} else if (isX(m)) {
ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
} else if (isX(p)) {
if (M === '0') {
ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
} else {
ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
}
} else if (pr) {
debug('replaceCaret pr', pr);
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`;
} else {
ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
}
} else {
ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`;
}
} else {
debug('no pr');
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`;
} else {
ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`;
}
} else {
ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`;
}
}
debug('caret return', ret);
return ret;
});
};
const replaceXRanges = (comp, options) => {
debug('replaceXRanges', comp, options);
return comp.split(/\s+/).map(comp => {
return replaceXRange(comp, options);
}).join(' ');
};
const replaceXRange = (comp, options) => {
comp = comp.trim();
const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
debug('xRange', comp, ret, gtlt, M, m, p, pr);
const xM = isX(M);
const xm = xM || isX(m);
const xp = xm || isX(p);
const anyX = xp;
if (gtlt === '=' && anyX) {
gtlt = '';
}
pr = options.includePrerelease ? '-0' : '';
if (xM) {
if (gtlt === '>' || gtlt === '<') {
ret = '<0.0.0-0';
} else {
ret = '*';
}
} else if (gtlt && anyX) {
if (xm) {
m = 0;
}
p = 0;
if (gtlt === '>') {
gtlt = '>=';
if (xm) {
M = +M + 1;
m = 0;
p = 0;
} else {
m = +m + 1;
p = 0;
}
} else if (gtlt === '<=') {
gtlt = '<';
if (xm) {
M = +M + 1;
} else {
m = +m + 1;
}
}
if (gtlt === '<') pr = '-0';
ret = `${gtlt + M}.${m}.${p}${pr}`;
} else if (xm) {
ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
} else if (xp) {
ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`;
}
debug('xRange return', ret);
return ret;
});
};
const replaceStars = (comp, options) => {
debug('replaceStars', comp, options);
return comp.trim().replace(re[t.STAR], '');
};
const replaceGTE0 = (comp, options) => {
debug('replaceGTE0', comp, options);
return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '');
};
const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => {
if (isX(fM)) {
from = '';
} else if (isX(fm)) {
from = `>=${fM}.0.0${incPr ? '-0' : ''}`;
} else if (isX(fp)) {
from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`;
} else if (fpr) {
from = `>=${from}`;
} else {
from = `>=${from}${incPr ? '-0' : ''}`;
}
if (isX(tM)) {
to = '';
} else if (isX(tm)) {
to = `<${+tM + 1}.0.0-0`;
} else if (isX(tp)) {
to = `<${tM}.${+tm + 1}.0-0`;
} else if (tpr) {
to = `<=${tM}.${tm}.${tp}-${tpr}`;
} else if (incPr) {
to = `<${tM}.${tm}.${+tp + 1}-0`;
} else {
to = `<=${to}`;
}
return `${from} ${to}`.trim();
};
const testSet = (set, version, options) => {
for (let i = 0; i < set.length; i++) {
if (!set[i].test(version)) {
return false;
}
}
if (version.prerelease.length && !options.includePrerelease) {
for (let i = 0; i < set.length; i++) {
debug(set[i].semver);
if (set[i].semver === Comparator.ANY) {
continue;
}
if (set[i].semver.prerelease.length > 0) {
const allowed = set[i].semver;
if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
return true;
}
}
}
return false;
}
return true;
};
return range;
}
var comparator;
var hasRequiredComparator;
function requireComparator() {
if (hasRequiredComparator) return comparator;
hasRequiredComparator = 1;
const ANY = Symbol('SemVer ANY');
class Comparator {
static get ANY() {
return ANY;
}
constructor(comp, options) {
options = parseOptions(options);
if (comp instanceof Comparator) {
if (comp.loose === !!options.loose) {
return comp;
} else {
comp = comp.value;
}
}
debug('comparator', comp, options);
this.options = options;
this.loose = !!options.loose;
this.parse(comp);
if (this.semver === ANY) {
this.value = '';
} else {
this.value = this.operator + this.semver.version;
}
debug('comp', this);
}
parse(comp) {
const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
const m = comp.match(r);
if (!m) {
throw new TypeError(`Invalid comparator: ${comp}`);
}
this.operator = m[1] !== undefined ? m[1] : '';
if (this.operator === '=') {
this.operator = '';
}
if (!m[2]) {
this.semver = ANY;
} else {
this.semver = new SemVer(m[2], this.options.loose);
}
}
toString() {
return this.value;
}
test(version) {
debug('Comparator.test', version, this.options.loose);
if (this.semver === ANY || version === ANY) {
return true;
}
if (typeof version === 'string') {
try {
version = new SemVer(version, this.options);
} catch (er) {
return false;
}
}
return cmp(version, this.operator, this.semver, this.options);
}
intersects(comp, options) {
if (!(comp instanceof Comparator)) {
throw new TypeError('a Comparator is required');
}
if (!options || typeof options !== 'object') {
options = {
loose: !!options,
includePrerelease: false
};
}
if (this.operator === '') {
if (this.value === '') {
return true;
}
return new Range(comp.value, options).test(this.value);
} else if (comp.operator === '') {
if (comp.value === '') {
return true;
}
return new Range(this.value, options).test(comp.semver);
}
const sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>');
const sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<');
const sameSemVer = this.semver.version === comp.semver.version;
const differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=');
const oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<');
const oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>');
return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
}
}
comparator = Comparator;
const parseOptions = parseOptions_1;
const {
re,
t
} = re$3.exports;
const cmp = cmp_1;
const debug = debug_1;
const SemVer = semver$2;
const Range = requireRange();
return comparator;
}
const Range$8 = requireRange();
const satisfies$3 = (version, range, options) => {
try {
range = new Range$8(range, options);
} catch (er) {
return false;
}
return range.test(version);
};
var satisfies_1 = satisfies$3;
const Range$7 = requireRange();
const toComparators = (range, options) => new Range$7(range, options).set.map(comp => comp.map(c => c.value).join(' ').trim().split(' '));
var toComparators_1 = toComparators;
const SemVer$3 = semver$2;
const Range$6 = requireRange();
const maxSatisfying = (versions, range, options) => {
let max = null;
let maxSV = null;
let rangeObj = null;
try {
rangeObj = new Range$6(range, options);
} catch (er) {
return null;
}
versions.forEach(v => {
if (rangeObj.test(v)) {
if (!max || maxSV.compare(v) === -1) {
max = v;
maxSV = new SemVer$3(max, options);
}
}
});
return max;
};
var maxSatisfying_1 = maxSatisfying;
const SemVer$2 = semver$2;
const Range$5 = requireRange();
const minSatisfying = (versions, range, options) => {
let min = null;
let minSV = null;
let rangeObj = null;
try {
rangeObj = new Range$5(range, options);
} catch (er) {
return null;
}
versions.forEach(v => {
if (rangeObj.test(v)) {
if (!min || minSV.compare(v) === 1) {
min = v;
minSV = new SemVer$2(min, options);
}
}
});
return min;
};
var minSatisfying_1 = minSatisfying;
const SemVer$1 = semver$2;
const Range$4 = requireRange();
const gt$1 = gt_1;
const minVersion = (range, loose) => {
range = new Range$4(range, loose);
let minver = new SemVer$1('0.0.0');
if (range.test(minver)) {
return minver;
}
minver = new SemVer$1('0.0.0-0');
if (range.test(minver)) {
return minver;
}
minver = null;
for (let i = 0; i < range.set.length; ++i) {
const comparators = range.set[i];
let setMin = null;
comparators.forEach(comparator => {
const compver = new SemVer$1(comparator.semver.version);
switch (comparator.operator) {
case '>':
if (compver.prerelease.length === 0) {
compver.patch++;
} else {
compver.prerelease.push(0);
}
compver.raw = compver.format();
case '':
case '>=':
if (!setMin || gt$1(compver, setMin)) {
setMin = compver;
}
break;
case '<':
case '<=':
break;
default:
throw new Error(`Unexpected operation: ${comparator.operator}`);
}
});
if (setMin && (!minver || gt$1(minver, setMin))) minver = setMin;
}
if (minver && range.test(minver)) {
return minver;
}
return null;
};
var minVersion_1 = minVersion;
const Range$3 = requireRange();
const validRange = (range, options) => {
try {
return new Range$3(range, options).range || '*';
} catch (er) {
return null;
}
};
var valid = validRange;
const SemVer = semver$2;
const Comparator$1 = requireComparator();
const {
ANY: ANY$1
} = Comparator$1;
const Range$2 = requireRange();
const satisfies$2 = satisfies_1;
const gt = gt_1;
const lt = lt_1;
const lte = lte_1;
const gte = gte_1;
const outside$2 = (version, range, hilo, options) => {
version = new SemVer(version, options);
range = new Range$2(range, options);
let gtfn, ltefn, ltfn, comp, ecomp;
switch (hilo) {
case '>':
gtfn = gt;
ltefn = lte;
ltfn = lt;
comp = '>';
ecomp = '>=';
break;
case '<':
gtfn = lt;
ltefn = gte;
ltfn = gt;
comp = '<';
ecomp = '<=';
break;
default:
throw new TypeError('Must provide a hilo val of "<" or ">"');
}
if (satisfies$2(version, range, options)) {
return false;
}
for (let i = 0; i < range.set.length; ++i) {
const comparators = range.set[i];
let high = null;
let low = null;
comparators.forEach(comparator => {
if (comparator.semver === ANY$1) {
comparator = new Comparator$1('>=0.0.0');
}
high = high || comparator;
low = low || comparator;
if (gtfn(comparator.semver, high.semver, options)) {
high = comparator;
} else if (ltfn(comparator.semver, low.semver, options)) {
low = comparator;
}
});
if (high.operator === comp || high.operator === ecomp) {
return false;
}
if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
return false;
} else if (low.operator === ecomp && ltfn(version, low.semver)) {
return false;
}
}
return true;
};
var outside_1 = outside$2;
const outside$1 = outside_1;
const gtr = (version, range, options) => outside$1(version, range, '>', options);
var gtr_1 = gtr;
const outside = outside_1;
const ltr = (version, range, options) => outside(version, range, '<', options);
var ltr_1 = ltr;
const Range$1 = requireRange();
const intersects = (r1, r2, options) => {
r1 = new Range$1(r1, options);
r2 = new Range$1(r2, options);
return r1.intersects(r2);
};
var intersects_1 = intersects;
const satisfies$1 = satisfies_1;
const compare$1 = compare_1;
var simplify = (versions, range, options) => {
const set = [];
let min = null;
let prev = null;
const v = versions.sort((a, b) => compare$1(a, b, options));
for (const version of v) {
const included = satisfies$1(version, range, options);
if (included) {
prev = version;
if (!min) min = version;
} else {
if (prev) {
set.push([min, prev]);
}
prev = null;
min = null;
}
}
if (min) set.push([min, null]);
const ranges = [];
for (const [min, max] of set) {
if (min === max) ranges.push(min);else if (!max && min === v[0]) ranges.push('*');else if (!max) ranges.push(`>=${min}`);else if (min === v[0]) ranges.push(`<=${max}`);else ranges.push(`${min} - ${max}`);
}
const simplified = ranges.join(' || ');
const original = typeof range.raw === 'string' ? range.raw : String(range);
return simplified.length < original.length ? simplified : range;
};
const Range = requireRange();
const Comparator = requireComparator();
const {
ANY
} = Comparator;
const satisfies = satisfies_1;
const compare = compare_1;
const subset = (sub, dom, options = {}) => {
if (sub === dom) return true;
sub = new Range(sub, options);
dom = new Range(dom, options);
let sawNonNull = false;
OUTER: for (const simpleSub of sub.set) {
for (const simpleDom of dom.set) {
const isSub = simpleSubset(simpleSub, simpleDom, options);
sawNonNull = sawNonNull || isSub !== null;
if (isSub) continue OUTER;
}
if (sawNonNull) return false;
}
return true;
};
const simpleSubset = (sub, dom, options) => {
if (sub === dom) return true;
if (sub.length === 1 && sub[0].semver === ANY) {
if (dom.length === 1 && dom[0].semver === ANY) return true;else if (options.includePrerelease) sub = [new Comparator('>=0.0.0-0')];else sub = [new Comparator('>=0.0.0')];
}
if (dom.length === 1 && dom[0].semver === ANY) {
if (options.includePrerelease) return true;else dom = [new Comparator('>=0.0.0')];
}
const eqSet = new Set();
let gt, lt;
for (const c of sub) {
if (c.operator === '>' || c.operator === '>=') gt = higherGT(gt, c, options);else if (c.operator === '<' || c.operator === '<=') lt = lowerLT(lt, c, options);else eqSet.add(c.semver);
}
if (eqSet.size > 1) return null;
let gtltComp;
if (gt && lt) {
gtltComp = compare(gt.semver, lt.semver, options);
if (gtltComp > 0) return null;else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) return null;
}
for (const eq of eqSet) {
if (gt && !satisfies(eq, String(gt), options)) return null;
if (lt && !satisfies(eq, String(lt), options)) return null;
for (const c of dom) {
if (!satisfies(eq, String(c), options)) return false;
}
return true;
}
let higher, lower;
let hasDomLT, hasDomGT;
let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false;
let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false;
if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {
needDomLTPre = false;
}
for (const c of dom) {
hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=';
hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=';
if (gt) {
if (needDomGTPre) {
if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) {
needDomGTPre = false;
}
}
if (c.operator === '>' || c.operator === '>=') {
higher = higherGT(gt, c, options);
if (higher === c && higher !== gt) return false;
} else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) return false;
}
if (lt) {
if (needDomLTPre) {
if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) {
needDomLTPre = false;
}
}
if (c.operator === '<' || c.operator === '<=') {
lower = lowerLT(lt, c, options);
if (lower === c && lower !== lt) return false;
} else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) return false;
}
if (!c.operator && (lt || gt) && gtltComp !== 0) return false;
}
if (gt && hasDomLT && !lt && gtltComp !== 0) return false;
if (lt && hasDomGT && !gt && gtltComp !== 0) return false;
if (needDomGTPre || needDomLTPre) return false;
return true;
};
const higherGT = (a, b, options) => {
if (!a) return b;
const comp = compare(a.semver, b.semver, options);
return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a;
};
const lowerLT = (a, b, options) => {
if (!a) return b;
const comp = compare(a.semver, b.semver, options);
return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a;
};
var subset_1 = subset;
const internalRe = re$3.exports;
var semver$1 = {
re: internalRe.re,
src: internalRe.src,
tokens: internalRe.t,
SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
SemVer: semver$2,
compareIdentifiers: identifiers.compareIdentifiers,
rcompareIdentifiers: identifiers.rcompareIdentifiers,
parse: parse_1,
valid: valid_1,
clean: clean_1,
inc: inc_1,
diff: diff_1,
major: major_1,
minor: minor_1,
patch: patch_1,
prerelease: prerelease_1,
compare: compare_1,
rcompare: rcompare_1,
compareLoose: compareLoose_1,
compareBuild: compareBuild_1,
sort: sort_1,
rsort: rsort_1,
gt: gt_1,
lt: lt_1,
eq: eq_1,
neq: neq_1,
gte: gte_1,
lte: lte_1,
cmp: cmp_1,
coerce: coerce_1,
Comparator: requireComparator(),
Range: requireRange(),
satisfies: satisfies_1,
toComparators: toComparators_1,
maxSatisfying: maxSatisfying_1,
minSatisfying: minSatisfying_1,
minVersion: minVersion_1,
validRange: valid,
outside: outside_1,
gtr: gtr_1,
ltr: ltr_1,
intersects: intersects_1,
simplifyRange: simplify,
subset: subset_1
};
var semver = semver$1;
var builtins = function ({
version = process.version,
experimental = false
} = {}) {
var coreModules = ['assert', 'buffer', 'child_process', 'cluster', 'console', 'constants', 'crypto', 'dgram', 'dns', 'domain', 'events', 'fs', 'http', 'https', 'module', 'net', 'os', 'path', 'punycode', 'querystring', 'readline', 'repl', 'stream', 'string_decoder', 'sys', 'timers', 'tls', 'tty', 'url', 'util', 'vm', 'zlib'];
if (semver.lt(version, '6.0.0')) coreModules.push('freelist');
if (semver.gte(version, '1.0.0')) coreModules.push('v8');
if (semver.gte(version, '1.1.0')) coreModules.push('process');
if (semver.gte(version, '8.0.0')) coreModules.push('inspector');
if (semver.gte(version, '8.1.0')) coreModules.push('async_hooks');
if (semver.gte(version, '8.4.0')) coreModules.push('http2');
if (semver.gte(version, '8.5.0')) coreModules.push('perf_hooks');
if (semver.gte(version, '10.0.0')) coreModules.push('trace_events');
if (semver.gte(version, '10.5.0') && (experimental || semver.gte(version, '12.0.0'))) {
coreModules.push('worker_threads');
}
if (semver.gte(version, '12.16.0') && experimental) {
coreModules.push('wasi');
}
return coreModules;
};
const reader = {
read
};
function read(jsonPath) {
return find(_path().dirname(jsonPath));
}
function find(dir) {
try {
const string = _fs().default.readFileSync(_path().toNamespacedPath(_path().join(dir, 'package.json')), 'utf8');
return {
string
};
} catch (error) {
if (error.code === 'ENOENT') {
const parent = _path().dirname(dir);
if (dir !== parent) return find(parent);
return {
string: undefined
};
}
throw error;
}
}
const isWindows = process.platform === 'win32';
const own$1 = {}.hasOwnProperty;
const codes = {};
const messages = new Map();
const nodeInternalPrefix = '__node_internal_';
let userStackTraceLimit;
codes.ERR_INVALID_MODULE_SPECIFIER = createError('ERR_INVALID_MODULE_SPECIFIER', (request, reason, base = undefined) => {
return `Invalid module "${request}" ${reason}${base ? ` imported from ${base}` : ''}`;
}, TypeError);
codes.ERR_INVALID_PACKAGE_CONFIG = createError('ERR_INVALID_PACKAGE_CONFIG', (path, base, message) => {
return `Invalid package config ${path}${base ? ` while importing ${base}` : ''}${message ? `. ${message}` : ''}`;
}, Error);
codes.ERR_INVALID_PACKAGE_TARGET = createError('ERR_INVALID_PACKAGE_TARGET', (pkgPath, key, target, isImport = false, base = undefined) => {
const relError = typeof target === 'string' && !isImport && target.length > 0 && !target.startsWith('./');
if (key === '.') {
_assert()(isImport === false);
return `Invalid "exports" main target ${JSON.stringify(target)} defined ` + `in the package config ${pkgPath}package.json${base ? ` imported from ${base}` : ''}${relError ? '; targets must start with "./"' : ''}`;
}
return `Invalid "${isImport ? 'imports' : 'exports'}" target ${JSON.stringify(target)} defined for '${key}' in the package config ${pkgPath}package.json${base ? ` imported from ${base}` : ''}${relError ? '; targets must start with "./"' : ''}`;
}, Error);
codes.ERR_MODULE_NOT_FOUND = createError('ERR_MODULE_NOT_FOUND', (path, base, type = 'package') => {
return `Cannot find ${type} '${path}' imported from ${base}`;
}, Error);
codes.ERR_PACKAGE_IMPORT_NOT_DEFINED = createError('ERR_PACKAGE_IMPORT_NOT_DEFINED', (specifier, packagePath, base) => {
return `Package import specifier "${specifier}" is not defined${packagePath ? ` in package ${packagePath}package.json` : ''} imported from ${base}`;
}, TypeError);
codes.ERR_PACKAGE_PATH_NOT_EXPORTED = createError('ERR_PACKAGE_PATH_NOT_EXPORTED', (pkgPath, subpath, base = undefined) => {
if (subpath === '.') return `No "exports" main defined in ${pkgPath}package.json${base ? ` imported from ${base}` : ''}`;
return `Package subpath '${subpath}' is not defined by "exports" in ${pkgPath}package.json${base ? ` imported from ${base}` : ''}`;
}, Error);
codes.ERR_UNSUPPORTED_DIR_IMPORT = createError('ERR_UNSUPPORTED_DIR_IMPORT', "Directory import '%s' is not supported " + 'resolving ES modules imported from %s', Error);
codes.ERR_UNKNOWN_FILE_EXTENSION = createError('ERR_UNKNOWN_FILE_EXTENSION', 'Unknown file extension "%s" for %s', TypeError);
codes.ERR_INVALID_ARG_VALUE = createError('ERR_INVALID_ARG_VALUE', (name, value, reason = 'is invalid') => {
let inspected = (0, _util().inspect)(value);
if (inspected.length > 128) {
inspected = `${inspected.slice(0, 128)}...`;
}
const type = name.includes('.') ? 'property' : 'argument';
return `The ${type} '${name}' ${reason}. Received ${inspected}`;
}, TypeError);
codes.ERR_UNSUPPORTED_ESM_URL_SCHEME = createError('ERR_UNSUPPORTED_ESM_URL_SCHEME', url => {
let message = 'Only file and data URLs are supported by the default ESM loader';
if (isWindows && url.protocol.length === 2) {
message += '. On Windows, absolute paths must be valid file:// URLs';
}
message += `. Received protocol '${url.protocol}'`;
return message;
}, Error);
function createError(sym, value, def) {
messages.set(sym, value);
return makeNodeErrorWithCode(def, sym);
}
function makeNodeErrorWithCode(Base, key) {
return NodeError;
function NodeError(...args) {
const limit = Error.stackTraceLimit;
if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = 0;
const error = new Base();
if (isErrorStackTraceLimitWritable()) Error.stackTraceLimit = limit;
const message = getMessage(key, args, error);
Object.defineProperty(error, 'message', {
value: message,
enumerable: false,
writable: true,
configurable: true
});
Object.defineProperty(error, 'toString', {
value() {
return `${this.name} [${key}]: ${this.message}`;
},
enumerable: false,
writable: true,
configurable: true
});
addCodeToName(error, Base.name, key);
error.code = key;
return error;
}
}
const addCodeToName = hideStackFrames(function (error, name, code) {
error = captureLargerStackTrace(error);
error.name = `${name} [${code}]`;
error.stack;
if (name === 'SystemError') {
Object.defineProperty(error, 'name', {
value: name,
enumerable: false,
writable: true,
configurable: true
});
} else {
delete error.name;
}
});
function isErrorStackTraceLimitWritable() {
const desc = Object.getOwnPropertyDescriptor(Error, 'stackTraceLimit');
if (desc === undefined) {
return Object.isExtensible(Error);
}
return own$1.call(desc, 'writable') ? desc.writable : desc.set !== undefined;
}
function hideStackFrames(fn) {
const hidden = nodeInternalPrefix + fn.name;
Object.defineProperty(fn, 'name', {
value: hidden
});
return fn;
}
const captureLargerStackTrace = hideStackFrames(function (error) {
const stackTraceLimitIsWritable = isErrorStackTraceLimitWritable();
if (stackTraceLimitIsWritable) {
userStackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = Number.POSITIVE_INFINITY;
}
Error.captureStackTrace(error);
if (stackTraceLimitIsWritable) Error.stackTraceLimit = userStackTraceLimit;
return error;
});
function getMessage(key, args, self) {
const message = messages.get(key);
if (typeof message === 'function') {
_assert()(message.length <= args.length, `Code: ${key}; The provided arguments length (${args.length}) does not ` + `match the required ones (${message.length}).`);
return Reflect.apply(message, self, args);
}
const expectedLength = (message.match(/%[dfijoOs]/g) || []).length;
_assert()(expectedLength === args.length, `Code: ${key}; The provided arguments length (${args.length}) does not ` + `match the required ones (${expectedLength}).`);
if (args.length === 0) return message;
args.unshift(message);
return Reflect.apply(_util().format, null, args);
}
const {
ERR_UNKNOWN_FILE_EXTENSION
} = codes;
const extensionFormatMap = {
__proto__: null,
'.cjs': 'commonjs',
'.js': 'module',
'.mjs': 'module'
};
function defaultGetFormat(url) {
if (url.startsWith('node:')) {
return {
format: 'builtin'
};
}
const parsed = new (_url().URL)(url);
if (parsed.protocol === 'data:') {
const {
1: mime
} = /^([^/]+\/[^;,]+)[^,]*?(;base64)?,/.exec(parsed.pathname) || [null, null];
const format = mime === 'text/javascript' ? 'module' : null;
return {
format
};
}
if (parsed.protocol === 'file:') {
const ext = _path().extname(parsed.pathname);
let format;
if (ext === '.js') {
format = getPackageType(parsed.href) === 'module' ? 'module' : 'commonjs';
} else {
format = extensionFormatMap[ext];
}
if (!format) {
throw new ERR_UNKNOWN_FILE_EXTENSION(ext, (0, _url().fileURLToPath)(url));
}
return {
format: format || null
};
}
return {
format: null
};
}
const listOfBuiltins = builtins();
const {
ERR_INVALID_MODULE_SPECIFIER,
ERR_INVALID_PACKAGE_CONFIG,
ERR_INVALID_PACKAGE_TARGET,
ERR_MODULE_NOT_FOUND,
ERR_PACKAGE_IMPORT_NOT_DEFINED,
ERR_PACKAGE_PATH_NOT_EXPORTED,
ERR_UNSUPPORTED_DIR_IMPORT,
ERR_UNSUPPORTED_ESM_URL_SCHEME,
ERR_INVALID_ARG_VALUE
} = codes;
const own = {}.hasOwnProperty;
const DEFAULT_CONDITIONS = Object.freeze(['node', 'import']);
const DEFAULT_CONDITIONS_SET = new Set(DEFAULT_CONDITIONS);
const invalidSegmentRegEx = /(^|\\|\/)(\.\.?|node_modules)(\\|\/|$)/;
const patternRegEx = /\*/g;
const encodedSepRegEx = /%2f|%2c/i;
const emittedPackageWarnings = new Set();
const packageJsonCache = new Map();
function emitFolderMapDeprecation(match, pjsonUrl, isExports, base) {
const pjsonPath = (0, _url().fileURLToPath)(pjsonUrl);
if (emittedPackageWarnings.has(pjsonPath + '|' + match)) return;
emittedPackageWarnings.add(pjsonPath + '|' + match);
process.emitWarning(`Use of deprecated folder mapping "${match}" in the ${isExports ? '"exports"' : '"imports"'} field module resolution of the package at ${pjsonPath}${base ? ` imported from ${(0, _url().fileURLToPath)(base)}` : ''}.\n` + `Update this package.json to use a subpath pattern like "${match}*".`, 'DeprecationWarning', 'DEP0148');
}
function emitLegacyIndexDeprecation(url, packageJsonUrl, base, main) {
const {
format
} = defaultGetFormat(url.href);
if (format !== 'module') return;
const path = (0, _url().fileURLToPath)(url.href);
const pkgPath = (0, _url().fileURLToPath)(new (_url().URL)('.', packageJsonUrl));
const basePath = (0, _url().fileURLToPath)(base);
if (main) process.emitWarning(`Package ${pkgPath} has a "main" field set to ${JSON.stringify(main)}, ` + `excluding the full filename and extension to the resolved file at "${path.slice(pkgPath.length)}", imported from ${basePath}.\n Automatic extension resolution of the "main" field is` + 'deprecated for ES modules.', 'DeprecationWarning', 'DEP0151');else process.emitWarning(`No "main" or "exports" field defined in the package.json for ${pkgPath} resolving the main entry point "${path.slice(pkgPath.length)}", imported from ${basePath}.\nDefault "index" lookups for the main are deprecated for ES modules.`, 'DeprecationWarning', 'DEP0151');
}
function getConditionsSet(conditions) {
if (conditions !== undefined && conditions !== DEFAULT_CONDITIONS) {
if (!Array.isArray(conditions)) {
throw new ERR_INVALID_ARG_VALUE('conditions', conditions, 'expected an array');
}
return new Set(conditions);
}
return DEFAULT_CONDITIONS_SET;
}
function tryStatSync(path) {
try {
return (0, _fs().statSync)(path);
} catch (_unused) {
return new (_fs().Stats)();
}
}
function getPackageConfig(path, specifier, base) {
const existing = packageJsonCache.get(path);
if (existing !== undefined) {
return existing;
}
const source = reader.read(path).string;
if (source === undefined) {
const packageConfig = {
pjsonPath: path,
exists: false,
main: undefined,
name: undefined,
type: 'none',
exports: undefined,
imports: undefined
};
packageJsonCache.set(path, packageConfig);
return packageConfig;
}
let packageJson;
try {
packageJson = JSON.parse(source);
} catch (error) {
throw new ERR_INVALID_PACKAGE_CONFIG(path, (base ? `"${specifier}" from ` : '') + (0, _url().fileURLToPath)(base || specifier), error.message);
}
const {
exports,
imports,
main,
name,
type
} = packageJson;
const packageConfig = {
pjsonPath: path,
exists: true,
main: typeof main === 'string' ? main : undefined,
name: typeof name === 'string' ? name : undefined,
type: type === 'module' || type === 'commonjs' ? type : 'none',
exports,
imports: imports && typeof imports === 'object' ? imports : undefined
};
packageJsonCache.set(path, packageConfig);
return packageConfig;
}
function getPackageScopeConfig(resolved) {
let packageJsonUrl = new (_url().URL)('./package.json', resolved);
while (true) {
const packageJsonPath = packageJsonUrl.pathname;
if (packageJsonPath.endsWith('node_modules/package.json')) break;
const packageConfig = getPackageConfig((0, _url().fileURLToPath)(packageJsonUrl), resolved);
if (packageConfig.exists) return packageConfig;
const lastPackageJsonUrl = packageJsonUrl;
packageJsonUrl = new (_url().URL)('../package.json', packageJsonUrl);
if (packageJsonUrl.pathname === lastPackageJsonUrl.pathname) break;
}
const packageJsonPath = (0, _url().fileURLToPath)(packageJsonUrl);
const packageConfig = {
pjsonPath: packageJsonPath,
exists: false,
main: undefined,
name: undefined,
type: 'none',
exports: undefined,
imports: undefined
};
packageJsonCache.set(packageJsonPath, packageConfig);
return packageConfig;
}
function fileExists(url) {
return tryStatSync((0, _url().fileURLToPath)(url)).isFile();
}
function legacyMainResolve(packageJsonUrl, packageConfig, base) {
let guess;
if (packageConfig.main !== undefined) {
guess = new (_url().URL)(`./${packageConfig.main}`, packageJsonUrl);
if (fileExists(guess)) return guess;
const tries = [`./${packageConfig.main}.js`, `./${packageConfig.main}.json`, `./${packageConfig.main}.node`, `./${packageConfig.main}/index.js`, `./${packageConfig.main}/index.json`, `./${packageConfig.main}/index.node`];
let i = -1;
while (++i < tries.length) {
guess = new (_url().URL)(tries[i], packageJsonUrl);
if (fileExists(guess)) break;
guess = undefined;
}
if (guess) {
emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
return guess;
}
}
const tries = ['./index.js', './index.json', './index.node'];
let i = -1;
while (++i < tries.length) {
guess = new (_url().URL)(tries[i], packageJsonUrl);
if (fileExists(guess)) break;
guess = undefined;
}
if (guess) {
emitLegacyIndexDeprecation(guess, packageJsonUrl, base, packageConfig.main);
return guess;
}
throw new ERR_MODULE_NOT_FOUND((0, _url().fileURLToPath)(new (_url().URL)('.', packageJsonUrl)), (0, _url().fileURLToPath)(base));
}
function finalizeResolution(resolved, base) {
if (encodedSepRegEx.test(resolved.pathname)) throw new ERR_INVALID_MODULE_SPECIFIER(resolved.pathname, 'must not include encoded "/" or "\\" characters', (0, _url().fileURLToPath)(base));
const path = (0, _url().fileURLToPath)(resolved);
const stats = tryStatSync(path.endsWith('/') ? path.slice(-1) : path);
if (stats.isDirectory()) {
const error = new ERR_UNSUPPORTED_DIR_IMPORT(path, (0, _url().fileURLToPath)(base));
error.url = String(resolved);
throw error;
}
if (!stats.isFile()) {
throw new ERR_MODULE_NOT_FOUND(path || resolved.pathname, base && (0, _url().fileURLToPath)(base), 'module');
}
return resolved;
}
function throwImportNotDefined(specifier, packageJsonUrl, base) {
throw new ERR_PACKAGE_IMPORT_NOT_DEFINED(specifier, packageJsonUrl && (0, _url().fileURLToPath)(new (_url().URL)('.', packageJsonUrl)), (0, _url().fileURLToPath)(base));
}
function throwExportsNotFound(subpath, packageJsonUrl, base) {
throw new ERR_PACKAGE_PATH_NOT_EXPORTED((0, _url().fileURLToPath)(new (_url().URL)('.', packageJsonUrl)), subpath, base && (0, _url().fileURLToPath)(base));
}
function throwInvalidSubpath(subpath, packageJsonUrl, internal, base) {
const reason = `request is not a valid subpath for the "${internal ? 'imports' : 'exports'}" resolution of ${(0, _url().fileURLToPath)(packageJsonUrl)}`;
throw new ERR_INVALID_MODULE_SPECIFIER(subpath, reason, base && (0, _url().fileURLToPath)(base));
}
function throwInvalidPackageTarget(subpath, target, packageJsonUrl, internal, base) {
target = typeof target === 'object' && target !== null ? JSON.stringify(target, null, '') : `${target}`;
throw new ERR_INVALID_PACKAGE_TARGET((0, _url().fileURLToPath)(new (_url().URL)('.', packageJsonUrl)), subpath, target, internal, base && (0, _url().fileURLToPath)(base));
}
function resolvePackageTargetString(target, subpath, match, packageJsonUrl, base, pattern, internal, conditions) {
if (subpath !== '' && !pattern && target[target.length - 1] !== '/') throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base);
if (!target.startsWith('./')) {
if (internal && !target.startsWith('../') && !target.startsWith('/')) {
let isURL = false;
try {
new (_url().URL)(target);
isURL = true;
} catch (_unused2) {}
if (!isURL) {
const exportTarget = pattern ? target.replace(patternRegEx, subpath) : target + subpath;
return packageResolve(exportTarget, packageJsonUrl, conditions);
}
}
throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base);
}
if (invalidSegmentRegEx.test(target.slice(2))) throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base);
const resolved = new (_url().URL)(target, packageJsonUrl);
const resolvedPath = resolved.pathname;
const packagePath = new (_url().URL)('.', packageJsonUrl).pathname;
if (!resolvedPath.startsWith(packagePath)) throwInvalidPackageTarget(match, target, packageJsonUrl, internal, base);
if (subpath === '') return resolved;
if (invalidSegmentRegEx.test(subpath)) throwInvalidSubpath(match + subpath, packageJsonUrl, internal, base);
if (pattern) return new (_url().URL)(resolved.href.replace(patternRegEx, subpath));
return new (_url().URL)(subpath, resolved);
}
function isArrayIndex(key) {
const keyNumber = Number(key);
if (`${keyNumber}` !== key) return false;
return keyNumber >= 0 && keyNumber < 0xffffffff;
}
function resolvePackageTarget(packageJsonUrl, target, subpath, packageSubpath, base, pattern, internal, conditions) {
if (typeof target === 'string') {
return resolvePackageTargetString(target, subpath, packageSubpath, packageJsonUrl, base, pattern, internal, conditions);
}
if (Array.isArray(target)) {
const targetList = target;
if (targetList.length === 0) return null;
let lastException;
let i = -1;
while (++i < targetList.length) {
const targetItem = targetList[i];
let resolved;
try {
resolved = resolvePackageTarget(packageJsonUrl, targetItem, subpath, packageSubpath, base, pattern, internal, conditions);
} catch (error) {
lastException = error;
if (error.code === 'ERR_INVALID_PACKAGE_TARGET') continue;
throw error;
}
if (resolved === undefined) continue;
if (resolved === null) {
lastException = null;
continue;
}
return resolved;
}
if (lastException === undefined || lastException === null) {
return lastException;
}
throw lastException;
}
if (typeof target === 'object' && target !== null) {
const keys = Object.getOwnPropertyNames(target);
let i = -1;
while (++i < keys.length) {
const key = keys[i];
if (isArrayIndex(key)) {
throw new ERR_INVALID_PACKAGE_CONFIG((0, _url().fileURLToPath)(packageJsonUrl), base, '"exports" cannot contain numeric property keys.');
}
}
i = -1;
while (++i < keys.length) {
const key = keys[i];
if (key === 'default' || conditions && conditions.has(key)) {
const conditionalTarget = target[key];
const resolved = resolvePackageTarget(packageJsonUrl, conditionalTarget, subpath, packageSubpath, base, pattern, internal, conditions);
if (resolved === undefined) continue;
return resolved;
}
}
return undefined;
}
if (target === null) {
return null;
}
throwInvalidPackageTarget(packageSubpath, target, packageJsonUrl, internal, base);
}
function isConditionalExportsMainSugar(exports, packageJsonUrl, base) {
if (typeof exports === 'string' || Array.isArray(exports)) return true;
if (typeof exports !== 'object' || exports === null) return false;
const keys = Object.getOwnPropertyNames(exports);
let isConditionalSugar = false;
let i = 0;
let j = -1;
while (++j < keys.length) {
const key = keys[j];
const curIsConditionalSugar = key === '' || key[0] !== '.';
if (i++ === 0) {
isConditionalSugar = curIsConditionalSugar;
} else if (isConditionalSugar !== curIsConditionalSugar) {
throw new ERR_INVALID_PACKAGE_CONFIG((0, _url().fileURLToPath)(packageJsonUrl), base, '"exports" cannot contain some keys starting with \'.\' and some not.' + ' The exports object must either be an object of package subpath keys' + ' or an object of main entry condition name keys only.');
}
}
return isConditionalSugar;
}
function packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions) {
let exports = packageConfig.exports;
if (isConditionalExportsMainSugar(exports, packageJsonUrl, base)) exports = {
'.': exports
};
if (own.call(exports, packageSubpath)) {
const target = exports[packageSubpath];
const resolved = resolvePackageTarget(packageJsonUrl, target, '', packageSubpath, base, false, false, conditions);
if (resolved === null || resolved === undefined) throwExportsNotFound(packageSubpath, packageJsonUrl, base);
return {
resolved,
exact: true
};
}
let bestMatch = '';
const keys = Object.getOwnPropertyNames(exports);
let i = -1;
while (++i < keys.length) {
const key = keys[i];
if (key[key.length - 1] === '*' && packageSubpath.startsWith(key.slice(0, -1)) && packageSubpath.length >= key.length && key.length > bestMatch.length) {
bestMatch = key;
} else if (key[key.length - 1] === '/' && packageSubpath.startsWith(key) && key.length > bestMatch.length) {
bestMatch = key;
}
}
if (bestMatch) {
const target = exports[bestMatch];
const pattern = bestMatch[bestMatch.length - 1] === '*';
const subpath = packageSubpath.slice(bestMatch.length - (pattern ? 1 : 0));
const resolved = resolvePackageTarget(packageJsonUrl, target, subpath, bestMatch, base, pattern, false, conditions);
if (resolved === null || resolved === undefined) throwExportsNotFound(packageSubpath, packageJsonUrl, base);
if (!pattern) emitFolderMapDeprecation(bestMatch, packageJsonUrl, true, base);
return {
resolved,
exact: pattern
};
}
throwExportsNotFound(packageSubpath, packageJsonUrl, base);
}
function packageImportsResolve(name, base, conditions) {
if (name === '#' || name.startsWith('#/')) {
const reason = 'is not a valid internal imports specifier name';
throw new ERR_INVALID_MODULE_SPECIFIER(name, reason, (0, _url().fileURLToPath)(base));
}
let packageJsonUrl;
const packageConfig = getPackageScopeConfig(base);
if (packageConfig.exists) {
packageJsonUrl = (0, _url().pathToFileURL)(packageConfig.pjsonPath);
const imports = packageConfig.imports;
if (imports) {
if (own.call(imports, name)) {
const resolved = resolvePackageTarget(packageJsonUrl, imports[name], '', name, base, false, true, conditions);
if (resolved !== null) return {
resolved,
exact: true
};
} else {
let bestMatch = '';
const keys = Object.getOwnPropertyNames(imports);
let i = -1;
while (++i < keys.length) {
const key = keys[i];
if (key[key.length - 1] === '*' && name.startsWith(key.slice(0, -1)) && name.length >= key.length && key.length > bestMatch.length) {
bestMatch = key;
} else if (key[key.length - 1] === '/' && name.startsWith(key) && key.length > bestMatch.length) {
bestMatch = key;
}
}
if (bestMatch) {
const target = imports[bestMatch];
const pattern = bestMatch[bestMatch.length - 1] === '*';
const subpath = name.slice(bestMatch.length - (pattern ? 1 : 0));
const resolved = resolvePackageTarget(packageJsonUrl, target, subpath, bestMatch, base, pattern, true, conditions);
if (resolved !== null) {
if (!pattern) emitFolderMapDeprecation(bestMatch, packageJsonUrl, false, base);
return {
resolved,
exact: pattern
};
}
}
}
}
}
throwImportNotDefined(name, packageJsonUrl, base);
}
function getPackageType(url) {
const packageConfig = getPackageScopeConfig(url);
return packageConfig.type;
}
function parsePackageName(specifier, base) {
let separatorIndex = specifier.indexOf('/');
let validPackageName = true;
let isScoped = false;
if (specifier[0] === '@') {
isScoped = true;
if (separatorIndex === -1 || specifier.length === 0) {
validPackageName = false;
} else {
separatorIndex = specifier.indexOf('/', separatorIndex + 1);
}
}
const packageName = separatorIndex === -1 ? specifier : specifier.slice(0, separatorIndex);
let i = -1;
while (++i < packageName.length) {
if (packageName[i] === '%' || packageName[i] === '\\') {
validPackageName = false;
break;
}
}
if (!validPackageName) {
throw new ERR_INVALID_MODULE_SPECIFIER(specifier, 'is not a valid package name', (0, _url().fileURLToPath)(base));
}
const packageSubpath = '.' + (separatorIndex === -1 ? '' : specifier.slice(separatorIndex));
return {
packageName,
packageSubpath,
isScoped
};
}
function packageResolve(specifier, base, conditions) {
const {
packageName,
packageSubpath,
isScoped
} = parsePackageName(specifier, base);
const packageConfig = getPackageScopeConfig(base);
if (packageConfig.exists) {
const packageJsonUrl = (0, _url().pathToFileURL)(packageConfig.pjsonPath);
if (packageConfig.name === packageName && packageConfig.exports !== undefined && packageConfig.exports !== null) {
return packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions).resolved;
}
}
let packageJsonUrl = new (_url().URL)('./node_modules/' + packageName + '/package.json', base);
let packageJsonPath = (0, _url().fileURLToPath)(packageJsonUrl);
let lastPath;
do {
const stat = tryStatSync(packageJsonPath.slice(0, -13));
if (!stat.isDirectory()) {
lastPath = packageJsonPath;
packageJsonUrl = new (_url().URL)((isScoped ? '../../../../node_modules/' : '../../../node_modules/') + packageName + '/package.json', packageJsonUrl);
packageJsonPath = (0, _url().fileURLToPath)(packageJsonUrl);
continue;
}
const packageConfig = getPackageConfig(packageJsonPath, specifier, base);
if (packageConfig.exports !== undefined && packageConfig.exports !== null) return packageExportsResolve(packageJsonUrl, packageSubpath, packageConfig, base, conditions).resolved;
if (packageSubpath === '.') return legacyMainResolve(packageJsonUrl, packageConfig, base);
return new (_url().URL)(packageSubpath, packageJsonUrl);
} while (packageJsonPath.length !== lastPath.length);
throw new ERR_MODULE_NOT_FOUND(packageName, (0, _url().fileURLToPath)(base));
}
function isRelativeSpecifier(specifier) {
if (specifier[0] === '.') {
if (specifier.length === 1 || specifier[1] === '/') return true;
if (specifier[1] === '.' && (specifier.length === 2 || specifier[2] === '/')) {
return true;
}
}
return false;
}
function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
if (specifier === '') return false;
if (specifier[0] === '/') return true;
return isRelativeSpecifier(specifier);
}
function moduleResolve(specifier, base, conditions) {
let resolved;
if (shouldBeTreatedAsRelativeOrAbsolutePath(specifier)) {
resolved = new (_url().URL)(specifier, base);
} else if (specifier[0] === '#') {
({
resolved
} = packageImportsResolve(specifier, base, conditions));
} else {
try {
resolved = new (_url().URL)(specifier);
} catch (_unused3) {
resolved = packageResolve(specifier, base, conditions);
}
}
return finalizeResolution(resolved, base);
}
function defaultResolve(specifier, context = {}) {
const {
parentURL
} = context;
let parsed;
try {
parsed = new (_url().URL)(specifier);
if (parsed.protocol === 'data:') {
return {
url: specifier
};
}
} catch (_unused4) {}
if (parsed && parsed.protocol === 'node:') return {
url: specifier
};
if (parsed && parsed.protocol !== 'file:' && parsed.protocol !== 'data:') throw new ERR_UNSUPPORTED_ESM_URL_SCHEME(parsed);
if (listOfBuiltins.includes(specifier)) {
return {
url: 'node:' + specifier
};
}
if (parentURL.startsWith('data:')) {
new (_url().URL)(specifier, parentURL);
}
const conditions = getConditionsSet(context.conditions);
let url = moduleResolve(specifier, new (_url().URL)(parentURL), conditions);
const urlPath = (0, _url().fileURLToPath)(url);
const real = (0, _fs().realpathSync)(urlPath);
const old = url;
url = (0, _url().pathToFileURL)(real + (urlPath.endsWith(_path().sep) ? '/' : ''));
url.search = old.search;
url.hash = old.hash;
return {
url: `${url}`
};
}
function resolve(_x, _x2) {
return _resolve.apply(this, arguments);
}
function _resolve() {
_resolve = _asyncToGenerator(function* (specifier, parent) {
if (!parent) {
throw new Error('Please pass `parent`: `import-meta-resolve` cannot ponyfill that');
}
try {
return defaultResolve(specifier, {
parentURL: parent
}).url;
} catch (error) {
return error.code === 'ERR_UNSUPPORTED_DIR_IMPORT' ? error.url : Promise.reject(error);
}
});
return _resolve.apply(this, arguments);
}
0 && 0;
\ No newline at end of file
(The MIT License)
Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca>
Copyright (c) 2018-2021 Josh Junon
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the 'Software'), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# debug
[![Build Status](https://travis-ci.org/debug-js/debug.svg?branch=master)](https://travis-ci.org/debug-js/debug) [![Coverage Status](https://coveralls.io/repos/github/debug-js/debug/badge.svg?branch=master)](https://coveralls.io/github/debug-js/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers)
[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors)
<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">
A tiny JavaScript debugging utility modelled after Node.js core's debugging
technique. Works in Node.js and web browsers.
## Installation
```bash
$ npm install debug
```
## Usage
`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole.
Example [_app.js_](./examples/node/app.js):
```js
var debug = require('debug')('http')
, http = require('http')
, name = 'My App';
// fake app
debug('booting %o', name);
http.createServer(function(req, res){
debug(req.method + ' ' + req.url);
res.end('hello\n');
}).listen(3000, function(){
debug('listening');
});
// fake worker of some kind
require('./worker');
```
Example [_worker.js_](./examples/node/worker.js):
```js
var a = require('debug')('worker:a')
, b = require('debug')('worker:b');
function work() {
a('doing lots of uninteresting work');
setTimeout(work, Math.random() * 1000);
}
work();
function workb() {
b('doing some work');
setTimeout(workb, Math.random() * 2000);
}
workb();
```
The `DEBUG` environment variable is then used to enable these based on space or
comma-delimited names.
Here are some examples:
<img width="647" alt="screen shot 2017-08-08 at 12 53 04 pm" src="https://user-images.githubusercontent.com/71256/29091703-a6302cdc-7c38-11e7-8304-7c0b3bc600cd.png">
<img width="647" alt="screen shot 2017-08-08 at 12 53 38 pm" src="https://user-images.githubusercontent.com/71256/29091700-a62a6888-7c38-11e7-800b-db911291ca2b.png">
<img width="647" alt="screen shot 2017-08-08 at 12 53 25 pm" src="https://user-images.githubusercontent.com/71256/29091701-a62ea114-7c38-11e7-826a-2692bedca740.png">
#### Windows command prompt notes
##### CMD
On Windows the environment variable is set using the `set` command.
```cmd
set DEBUG=*,-not_this
```
Example:
```cmd
set DEBUG=* & node app.js
```
##### PowerShell (VS Code default)
PowerShell uses different syntax to set environment variables.
```cmd
$env:DEBUG = "*,-not_this"
```
Example:
```cmd
$env:DEBUG='app';node app.js
```
Then, run the program to be debugged as usual.
npm script example:
```js
"windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js",
```
## Namespace Colors
Every debug instance has a color generated for it based on its namespace name.
This helps when visually parsing the debug output to identify which debug instance
a debug line belongs to.
#### Node.js
In Node.js, colors are enabled when stderr is a TTY. You also _should_ install
the [`supports-color`](https://npmjs.org/supports-color) module alongside debug,
otherwise debug will only use a small handful of basic colors.
<img width="521" src="https://user-images.githubusercontent.com/71256/29092181-47f6a9e6-7c3a-11e7-9a14-1928d8a711cd.png">
#### Web Browser
Colors are also enabled on "Web Inspectors" that understand the `%c` formatting
option. These are WebKit web inspectors, Firefox ([since version
31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/))
and the Firebug plugin for Firefox (any version).
<img width="524" src="https://user-images.githubusercontent.com/71256/29092033-b65f9f2e-7c39-11e7-8e32-f6f0d8e865c1.png">
## Millisecond diff
When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.
<img width="647" src="https://user-images.githubusercontent.com/71256/29091486-fa38524c-7c37-11e7-895f-e7ec8e1039b6.png">
When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below:
<img width="647" src="https://user-images.githubusercontent.com/71256/29091956-6bd78372-7c39-11e7-8c55-c948396d6edd.png">
## Conventions
If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output.
## Wildcards
The `*` character may be used as a wildcard. Suppose for example your library has
debuggers named "connect:bodyParser", "connect:compress", "connect:session",
instead of listing all three with
`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do
`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.
You can also exclude specific debuggers by prefixing them with a "-" character.
For example, `DEBUG=*,-connect:*` would include all debuggers except those
starting with "connect:".
## Environment Variables
When running through Node.js, you can set a few environment variables that will
change the behavior of the debug logging:
| Name | Purpose |
|-----------|-------------------------------------------------|
| `DEBUG` | Enables/disables specific debugging namespaces. |
| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). |
| `DEBUG_COLORS`| Whether or not to use colors in the debug output. |
| `DEBUG_DEPTH` | Object inspection depth. |
| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. |
__Note:__ The environment variables beginning with `DEBUG_` end up being
converted into an Options object that gets used with `%o`/`%O` formatters.
See the Node.js documentation for
[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options)
for the complete list.
## Formatters
Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting.
Below are the officially supported formatters:
| Formatter | Representation |
|-----------|----------------|
| `%O` | Pretty-print an Object on multiple lines. |
| `%o` | Pretty-print an Object all on a single line. |
| `%s` | String. |
| `%d` | Number (both integer and float). |
| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. |
| `%%` | Single percent sign ('%'). This does not consume an argument. |
### Custom formatters
You can add custom formatters by extending the `debug.formatters` object.
For example, if you wanted to add support for rendering a Buffer as hex with
`%h`, you could do something like:
```js
const createDebug = require('debug')
createDebug.formatters.h = (v) => {
return v.toString('hex')
}
// …elsewhere
const debug = createDebug('foo')
debug('this is hex: %h', new Buffer('hello world'))
// foo this is hex: 68656c6c6f20776f726c6421 +0ms
```
## Browser Support
You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify),
or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest),
if you don't want to build it yourself.
Debug's enable state is currently persisted by `localStorage`.
Consider the situation shown below where you have `worker:a` and `worker:b`,
and wish to debug both. You can enable this using `localStorage.debug`:
```js
localStorage.debug = 'worker:*'
```
And then refresh the page.
```js
a = debug('worker:a');
b = debug('worker:b');
setInterval(function(){
a('doing some work');
}, 1000);
setInterval(function(){
b('doing some work');
}, 1200);
```
In Chromium-based web browsers (e.g. Brave, Chrome, and Electron), the JavaScript console will—by default—only show messages logged by `debug` if the "Verbose" log level is _enabled_.
<img width="647" src="https://user-images.githubusercontent.com/7143133/152083257-29034707-c42c-4959-8add-3cee850e6fcf.png">
## Output streams
By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method:
Example [_stdout.js_](./examples/node/stdout.js):
```js
var debug = require('debug');
var error = debug('app:error');
// by default stderr is used
error('goes to stderr!');
var log = debug('app:log');
// set this namespace to log via console.log
log.log = console.log.bind(console); // don't forget to bind to console!
log('goes to stdout');
error('still goes to stderr!');
// set all output to go via console.info
// overrides all per-namespace log settings
debug.log = console.info.bind(console);
error('now goes to stdout via console.info');
log('still goes to stdout, but via console.info now');
```
## Extend
You can simply extend debugger
```js
const log = require('debug')('auth');
//creates new debug instance with extended namespace
const logSign = log.extend('sign');
const logLogin = log.extend('login');
log('hello'); // auth hello
logSign('hello'); //auth:sign hello
logLogin('hello'); //auth:login hello
```
## Set dynamically
You can also enable debug dynamically by calling the `enable()` method :
```js
let debug = require('debug');
console.log(1, debug.enabled('test'));
debug.enable('test');
console.log(2, debug.enabled('test'));
debug.disable();
console.log(3, debug.enabled('test'));
```
print :
```
1 false
2 true
3 false
```
Usage :
`enable(namespaces)`
`namespaces` can include modes separated by a colon and wildcards.
Note that calling `enable()` completely overrides previously set DEBUG variable :
```
$ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))'
=> false
```
`disable()`
Will disable all namespaces. The functions returns the namespaces currently
enabled (and skipped). This can be useful if you want to disable debugging
temporarily without knowing what was enabled to begin with.
For example:
```js
let debug = require('debug');
debug.enable('foo:*,-foo:bar');
let namespaces = debug.disable();
debug.enable(namespaces);
```
Note: There is no guarantee that the string will be identical to the initial
enable string, but semantically they will be identical.
## Checking whether a debug target is enabled
After you've created a debug instance, you can determine whether or not it is
enabled by checking the `enabled` property:
```javascript
const debug = require('debug')('http');
if (debug.enabled) {
// do stuff...
}
```
You can also manually toggle this property to force the debug instance to be
enabled or disabled.
## Usage in child processes
Due to the way `debug` detects if the output is a TTY or not, colors are not shown in child processes when `stderr` is piped. A solution is to pass the `DEBUG_COLORS=1` environment variable to the child process.
For example:
```javascript
worker = fork(WORKER_WRAP_PATH, [workerPath], {
stdio: [
/* stdin: */ 0,
/* stdout: */ 'pipe',
/* stderr: */ 'pipe',
'ipc',
],
env: Object.assign({}, process.env, {
DEBUG_COLORS: 1 // without this settings, colors won't be shown
}),
});
worker.stderr.pipe(process.stderr, { end: false });
```
## Authors
- TJ Holowaychuk
- Nathan Rajlich
- Andrew Rhyne
- Josh Junon
## Backers
Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)]
<a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a>
## Sponsors
Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)]
<a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a>
<a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a>
## License
(The MIT License)
Copyright (c) 2014-2017 TJ Holowaychuk &lt;tj@vision-media.ca&gt;
Copyright (c) 2018-2021 Josh Junon
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
"name": "debug",
"version": "4.3.4",
"repository": {
"type": "git",
"url": "git://github.com/debug-js/debug.git"
},
"description": "Lightweight debugging utility for Node.js and the browser",
"keywords": [
"debug",
"log",
"debugger"
],
"files": [
"src",
"LICENSE",
"README.md"
],
"author": "Josh Junon <josh.junon@protonmail.com>",
"contributors": [
"TJ Holowaychuk <tj@vision-media.ca>",
"Nathan Rajlich <nathan@tootallnate.net> (http://n8.io)",
"Andrew Rhyne <rhyneandrew@gmail.com>"
],
"license": "MIT",
"scripts": {
"lint": "xo",
"test": "npm run test:node && npm run test:browser && npm run lint",
"test:node": "istanbul cover _mocha -- test.js",
"test:browser": "karma start --single-run",
"test:coverage": "cat ./coverage/lcov.info | coveralls"
},
"dependencies": {
"ms": "2.1.2"
},
"devDependencies": {
"brfs": "^2.0.1",
"browserify": "^16.2.3",
"coveralls": "^3.0.2",
"istanbul": "^0.4.5",
"karma": "^3.1.4",
"karma-browserify": "^6.0.0",
"karma-chrome-launcher": "^2.2.0",
"karma-mocha": "^1.3.0",
"mocha": "^5.2.0",
"mocha-lcov-reporter": "^1.2.0",
"xo": "^0.23.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
},
"main": "./src/index.js",
"browser": "./src/browser.js",
"engines": {
"node": ">=6.0"
}
}
/* eslint-env browser */
/**
* This is the web browser implementation of `debug()`.
*/
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
exports.destroy = (() => {
let warned = false;
return () => {
if (!warned) {
warned = true;
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
};
})();
/**
* Colors.
*/
exports.colors = [
'#0000CC',
'#0000FF',
'#0033CC',
'#0033FF',
'#0066CC',
'#0066FF',
'#0099CC',
'#0099FF',
'#00CC00',
'#00CC33',
'#00CC66',
'#00CC99',
'#00CCCC',
'#00CCFF',
'#3300CC',
'#3300FF',
'#3333CC',
'#3333FF',
'#3366CC',
'#3366FF',
'#3399CC',
'#3399FF',
'#33CC00',
'#33CC33',
'#33CC66',
'#33CC99',
'#33CCCC',
'#33CCFF',
'#6600CC',
'#6600FF',
'#6633CC',
'#6633FF',
'#66CC00',
'#66CC33',
'#9900CC',
'#9900FF',
'#9933CC',
'#9933FF',
'#99CC00',
'#99CC33',
'#CC0000',
'#CC0033',
'#CC0066',
'#CC0099',
'#CC00CC',
'#CC00FF',
'#CC3300',
'#CC3333',
'#CC3366',
'#CC3399',
'#CC33CC',
'#CC33FF',
'#CC6600',
'#CC6633',
'#CC9900',
'#CC9933',
'#CCCC00',
'#CCCC33',
'#FF0000',
'#FF0033',
'#FF0066',
'#FF0099',
'#FF00CC',
'#FF00FF',
'#FF3300',
'#FF3333',
'#FF3366',
'#FF3399',
'#FF33CC',
'#FF33FF',
'#FF6600',
'#FF6633',
'#FF9900',
'#FF9933',
'#FFCC00',
'#FFCC33'
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
// eslint-disable-next-line complexity
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
return true;
}
// Internet Explorer and Edge do not support colors.
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
return false;
}
// Is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
// Is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
// Is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
// Double check webkit in userAgent just in case we are in a worker
(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
args[0] = (this.useColors ? '%c' : '') +
this.namespace +
(this.useColors ? ' %c' : ' ') +
args[0] +
(this.useColors ? '%c ' : ' ') +
'+' + module.exports.humanize(this.diff);
if (!this.useColors) {
return;
}
const c = 'color: ' + this.color;
args.splice(1, 0, c, 'color: inherit');
// The final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, match => {
if (match === '%%') {
return;
}
index++;
if (match === '%c') {
// We only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.debug()` when available.
* No-op when `console.debug` is not a "function".
* If `console.debug` is not available, falls back
* to `console.log`.
*
* @api public
*/
exports.log = console.debug || console.log || (() => {});
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (namespaces) {
exports.storage.setItem('debug', namespaces);
} else {
exports.storage.removeItem('debug');
}
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
let r;
try {
r = exports.storage.getItem('debug');
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
// The Browser also has localStorage in the global context.
return localStorage;
} catch (error) {
// Swallow
// XXX (@Qix-) should we be logging these?
}
}
module.exports = require('./common')(exports);
const {formatters} = module.exports;
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
formatters.j = function (v) {
try {
return JSON.stringify(v);
} catch (error) {
return '[UnexpectedJSONParseError]: ' + error.message;
}
};
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*/
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = require('ms');
createDebug.destroy = destroy;
Object.keys(env).forEach(key => {
createDebug[key] = env[key];
});
/**
* The currently active debug mode names, and names to skip.
*/
createDebug.names = [];
createDebug.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
createDebug.formatters = {};
/**
* Selects a color for a debug namespace
* @param {String} namespace The namespace string for the debug instance to be colored
* @return {Number|String} An ANSI color code for the given namespace
* @api private
*/
function selectColor(namespace) {
let hash = 0;
for (let i = 0; i < namespace.length; i++) {
hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
hash |= 0; // Convert to 32bit integer
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
let prevTime;
let enableOverride = null;
let namespacesCache;
let enabledCache;
function debug(...args) {
// Disabled?
if (!debug.enabled) {
return;
}
const self = debug;
// Set `diff` timestamp
const curr = Number(new Date());
const ms = curr - (prevTime || curr);
self.diff = ms;
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== 'string') {
// Anything else let's inspect with %O
args.unshift('%O');
}
// Apply any `formatters` transformations
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
// If we encounter an escaped % then don't increase the array index
if (match === '%%') {
return '%';
}
index++;
const formatter = createDebug.formatters[format];
if (typeof formatter === 'function') {
const val = args[index];
match = formatter.call(self, val);
// Now we need to remove `args[index]` since it's inlined in the `format`
args.splice(index, 1);
index--;
}
return match;
});
// Apply env-specific formatting (colors, etc.)
createDebug.formatArgs.call(self, args);
const logFn = self.log || createDebug.log;
logFn.apply(self, args);
}
debug.namespace = namespace;
debug.useColors = createDebug.useColors();
debug.color = createDebug.selectColor(namespace);
debug.extend = extend;
debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
Object.defineProperty(debug, 'enabled', {
enumerable: true,
configurable: false,
get: () => {
if (enableOverride !== null) {
return enableOverride;
}
if (namespacesCache !== createDebug.namespaces) {
namespacesCache = createDebug.namespaces;
enabledCache = createDebug.enabled(namespace);
}
return enabledCache;
},
set: v => {
enableOverride = v;
}
});
// Env-specific initialization logic for debug instances
if (typeof createDebug.init === 'function') {
createDebug.init(debug);
}
return debug;
}
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.namespaces = namespaces;
createDebug.names = [];
createDebug.skips = [];
let i;
const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
const len = split.length;
for (i = 0; i < len; i++) {
if (!split[i]) {
// ignore empty strings
continue;
}
namespaces = split[i].replace(/\*/g, '.*?');
if (namespaces[0] === '-') {
createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
} else {
createDebug.names.push(new RegExp('^' + namespaces + '$'));
}
}
}
/**
* Disable debug output.
*
* @return {String} namespaces
* @api public
*/
function disable() {
const namespaces = [
...createDebug.names.map(toNamespace),
...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
].join(',');
createDebug.enable('');
return namespaces;
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
if (name[name.length - 1] === '*') {
return true;
}
let i;
let len;
for (i = 0, len = createDebug.skips.length; i < len; i++) {
if (createDebug.skips[i].test(name)) {
return false;
}
}
for (i = 0, len = createDebug.names.length; i < len; i++) {
if (createDebug.names[i].test(name)) {
return true;
}
}
return false;
}
/**
* Convert regexp to namespace
*
* @param {RegExp} regxep
* @return {String} namespace
* @api private
*/
function toNamespace(regexp) {
return regexp.toString()
.substring(2, regexp.toString().length - 2)
.replace(/\.\*\?$/, '*');
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) {
return val.stack || val.message;
}
return val;
}
/**
* XXX DO NOT USE. This is a temporary stub function.
* XXX It WILL be removed in the next major release.
*/
function destroy() {
console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
}
createDebug.enable(createDebug.load());
return createDebug;
}
module.exports = setup;
/**
* Detect Electron renderer / nwjs process, which is node, but we should
* treat as a browser.
*/
if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
module.exports = require('./browser.js');
} else {
module.exports = require('./node.js');
}
/**
* Module dependencies.
*/
const tty = require('tty');
const util = require('util');
/**
* This is the Node.js implementation of `debug()`.
*/
exports.init = init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.destroy = util.deprecate(
() => {},
'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
);
/**
* Colors.
*/
exports.colors = [6, 2, 3, 4, 5, 1];
try {
// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
// eslint-disable-next-line import/no-extraneous-dependencies
const supportsColor = require('supports-color');
if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
exports.colors = [
20,
21,
26,
27,
32,
33,
38,
39,
40,
41,
42,
43,
44,
45,
56,
57,
62,
63,
68,
69,
74,
75,
76,
77,
78,
79,
80,
81,
92,
93,
98,
99,
112,
113,
128,
129,
134,
135,
148,
149,
160,
161,
162,
163,
164,
165,
166,
167,
168,
169,
170,
171,
172,
173,
178,
179,
184,
185,
196,
197,
198,
199,
200,
201,
202,
203,
204,
205,
206,
207,
208,
209,
214,
215,
220,
221
];
}
} catch (error) {
// Swallow - we only care if `supports-color` is available; it doesn't have to be.
}
/**
* Build up the default `inspectOpts` object from the environment variables.
*
* $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
*/
exports.inspectOpts = Object.keys(process.env).filter(key => {
return /^debug_/i.test(key);
}).reduce((obj, key) => {
// Camel-case
const prop = key
.substring(6)
.toLowerCase()
.replace(/_([a-z])/g, (_, k) => {
return k.toUpperCase();
});
// Coerce string value into JS value
let val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) {
val = true;
} else if (/^(no|off|false|disabled)$/i.test(val)) {
val = false;
} else if (val === 'null') {
val = null;
} else {
val = Number(val);
}
obj[prop] = val;
return obj;
}, {});
/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/
function useColors() {
return 'colors' in exports.inspectOpts ?
Boolean(exports.inspectOpts.colors) :
tty.isatty(process.stderr.fd);
}
/**
* Adds ANSI color escape codes if enabled.
*
* @api public
*/
function formatArgs(args) {
const {namespace: name, useColors} = this;
if (useColors) {
const c = this.color;
const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
const prefix = ` ${colorCode};1m${name} \u001B[0m`;
args[0] = prefix + args[0].split('\n').join('\n' + prefix);
args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
} else {
args[0] = getDate() + name + ' ' + args[0];
}
}
function getDate() {
if (exports.inspectOpts.hideDate) {
return '';
}
return new Date().toISOString() + ' ';
}
/**
* Invokes `util.format()` with the specified arguments and writes to stderr.
*/
function log(...args) {
return process.stderr.write(util.format(...args) + '\n');
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
if (namespaces) {
process.env.DEBUG = namespaces;
} else {
// If you set a process.env field to null or undefined, it gets cast to the
// string 'null' or 'undefined'. Just delete instead.
delete process.env.DEBUG;
}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
return process.env.DEBUG;
}
/**
* Init logic for `debug` instances.
*
* Create a new `inspectOpts` object in case `useColors` is set
* differently for a particular `debug` instance.
*/
function init(debug) {
debug.inspectOpts = {};
const keys = Object.keys(exports.inspectOpts);
for (let i = 0; i < keys.length; i++) {
debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
}
}
module.exports = require('./common')(exports);
const {formatters} = module.exports;
/**
* Map %o to `util.inspect()`, all on a single line.
*/
formatters.o = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts)
.split('\n')
.map(str => str.trim())
.join(' ');
};
/**
* Map %O to `util.inspect()`, allowing multiple lines if needed.
*/
formatters.O = function (v) {
this.inspectOpts.colors = this.useColors;
return util.inspect(v, this.inspectOpts);
};
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var w = d * 7;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @param {String|Number} val
* @param {Object} [options]
* @throws {Error} throw an error if val is not a non-empty string or a number
* @return {String|Number}
* @api public
*/
module.exports = function(val, options) {
options = options || {};
var type = typeof val;
if (type === 'string' && val.length > 0) {
return parse(val);
} else if (type === 'number' && isFinite(val)) {
return options.long ? fmtLong(val) : fmtShort(val);
}
throw new Error(
'val is not a non-empty string or a valid number. val=' +
JSON.stringify(val)
);
};
/**
* Parse the given `str` and return milliseconds.
*
* @param {String} str
* @return {Number}
* @api private
*/
function parse(str) {
str = String(str);
if (str.length > 100) {
return;
}
var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
str
);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'yrs':
case 'yr':
case 'y':
return n * y;
case 'weeks':
case 'week':
case 'w':
return n * w;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'hrs':
case 'hr':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'mins':
case 'min':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 'secs':
case 'sec':
case 's':
return n * s;
case 'milliseconds':
case 'millisecond':
case 'msecs':
case 'msec':
case 'ms':
return n;
default:
return undefined;
}
}
/**
* Short format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtShort(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return Math.round(ms / d) + 'd';
}
if (msAbs >= h) {
return Math.round(ms / h) + 'h';
}
if (msAbs >= m) {
return Math.round(ms / m) + 'm';
}
if (msAbs >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @param {Number} ms
* @return {String}
* @api private
*/
function fmtLong(ms) {
var msAbs = Math.abs(ms);
if (msAbs >= d) {
return plural(ms, msAbs, d, 'day');
}
if (msAbs >= h) {
return plural(ms, msAbs, h, 'hour');
}
if (msAbs >= m) {
return plural(ms, msAbs, m, 'minute');
}
if (msAbs >= s) {
return plural(ms, msAbs, s, 'second');
}
return ms + ' ms';
}
/**
* Pluralization helper.
*/
function plural(ms, msAbs, n, name) {
var isPlural = msAbs >= n * 1.5;
return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment